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