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;
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)
54 // FIXME: Consume fuel
57 ControlMap* Airplane::getControlMap()
62 Model* Airplane::getModel()
67 void Airplane::getPilotAccel(float* out)
69 State* s = _model.getState();
72 Glue::geodUp(s->pos, out);
73 Math::mul3(-9.8, out, out);
75 // The regular acceleration
77 Math::mul3(-1, s->acc, tmp);
78 Math::add3(tmp, out, out);
80 // Convert to aircraft coordinates
81 Math::vmul33(s->orient, out, out);
83 // FIXME: rotational & centripetal acceleration needed
86 void Airplane::setPilotPos(float* pos)
88 for(int i=0; i<3; i++) _pilotPos[i] = pos[i];
91 void Airplane::getPilotPos(float* out)
93 for(int i=0; i<3; i++) out[i] = _pilotPos[i];
96 int Airplane::numGear()
101 Gear* Airplane::getGear(int g)
103 return ((GearRec*)_gears.get(g))->gear;
106 void Airplane::setGearState(bool down, float dt)
108 for(int i=0; i<_gears.size(); i++) {
109 GearRec* gr = (GearRec*)_gears.get(i);
112 gr->gear->setExtension(1);
113 gr->surf->setXDrag(1);
114 gr->surf->setYDrag(1);
115 gr->surf->setZDrag(1);
119 float diff = dt / gr->time;
120 if(!down) diff = -diff;
121 float ext = gr->gear->getExtension() + diff;
125 gr->gear->setExtension(ext);
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::addApproachControl(int control, float val)
157 Control* c = new Control();
158 c->control = control;
160 _approachControls.add(c);
163 void Airplane::addCruiseControl(int control, float val)
165 Control* c = new Control();
166 c->control = control;
168 _cruiseControls.add(c);
171 int Airplane::numTanks()
173 return _tanks.size();
176 float Airplane::getFuel(int tank)
178 return ((Tank*)_tanks.get(tank))->fill;
181 float Airplane::getFuelDensity(int tank)
183 return ((Tank*)_tanks.get(tank))->density;
186 void Airplane::setWeight(float weight)
188 _emptyWeight = weight;
191 void Airplane::setWing(Wing* wing)
196 void Airplane::setTail(Wing* tail)
201 void Airplane::addVStab(Wing* vstab)
206 void Airplane::addFuselage(float* front, float* back, float width)
208 Fuselage* f = new Fuselage();
209 for(int i=0; i<3; i++) {
210 f->front[i] = front[i];
211 f->back[i] = back[i];
217 int Airplane::addTank(float* pos, float cap, float density)
219 Tank* t = new Tank();
220 for(int i=0; i<3; i++) t->pos[i] = pos[i];
223 t->density = density;
224 t->handle = 0xffffffff;
225 return _tanks.add(t);
228 void Airplane::addGear(Gear* gear, float transitionTime)
230 GearRec* g = new GearRec();
233 g->time = transitionTime;
237 void Airplane::addThruster(Thruster* thruster, float mass, float* cg)
239 ThrustRec* t = new ThrustRec();
240 t->thruster = thruster;
242 for(int i=0; i<3; i++) t->cg[i] = cg[i];
246 void Airplane::addBallast(float* pos, float mass)
248 _model.getBody()->addMass(mass, pos);
252 int Airplane::addWeight(float* pos, float size)
254 WeightRec* wr = new WeightRec();
255 wr->handle = _model.getBody()->addMass(0, pos);
257 wr->surf = new Surface();
258 wr->surf->setPosition(pos);
259 wr->surf->setTotalDrag(size*size);
260 _model.addSurface(wr->surf);
261 _surfs.add(wr->surf);
263 return _weights.add(wr);
266 void Airplane::setWeight(int handle, float mass)
268 WeightRec* wr = (WeightRec*)_weights.get(handle);
270 _model.getBody()->setMass(wr->handle, mass);
272 // Kill the aerodynamic drag if the mass is exactly zero. This is
273 // how we simulate droppable stores.
275 wr->surf->setXDrag(0);
276 wr->surf->setYDrag(0);
277 wr->surf->setZDrag(0);
279 wr->surf->setXDrag(1);
280 wr->surf->setYDrag(1);
281 wr->surf->setZDrag(1);
285 void Airplane::setFuelFraction(float frac)
287 for(int 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;
333 for(int i=0; i<3; i++)
334 s->pos[i] = s->rot[i] = s->acc[i] = s->racc[i] = 0;
336 // Put us 1m above the origin, or else the gravity computation in
341 float Airplane::compileWing(Wing* w)
343 // Make sure it's initialized. The surfaces will pop out with
344 // total drag coefficients equal to their areas, which is what we
349 for(int i=0; i<w->numSurfaces(); i++) {
350 Surface* s = (Surface*)w->getSurface(i);
351 _model.addSurface(s);
355 _model.getBody()->addMass(w->getSurfaceWeight(i), pos);
356 wgt += w->getSurfaceWeight(i);
361 float Airplane::compileFuselage(Fuselage* f)
365 Math::sub3(f->front, f->back, fwd);
366 float len = Math::mag3(fwd);
367 float wid = f->width;
368 int segs = (int)Math::ceil(len/wid);
369 float segWgt = len*wid/segs;
370 for(int j=0; j<segs; j++) {
371 float frac = (j+0.5) / segs;
373 Math::mul3(frac, fwd, pos);
374 Math::add3(f->back, pos, pos);
375 _model.getBody()->addMass(segWgt, pos);
378 // Make a Surface too
379 Surface* s = new Surface();
381 float sideDrag = len/wid;
382 s->setYDrag(sideDrag);
383 s->setZDrag(sideDrag);
384 s->setTotalDrag(segWgt);
386 // FIXME: fails for fuselages aligned along the Y axis
388 float *x=o, *y=o+3, *z=o+6; // nicknames for the axes
390 y[0] = 0; y[1] = 1; y[2] = 0;
391 Math::cross3(x, y, z);
392 s->setOrientation(o);
394 _model.addSurface(s);
400 // FIXME: should probably add a mass for the gear, too
401 void Airplane::compileGear(GearRec* gr)
405 // Make a Surface object for the aerodynamic behavior
406 Surface* s = new Surface();
409 // Put the surface at the half-way point on the gear strut, give
410 // it a drag coefficient equal to a square of the same dimension
411 // (gear are really draggy) and make it symmetric. Assume that
412 // the "length" of the gear is 3x the compression distance
413 float pos[3], cmp[3];
414 g->getCompression(cmp);
415 float length = 3 * Math::mag3(cmp);
417 Math::mul3(0.5, cmp, cmp);
418 Math::add3(pos, cmp, pos);
421 s->setTotalDrag(length*length);
424 _model.addSurface(s);
428 void Airplane::compile()
431 ground[0] = 0; ground[1] = 0; ground[2] = 1;
432 _model.setGroundPlane(ground, -100000);
434 RigidBody* body = _model.getBody();
435 int firstMass = body->numMasses();
437 // Generate the point masses for the plane. Just use unitless
438 // numbers for a first pass, then go back through and rescale to
439 // make the weight right.
443 aeroWgt += compileWing(_wing);
444 aeroWgt += compileWing(_tail);
445 for(int i=0; i<_vstabs.size(); i++) {
446 aeroWgt += compileWing((Wing*)_vstabs.get(i));
450 for(int i=0; i<_fuselages.size(); i++) {
451 aeroWgt += compileFuselage((Fuselage*)_fuselages.get(i));
454 // Count up the absolute weight we have
455 float nonAeroWgt = _ballast;
456 for(int i=0; i<_thrusters.size(); i++)
457 nonAeroWgt += ((ThrustRec*)_thrusters.get(i))->mass;
459 // Rescale to the specified empty weight
460 float wscale = (_emptyWeight-nonAeroWgt)/aeroWgt;
461 for(int i=firstMass; i<body->numMasses(); i++)
462 body->setMass(i, body->getMass(i)*wscale);
464 // Add the thruster masses
465 for(int i=0; i<_thrusters.size(); i++) {
466 ThrustRec* t = (ThrustRec*)_thrusters.get(i);
467 body->addMass(t->mass, t->cg);
470 // Add the tanks, empty for now.
472 for(int i=0; i<_tanks.size(); i++) {
473 Tank* t = (Tank*)_tanks.get(i);
474 t->handle = body->addMass(0, t->pos);
477 _cruiseWeight = _emptyWeight + totalFuel*0.5;
478 _approachWeight = _emptyWeight + totalFuel*0.2;
482 // Add surfaces for the landing gear.
483 for(int i=0; i<_gears.size(); i++)
484 compileGear((GearRec*)_gears.get(i));
486 // The Thruster objects
487 for(int i=0; i<_thrusters.size(); i++) {
488 ThrustRec* tr = (ThrustRec*)_thrusters.get(i);
489 tr->handle = _model.addThruster(tr->thruster);
494 float gespan = _wing->getGroundEffect(gepos);
495 _model.setGroundEffect(gepos, gespan, .3);
500 // Drop the gear (use a really big dt)
501 setGearState(true, 1000000);
504 void Airplane::solveGear()
507 _model.getBody()->getCG(cg);
509 // Calculate spring constant weightings for the gear. Weight by
510 // the inverse of the distance to the c.g. in the XY plane, which
511 // should be correct for most gear arrangements. Add 50cm of
512 // "buffer" to keep things from blowing up with aircraft with a
513 // single gear very near the c.g. (AV-8, for example).
515 for(int i=0; i<_gears.size(); i++) {
516 GearRec* gr = (GearRec*)_gears.get(i);
519 Math::sub3(cg, pos, pos);
520 gr->wgt = 1/(0.5+Math::sqrt(pos[0]*pos[0] + pos[1]*pos[1]));
524 // Renormalize so they sum to 1
525 for(int i=0; i<_gears.size(); i++)
526 ((GearRec*)_gears.get(i))->wgt /= total;
528 // The force at max compression should be sufficient to stop a
529 // plane moving downwards at 3x the approach descent rate. Assume
530 // a 3 degree approach.
531 float descentRate = 3*_approachSpeed/19.1;
533 // Spread the kinetic energy according to the gear weights. This
534 // will results in an equal compression fraction (not distance) of
536 float energy = 0.5*_approachWeight*descentRate*descentRate;
538 for(int i=0; i<_gears.size(); i++) {
539 GearRec* gr = (GearRec*)_gears.get(i);
540 float e = energy * gr->wgt;
542 gr->gear->getCompression(comp);
543 float len = Math::mag3(comp);
545 // Energy in a spring: e = 0.5 * k * len^2
546 float k = 2 * e / (len*len);
548 gr->gear->setSpring(k);
550 // Critically damped (too damped, too!)
551 gr->gear->setDamping(2*Math::sqrt(k*_approachWeight*gr->wgt));
553 // These are pretty generic
554 gr->gear->setStaticFriction(0.8);
555 gr->gear->setDynamicFriction(0.7);
559 void Airplane::stabilizeThrust()
561 for(int i=0; i<_thrusters.size(); i++)
562 _model.getThruster(i)->stabilize();
565 void Airplane::runCruise()
567 setupState(_cruiseAoA, _cruiseSpeed, &_cruiseState);
568 _model.setState(&_cruiseState);
569 _model.setAir(_cruiseP, _cruiseT);
571 // The control configuration
573 for(int i=0; i<_cruiseControls.size(); i++) {
574 Control* c = (Control*)_cruiseControls.get(i);
575 _controls.setInput(c->control, c->val);
577 _controls.applyControls();
581 Math::mul3(-1, _cruiseState.v, wind);
582 Math::vmul33(_cruiseState.orient, wind, wind);
584 // Gear are up (if they're non-retractable, this is a noop)
585 setGearState(false, 100000);
587 // Cruise is by convention at 50% tank capacity
588 setFuelFraction(0.5);
590 // Set up the thruster parameters and iterate until the thrust
592 for(int i=0; i<_thrusters.size(); i++) {
593 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
595 t->setAir(_cruiseP, _cruiseT);
599 // Precompute thrust in the model, and calculate aerodynamic forces
600 _model.getBody()->reset();
601 _model.initIteration();
602 _model.calcForces(&_cruiseState);
605 void Airplane::runApproach()
607 setupState(_approachAoA, _approachSpeed, &_approachState);
608 _model.setState(&_approachState);
609 _model.setAir(_approachP, _approachT);
611 // The control configuration
613 for(int i=0; i<_approachControls.size(); i++) {
614 Control* c = (Control*)_approachControls.get(i);
615 _controls.setInput(c->control, c->val);
617 _controls.applyControls();
621 Math::mul3(-1, _approachState.v, wind);
622 Math::vmul33(_approachState.orient, wind, wind);
624 // Approach is by convention at 20% tank capacity
625 setFuelFraction(0.2);
628 setGearState(true, 100000);
630 // Run the thrusters until they get to a stable setting. FIXME:
631 // this is lots of wasted work.
632 for(int i=0; i<_thrusters.size(); i++) {
633 Thruster* t = ((ThrustRec*)_thrusters.get(i))->thruster;
635 t->setAir(_approachP, _approachT);
639 // Precompute thrust in the model, and calculate aerodynamic forces
640 _model.getBody()->reset();
641 _model.initIteration();
642 _model.calcForces(&_approachState);
645 void Airplane::applyDragFactor(float factor)
647 float applied = Math::sqrt(factor);
648 _dragFactor *= applied;
649 _wing->setDragScale(_wing->getDragScale() * applied);
650 _tail->setDragScale(_tail->getDragScale() * applied);
651 for(int i=0; i<_vstabs.size(); i++) {
652 Wing* w = (Wing*)_vstabs.get(i);
653 w->setDragScale(w->getDragScale() * applied);
655 for(int i=0; i<_surfs.size(); i++) {
656 Surface* s = (Surface*)_surfs.get(i);
657 s->setTotalDrag(s->getTotalDrag() * applied);
661 void Airplane::applyLiftRatio(float factor)
663 float applied = Math::sqrt(factor);
664 _liftRatio *= applied;
665 _wing->setLiftRatio(_wing->getLiftRatio() * applied);
666 _tail->setLiftRatio(_tail->getLiftRatio() * applied);
667 for(int i=0; i<_vstabs.size(); i++) {
668 Wing* w = (Wing*)_vstabs.get(i);
669 w->setLiftRatio(w->getLiftRatio() * applied);
673 float Airplane::clamp(float val, float min, float max)
675 if(val < min) return min;
676 if(val > max) return max;
680 float Airplane::normFactor(float f)
687 void Airplane::solve()
689 static const float ARCMIN = 0.0002909;
692 _solutionIterations = 0;
695 if(_solutionIterations++ > 10000) {
696 _failureMsg = "Solution failed to converge after 10000 iterations";
700 // Run an iteration at cruise, and extract the needed numbers:
703 _model.getThrust(tmp);
704 float thrust = tmp[0];
706 _model.getBody()->getAccel(tmp);
707 float xforce = _cruiseWeight * tmp[0];
708 float clift0 = _cruiseWeight * tmp[2];
710 _model.getBody()->getAngularAccel(tmp);
711 float pitch0 = tmp[1];
713 // Run an approach iteration, and do likewise
716 _model.getBody()->getAccel(tmp);
717 float alift = _approachWeight * tmp[2];
719 // Modify the cruise AoA a bit to get a derivative
720 _cruiseAoA += ARCMIN;
722 _cruiseAoA -= ARCMIN;
724 _model.getBody()->getAccel(tmp);
725 float clift1 = _cruiseWeight * tmp[2];
727 // Do the same with the tail incidence
728 _tail->setIncidence(_tailIncidence + ARCMIN);
730 _tail->setIncidence(_tailIncidence);
732 _model.getBody()->getAngularAccel(tmp);
733 float pitch1 = tmp[1];
736 float awgt = 9.8 * _approachWeight;
738 float dragFactor = thrust / (thrust-xforce);
739 float liftFactor = awgt / (awgt+alift);
740 float aoaDelta = -clift0 * (ARCMIN/(clift1-clift0));
741 float tailDelta = -pitch0 * (ARCMIN/(pitch1-pitch0));
744 if(dragFactor <= 0) {
745 _failureMsg = "Zero or negative drag adjustment.";
747 } else if(liftFactor <= 0) {
748 _failureMsg = "Zero or negative lift adjustment.";
753 applyDragFactor(dragFactor);
754 applyLiftRatio(liftFactor);
756 // DON'T do the following until the above are sane
757 if(normFactor(dragFactor) > 1.1
758 || normFactor(liftFactor) > 1.1)
763 // OK, now we can adjust the minor variables
764 _cruiseAoA += 0.5*aoaDelta;
765 _tailIncidence += 0.5*tailDelta;
767 _cruiseAoA = clamp(_cruiseAoA, -.174, .174);
768 _tailIncidence = clamp(_tailIncidence, -.174, .174);
770 if(dragFactor < 1.00001 && liftFactor < 1.00001 &&
771 aoaDelta < .000017 && tailDelta < .000017)
777 if(_dragFactor < 1e-06 || _dragFactor > 1e6) {
778 _failureMsg = "Drag factor beyond reasonable bounds.";
780 } else if(_liftRatio < 1e-04 || _liftRatio > 1e4) {
781 _failureMsg = "Lift ratio beyond reasonable bounds.";
783 } else if(Math::abs(_cruiseAoA) >= .174) {
784 _failureMsg = "Cruise AoA > 10 degrees";
786 } else if(Math::abs(_tailIncidence) >= .174) {
787 _failureMsg = "Tail incidence > 10 degrees";
791 }; // namespace yasim