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