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