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