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