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