]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
Fix apparently ancient typo.
[flightgear.git] / src / FDM / YASim / YASim.cxx
1
2 #ifdef HAVE_CONFIG_H
3 #  include "config.h"
4 #endif
5
6 #include <simgear/debug/logstream.hxx>
7 #include <simgear/math/sg_geodesy.hxx>
8 #include <simgear/misc/sg_path.hxx>
9 #include <simgear/scene/model/placement.hxx>
10 #include <simgear/xml/easyxml.hxx>
11
12 #include <Main/globals.hxx>
13 #include <Main/fg_props.hxx>
14
15 #include "FGFDM.hpp"
16 #include "Atmosphere.hpp"
17 #include "Math.hpp"
18 #include "Airplane.hpp"
19 #include "Model.hpp"
20 #include "Integrator.hpp"
21 #include "Glue.hpp"
22 #include "Gear.hpp"
23 #include "Hook.hpp"
24 #include "Launchbar.hpp"
25 #include "FGGround.hpp"
26 #include "PropEngine.hpp"
27 #include "PistonEngine.hpp"
28
29 #include "YASim.hxx"
30
31 using namespace yasim;
32
33 static const float YASIM_PI = 3.14159265358979323846;
34 static const float RAD2DEG = 180/YASIM_PI;
35 static const float PI2 = YASIM_PI*2;
36 static const float RAD2RPM = 9.54929658551;
37 static const float M2FT = 3.2808399;
38 static const float FT2M = 0.3048;
39 static const float MPS2KTS = 3600.0/1852.0;
40 static const float CM2GALS = 264.172037284; // gallons/cubic meter
41 static const float KG2LBS = 2.20462262185;
42 static const float W2HP = 1.3416e-3;
43 static const float INHG2PA = 3386.389;
44 static const float SLUG2KG = 14.59390;
45
46 YASim::YASim(double dt)
47 {
48 //     set_delta_t(dt);
49     _fdm = new FGFDM();
50
51     _dt = dt;
52
53     _fdm->getAirplane()->getModel()->setGroundCallback( new FGGround(this) );
54     _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
55 }
56
57 YASim::~YASim()
58 {
59     delete _fdm;
60 }
61
62 void YASim::report()
63 {
64     Airplane* a = _fdm->getAirplane();
65
66     float aoa = a->getCruiseAoA() * RAD2DEG;
67     float tail = -1 * a->getTailIncidence() * RAD2DEG;
68     float drag = 1000 * a->getDragCoefficient();
69
70     SG_LOG(SG_FLIGHT,SG_INFO,"YASim solution results:");
71     SG_LOG(SG_FLIGHT,SG_INFO,"       Iterations: "<<a->getSolutionIterations());
72     SG_LOG(SG_FLIGHT,SG_INFO," Drag Coefficient: "<< drag);
73     SG_LOG(SG_FLIGHT,SG_INFO,"       Lift Ratio: "<<a->getLiftRatio());
74     SG_LOG(SG_FLIGHT,SG_INFO,"       Cruise AoA: "<< aoa);
75     SG_LOG(SG_FLIGHT,SG_INFO,"   Tail Incidence: "<< tail);
76     SG_LOG(SG_FLIGHT,SG_INFO,"Approach Elevator: "<<a->getApproachElevator());
77     
78
79     float cg[3];
80     char buf[256];
81     a->getModel()->getBody()->getCG(cg);
82     sprintf(buf, "            CG: %.3f, %.3f, %.3f", cg[0], cg[1], cg[2]);
83     SG_LOG(SG_FLIGHT, SG_INFO, buf);
84
85     if(a->getFailureMsg()) {
86         SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
87         SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
88         exit(1);
89     }
90 }
91
92 void YASim::bind()
93 {
94     // Run the superclass bind to set up a bunch of property ties
95     FGInterface::bind();
96
97     // Now UNtie the ones that we are going to set ourselves.
98     fgUntie("/consumables/fuel/tank[0]/level-gal_us");
99     fgUntie("/consumables/fuel/tank[1]/level-gal_us");
100
101     char buf[256];
102     for(int i=0; i<_fdm->getAirplane()->getModel()->numThrusters(); i++) {
103         sprintf(buf, "/engines/engine[%d]/fuel-flow-gph", i);        fgUntie(buf);
104         sprintf(buf, "/engines/engine[%d]/rpm", i);                  fgUntie(buf);
105         sprintf(buf, "/engines/engine[%d]/mp-osi", i);               fgUntie(buf);
106         sprintf(buf, "/engines/engine[%d]/egt-degf", i);             fgUntie(buf);
107         sprintf(buf, "/engines/engine[%d]/oil-temperature-degf", i); fgUntie(buf);
108     }
109 }
110
111 void YASim::init()
112 {
113     Airplane* a = _fdm->getAirplane();
114     Model* m = a->getModel();
115
116     // Superclass hook
117     common_init();
118
119     m->setCrashed(false);
120
121     // Figure out the initial speed type
122     string speed_set = fgGetString("/sim/presets/speed-set", "UVW");
123     if (speed_set == "NED")
124         _speed_set = NED;
125     else if (speed_set == "UVW")
126         _speed_set = UVW;
127     else if (speed_set == "knots")
128         _speed_set = KNOTS;
129     else if (speed_set == "mach")
130         _speed_set = MACH;
131     else {
132         _speed_set = UVW;
133         SG_LOG(SG_FLIGHT, SG_ALERT, "Unknown speed type " << speed_set);
134     }
135
136     // Build a filename and parse it
137     SGPath f(fgGetString("/sim/aircraft-dir"));
138     f.append(fgGetString("/sim/aero"));
139     f.concat(".xml");
140     readXML(f.str(), *_fdm);
141
142     // Compile it into a real airplane, and tell the user what they got
143     a->compile();
144     report();
145
146     _fdm->init();
147
148     // Create some FG{Eng|Gear}Interface objects
149     int i;
150     for(i=0; i<a->numGear(); i++) {
151         Gear* g = a->getGear(i);
152         SGPropertyNode * node = fgGetNode("gear/gear", i, true);
153         float pos[3];
154         g->getPosition(pos);
155         node->setDoubleValue("xoffset-in", pos[0] * M2FT * 12);
156         node->setDoubleValue("yoffset-in", pos[1] * M2FT * 12);
157         node->setDoubleValue("zoffset-in", pos[2] * M2FT * 12);
158     }
159
160     // Are we at ground level?  If so, lift the plane up so the gear
161     // clear the ground.
162     double runway_altitude = get_Runway_altitude();
163     if(get_Altitude() - runway_altitude < 50) {
164         fgSetBool("/controls/gear/gear-down", false);
165         float minGearZ = 1e18;
166         for(i=0; i<a->numGear(); i++) {
167             Gear* g = a->getGear(i);
168             float pos[3];
169             g->getPosition(pos);
170             if(pos[2] < minGearZ)
171                 minGearZ = pos[2];
172         }
173         _set_Altitude(runway_altitude - minGearZ*M2FT);
174         fgSetBool("/controls/gear/gear-down", true);
175     }
176
177     // Blank the state, and copy in ours
178     State s;
179     m->setState(&s);
180     copyToYASim(true);
181
182     _fdm->getExternalInput();
183     _fdm->getAirplane()->initEngines();
184
185     set_inited(true);
186 }
187
188 void YASim::update(double dt)
189 {
190     if (is_suspended())
191         return;
192
193     int iterations = _calc_multiloop(dt);
194
195     // If we're crashed, then we don't care
196     if(_fdm->getAirplane()->getModel()->isCrashed()) {
197         if(!fgGetBool("/sim/crashed"))
198             fgSetBool("/sim/crashed", true);
199         return;
200     }
201
202     // ground.  Calculate a cartesian coordinate for the ground under
203     // us, find the (geodetic) up vector normal to the ground, then
204     // use that to find the final (radius) term of the plane equation.
205     float v[3] = { get_uBody(), get_vBody(), get_wBody() };
206     float lat = get_Latitude(); float lon = get_Longitude();
207     float alt = get_Altitude() * FT2M; double xyz[3];
208     sgGeodToCart(lat, lon, alt, xyz);
209     // build the environment cache.
210     float vr = _fdm->getVehicleRadius();
211     vr += 2.0*FT2M*dt*Math::mag3(v);
212     prepare_ground_cache_m( 0.0, xyz, vr );
213
214     // Track time increments.
215     FGGround* gr
216       = (FGGround*)_fdm->getAirplane()->getModel()->getGroundCallback();
217
218     int i;
219     for(i=0; i<iterations; i++) {
220         gr->setTimeOffset(i*_dt);
221         copyToYASim(false);
222         _fdm->iterate(_dt);
223         copyFromYASim();
224     }
225
226     // Reset the time increment.
227     gr->setTimeOffset(0.0);
228 }
229
230 void YASim::copyToYASim(bool copyState)
231 {
232     // Physical state
233     double lat = get_Latitude();
234     double lon = get_Longitude();
235     float alt = get_Altitude() * FT2M;
236     float roll = get_Phi();
237     float pitch = get_Theta();
238     float hdg = get_Psi();
239
240     // Environment
241     float wind[3];
242     wind[0] = get_V_north_airmass() * FT2M * -1.0;
243     wind[1] = get_V_east_airmass() * FT2M * -1.0;
244     wind[2] = get_V_down_airmass() * FT2M * -1.0;
245
246     float pressure = fgGetFloat("/environment/pressure-inhg") * INHG2PA;
247     float temp = fgGetFloat("/environment/temperature-degc") + 273.15;
248     float dens = fgGetFloat("/environment/density-slugft3") 
249         * SLUG2KG * M2FT*M2FT*M2FT;
250
251     // Convert and set:
252     Model* model = _fdm->getAirplane()->getModel();
253     State s;
254     float xyz2ned[9];
255     Glue::xyz2nedMat(lat, lon, xyz2ned);
256
257     // position
258     sgGeodToCart(lat, lon, alt, s.pos);
259
260     // orientation
261     Glue::euler2orient(roll, pitch, hdg, s.orient);
262     Math::mmul33(s.orient, xyz2ned, s.orient);
263
264     // Velocity
265     string speed_set = fgGetString("/sim/presets/speed-set", "UVW");
266     float v[3];
267     bool needCopy = false;
268     switch (_speed_set) {
269     case NED:
270         v[0] = get_V_north() * FT2M * -1.0;
271         v[1] = get_V_east() * FT2M * -1.0;
272         v[2] = get_V_down() * FT2M * -1.0;
273         break;
274     case UVW:
275         v[0] = get_uBody() * FT2M;
276         v[1] = get_vBody() * FT2M;
277         v[2] = get_wBody() * FT2M;
278         Math::tmul33(s.orient, v, v);
279         break;
280     case KNOTS:
281         v[0] = Atmosphere::spdFromVCAS(get_V_calibrated_kts()/MPS2KTS,
282                                        pressure, temp);
283         v[1] = 0;
284         v[2] = 0;
285         Math::tmul33(s.orient, v, v);
286         needCopy = true;
287         break;
288     case MACH:
289         v[0] = Atmosphere::spdFromMach(get_Mach_number(), temp);
290         v[1] = 0;
291         v[2] = 0;
292         Math::tmul33(s.orient, v, v);
293         needCopy = true;
294         break;
295     default:
296         v[0] = 0;
297         v[1] = 0;
298         v[2] = 0;
299         break;
300     }
301     if (!copyState)
302         _speed_set = UVW;       // change to this after initial setting
303     Math::set3(v, s.v);
304
305     if(copyState || needCopy)
306         model->setState(&s);
307
308     // wind
309     Math::tmul33(xyz2ned, wind, wind);
310     model->setWind(wind);
311
312     // air
313     model->setAir(pressure, temp, dens);
314
315     // Query a ground plane for each gear/hook/launchbar and
316     // write that value into the corresponding class.
317     _fdm->getAirplane()->getModel()->updateGround(&s);
318
319     Launchbar* l = model->getLaunchbar();
320     if (l)
321         l->setLaunchCmd(0.0<fgGetFloat("/controls/gear/catapult-launch-cmd"));
322 }
323
324 // All the settables:
325 //
326 // These are set below:
327 // _set_Accels_Local
328 // _set_Accels_Body
329 // _set_Accels_CG_Body 
330 // _set_Accels_Pilot_Body
331 // _set_Accels_CG_Body_N 
332 // _set_Velocities_Local
333 // _set_Velocities_Ground
334 // _set_Velocities_Wind_Body
335 // _set_Omega_Body
336 // _set_Euler_Rates
337 // _set_Euler_Angles
338 // _set_V_rel_wind
339 // _set_V_ground_speed
340 // _set_V_equiv_kts
341 // _set_V_calibrated_kts
342 // _set_Alpha
343 // _set_Beta
344 // _set_Mach_number
345 // _set_Climb_Rate
346 // _set_Tank1Fuel
347 // _set_Tank2Fuel
348 // _set_Altitude_AGL
349 // _set_Geodetic_Position
350 // _set_Runway_altitude
351
352 // Ignoring these, because they're unused:
353 // _set_Geocentric_Position
354 // _set_Geocentric_Rates
355 // _set_Cos_phi
356 // _set_Cos_theta
357 // _set_Earth_position_angle (WTF?)
358 // _set_Gamma_vert_rad
359 // _set_Inertias
360 // _set_T_Local_to_Body
361 // _set_CG_Position
362 // _set_Sea_Level_Radius
363
364 // Externally set via the weather code:
365 // _set_Velocities_Local_Airmass
366 // _set_Density
367 // _set_Static_pressure
368 // _set_Static_temperature
369 void YASim::copyFromYASim()
370 {
371     Airplane* airplane = _fdm->getAirplane();
372     Model* model = airplane->getModel();
373     State* s = model->getState();
374
375     // position
376     double lat, lon, alt;
377     sgCartToGeod(s->pos, &lat, &lon, &alt);
378     _set_Geodetic_Position(lat, lon, alt*M2FT);
379     double groundlevel_m = get_groundlevel_m(lat, lon, alt);
380     _set_Runway_altitude(groundlevel_m*SG_METER_TO_FEET);
381     _set_Altitude_AGL((alt-groundlevel_m)*SG_METER_TO_FEET);
382
383     // the smallest agl of all gears
384     fgSetFloat("/position/gear-agl-m", model->getAGL());
385     fgSetFloat("/position/gear-agl-ft", model->getAGL()*M2FT);
386
387     // UNUSED
388     //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
389
390     // useful conversion matrix
391     float xyz2ned[9];
392     Glue::xyz2nedMat(lat, lon, xyz2ned);
393
394     // velocity
395     float v[3];
396     Math::vmul33(xyz2ned, s->v, v);
397     _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
398     _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
399                                    M2FT*v[1]*M2FT*v[1]));
400     _set_Climb_Rate(-M2FT*v[2]);
401
402     // The HUD uses this, but inverts down (?!)
403     _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
404
405     // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
406
407     // Airflow velocity.
408     float wind[3];
409     wind[0] = get_V_north_airmass() * FT2M * -1.0;  // Wind in NED
410     wind[1] = get_V_east_airmass() * FT2M * -1.0;
411     wind[2] = get_V_down_airmass() * FT2M * -1.0;
412     Math::tmul33(xyz2ned, wind, wind);              // Wind in global
413     Math::sub3(s->v, wind, v);                      // V - wind in global
414     Math::vmul33(s->orient, v, v);               // to body coordinates
415     _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
416     _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
417
418     float P = fgGetDouble("/environment/pressure-inhg") * INHG2PA;
419     float T = fgGetDouble("/environment/temperature-degc") + 273.15;
420     float D = fgGetFloat("/environment/density-slugft3")
421         *SLUG2KG * M2FT*M2FT*M2FT;
422     _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T, D)*MPS2KTS);
423     _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
424     _set_Mach_number(Atmosphere::calcMach(v[0], T));
425
426     // acceleration
427     Math::vmul33(xyz2ned, s->acc, v);
428     _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
429
430     Math::vmul33(s->orient, s->acc, v);
431     _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
432     _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
433
434     _fdm->getAirplane()->getPilotAccel(v);
435     _set_Accels_Pilot_Body(-M2FT*v[0], M2FT*v[1], M2FT*v[2]);
436
437     // There is no property for pilot G's, but I need it for a panel
438     // instrument.  Hack this in here, and REMOVE IT WHEN IT FINDS A
439     // REAL HOME!
440     fgSetFloat("/accelerations/pilot-g", -v[2]/9.8);
441
442     // The one appears (!) to want inverted pilot acceleration
443     // numbers, in G's...
444     Math::mul3(1.0/9.8, v, v);
445     _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
446
447     // orientation
448     float alpha, beta;
449     Glue::calcAlphaBeta(s, wind, &alpha, &beta);
450     _set_Alpha(alpha);
451     _set_Beta(beta);
452
453     float tmp[9];
454     Math::trans33(xyz2ned, tmp);
455     Math::mmul33(s->orient, tmp, tmp);
456     float roll, pitch, hdg;
457     Glue::orient2euler(tmp, &roll, &pitch, &hdg);
458     // make heading positive value
459     if(hdg < 0.0) hdg += PI2;
460     _set_Euler_Angles(roll, pitch, hdg);
461
462     // rotation
463     Math::vmul33(s->orient, s->rot, v);
464     _set_Omega_Body(v[0], -v[1], -v[2]);
465
466     Glue::calcEulerRates(s, &roll, &pitch, &hdg);
467     _set_Euler_Rates(roll, pitch, hdg);
468
469     // Fill out our engine and gear objects
470     int i;
471     for(i=0; i<airplane->numGear(); i++) {
472         Gear* g = airplane->getGear(i);
473         SGPropertyNode * node = fgGetNode("gear/gear", i, true);
474         node->setBoolValue("has-brake", g->getBrake() != 0);
475         node->setBoolValue("wow", g->getCompressFraction() != 0);
476         node->setFloatValue("compression-norm", g->getCompressFraction());
477         node->setFloatValue("compression-m", g->getCompressDist());
478         node->setFloatValue("caster-angle-deg", g->getCasterAngle() * RAD2DEG);
479         node->setFloatValue("rollspeed-ms", g->getRollSpeed());
480         node->setBoolValue("ground-is-solid", g->getGroundIsSolid()!=0);
481         node->setFloatValue("ground-friction-factor", g->getGroundFrictionFactor());
482     }
483
484     Hook* h = airplane->getHook();
485     if(h) {
486         SGPropertyNode * node = fgGetNode("gear/tailhook", 0, true);
487         node->setFloatValue("position-norm", h->getCompressFraction());
488     }
489
490     Launchbar* l = airplane->getLaunchbar();
491     if(l) {
492         SGPropertyNode * node = fgGetNode("gear/launchbar", 0, true);
493         node->setFloatValue("position-norm", l->getCompressFraction());
494         node->setFloatValue("holdback-position-norm", l->getHoldbackCompressFraction());
495         node->setStringValue("state", l->getState());
496         node->setBoolValue("strop", l->getStrop());
497     }
498
499 }