]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
Fix stall widths for the "auxilliary" (reverse flow) stalls so they
[flightgear.git] / src / FDM / YASim / YASim.cxx
1
2 #include <simgear/debug/logstream.hxx>
3 #include <simgear/math/sg_geodesy.hxx>
4 #include <simgear/misc/sg_path.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
11 #include "FGFDM.hpp"
12 #include "Atmosphere.hpp"
13 #include "Math.hpp"
14 #include "Airplane.hpp"
15 #include "Model.hpp"
16 #include "Integrator.hpp"
17 #include "Glue.hpp"
18 #include "Gear.hpp"
19 #include "Hook.hpp"
20 #include "Launchbar.hpp"
21 #include "FGGround.hpp"
22 #include "PropEngine.hpp"
23 #include "PistonEngine.hpp"
24
25 #include "YASim.hxx"
26
27 using namespace yasim;
28
29 static const float YASIM_PI = 3.14159265358979323846;
30 static const float RAD2DEG = 180/YASIM_PI;
31 static const float PI2 = YASIM_PI*2;
32 static const float RAD2RPM = 9.54929658551;
33 static const float M2FT = 3.2808399;
34 static const float FT2M = 0.3048;
35 static const float MPS2KTS = 3600.0/1852.0;
36 static const float CM2GALS = 264.172037284; // gallons/cubic meter
37 static const float KG2LBS = 2.20462262185;
38 static const float W2HP = 1.3416e-3;
39 static const float INHG2PA = 3386.389;
40 static const float SLUG2KG = 14.59390;
41
42 YASim::YASim(double dt)
43 {
44 //     set_delta_t(dt);
45     _fdm = new FGFDM();
46
47     _dt = dt;
48
49     _fdm->getAirplane()->getModel()->setGroundCallback( new FGGround(this) );
50     _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
51 }
52
53 void YASim::report()
54 {
55     Airplane* a = _fdm->getAirplane();
56
57     float aoa = a->getCruiseAoA() * RAD2DEG;
58     float tail = -1 * a->getTailIncidence() * RAD2DEG;
59     float drag = 1000 * a->getDragCoefficient();
60
61     SG_LOG(SG_FLIGHT,SG_INFO,"YASim solution results:");
62     SG_LOG(SG_FLIGHT,SG_INFO,"       Iterations: "<<a->getSolutionIterations());
63     SG_LOG(SG_FLIGHT,SG_INFO," Drag Coefficient: "<< drag);
64     SG_LOG(SG_FLIGHT,SG_INFO,"       Lift Ratio: "<<a->getLiftRatio());
65     SG_LOG(SG_FLIGHT,SG_INFO,"       Cruise AoA: "<< aoa);
66     SG_LOG(SG_FLIGHT,SG_INFO,"   Tail Incidence: "<< tail);
67     SG_LOG(SG_FLIGHT,SG_INFO,"Approach Elevator: "<<a->getApproachElevator());
68     
69
70     float cg[3];
71     char buf[256];
72     a->getModel()->getBody()->getCG(cg);
73     sprintf(buf, "            CG: %.3f, %.3f, %.3f", cg[0], cg[1], cg[2]);
74     SG_LOG(SG_FLIGHT, SG_INFO, buf);
75
76     if(a->getFailureMsg()) {
77         SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
78         SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
79         exit(1);
80     }
81 }
82
83 void YASim::bind()
84 {
85     // Run the superclass bind to set up a bunch of property ties
86     FGInterface::bind();
87
88     // Now UNtie the ones that we are going to set ourselves.
89     fgUntie("/consumables/fuel/tank[0]/level-gal_us");
90     fgUntie("/consumables/fuel/tank[1]/level-gal_us");
91
92     char buf[256];
93     for(int i=0; i<_fdm->getAirplane()->getModel()->numThrusters(); i++) {
94         sprintf(buf, "/engines/engine[%d]/fuel-flow-gph", i);        fgUntie(buf);
95         sprintf(buf, "/engines/engine[%d]/rpm", i);                  fgUntie(buf);
96         sprintf(buf, "/engines/engine[%d]/mp-osi", i);               fgUntie(buf);
97         sprintf(buf, "/engines/engine[%d]/egt-degf", i);             fgUntie(buf);
98         sprintf(buf, "/engines/engine[%d]/oil-temperature-degf", i); fgUntie(buf);
99     }
100 }
101
102 void YASim::init()
103 {
104     Airplane* a = _fdm->getAirplane();
105     Model* m = a->getModel();
106
107     // Superclass hook
108     common_init();
109
110     m->setCrashed(false);
111
112     // Figure out the initial speed type
113     string speed_set = fgGetString("/sim/presets/speed-set", "UVW");
114     if (speed_set == "NED")
115         _speed_set = NED;
116     else if (speed_set == "UVW")
117         _speed_set = UVW;
118     else if (speed_set == "knots")
119         _speed_set = KNOTS;
120     else if (speed_set == "mach")
121         _speed_set = MACH;
122     else {
123         _speed_set = UVW;
124         SG_LOG(SG_FLIGHT, SG_ALERT, "Unknown speed type " << speed_set);
125     }
126
127     // Build a filename and parse it
128     SGPath f(fgGetString("/sim/aircraft-dir"));
129     f.append(fgGetString("/sim/aero"));
130     f.concat(".xml");
131     readXML(f.str(), *_fdm);
132
133     // Compile it into a real airplane, and tell the user what they got
134     a->compile();
135     report();
136
137     _fdm->init();
138
139     // Create some FG{Eng|Gear}Interface objects
140     int i;
141     for(i=0; i<a->numGear(); i++) {
142         Gear* g = a->getGear(i);
143         SGPropertyNode * node = fgGetNode("gear/gear", i, true);
144         float pos[3];
145         g->getPosition(pos);
146         node->setDoubleValue("xoffset-in", pos[0] * M2FT * 12);
147         node->setDoubleValue("yoffset-in", pos[1] * M2FT * 12);
148         node->setDoubleValue("zoffset-in", pos[2] * M2FT * 12);
149     }
150
151     // Are we at ground level?  If so, lift the plane up so the gear
152     // clear the ground.
153     double runway_altitude = get_Runway_altitude();
154     if(get_Altitude() - runway_altitude < 50) {
155         fgSetBool("/controls/gear/gear-down", false);
156         float minGearZ = 1e18;
157         for(i=0; i<a->numGear(); i++) {
158             Gear* g = a->getGear(i);
159             float pos[3];
160             g->getPosition(pos);
161             if(pos[2] < minGearZ)
162                 minGearZ = pos[2];
163         }
164         _set_Altitude(runway_altitude - minGearZ*M2FT);
165         fgSetBool("/controls/gear/gear-down", true);
166     }
167
168     // Blank the state, and copy in ours
169     State s;
170     m->setState(&s);
171     copyToYASim(true);
172
173     _fdm->getExternalInput();
174     _fdm->getAirplane()->initEngines();
175
176     set_inited(true);
177 }
178
179 void YASim::update(double dt)
180 {
181     if (is_suspended())
182         return;
183
184     int iterations = _calc_multiloop(dt);
185
186     // If we're crashed, then we don't care
187     if(_fdm->getAirplane()->getModel()->isCrashed()) {
188         if(!fgGetBool("/sim/crashed"))
189             fgSetBool("/sim/crashed", true);
190         return;
191     }
192
193     // ground.  Calculate a cartesian coordinate for the ground under
194     // us, find the (geodetic) up vector normal to the ground, then
195     // use that to find the final (radius) term of the plane equation.
196     float v[3] = { get_uBody(), get_vBody(), get_wBody() };
197     float lat = get_Latitude(); float lon = get_Longitude();
198     float alt = get_Altitude() * FT2M; double xyz[3];
199     sgGeodToCart(lat, lon, alt, xyz);
200     // build the environment cache.
201     float vr = _fdm->getVehicleRadius();
202     vr += 2.0*FT2M*dt*Math::mag3(v);
203     prepare_ground_cache_m( 0.0, xyz, vr );
204
205     // Track time increments.
206     FGGround* gr
207       = (FGGround*)_fdm->getAirplane()->getModel()->getGroundCallback();
208
209     int i;
210     for(i=0; i<iterations; i++) {
211         gr->setTimeOffset(i*_dt);
212         copyToYASim(false);
213         _fdm->iterate(_dt);
214         copyFromYASim();
215     }
216
217     // Reset the time increment.
218     gr->setTimeOffset(0.0);
219 }
220
221 void YASim::copyToYASim(bool copyState)
222 {
223     // Physical state
224     float lat = get_Latitude();
225     float lon = get_Longitude();
226     float alt = get_Altitude() * FT2M;
227     float roll = get_Phi();
228     float pitch = get_Theta();
229     float hdg = get_Psi();
230
231     // Environment
232     float wind[3];
233     wind[0] = get_V_north_airmass() * FT2M * -1.0;
234     wind[1] = get_V_east_airmass() * FT2M * -1.0;
235     wind[2] = get_V_down_airmass() * FT2M * -1.0;
236
237     float pressure = fgGetFloat("/environment/pressure-inhg") * INHG2PA;
238     float temp = fgGetFloat("/environment/temperature-degc") + 273.15;
239     float dens = fgGetFloat("/environment/density-slugft3") 
240         * SLUG2KG * M2FT*M2FT*M2FT;
241
242     // Convert and set:
243     Model* model = _fdm->getAirplane()->getModel();
244     State s;
245     float xyz2ned[9];
246     Glue::xyz2nedMat(lat, lon, xyz2ned);
247
248     // position
249     sgGeodToCart(lat, lon, alt, s.pos);
250
251     // orientation
252     Glue::euler2orient(roll, pitch, hdg, s.orient);
253     Math::mmul33(s.orient, xyz2ned, s.orient);
254
255     // Velocity
256     string speed_set = fgGetString("/sim/presets/speed-set", "UVW");
257     float v[3];
258     bool needCopy = false;
259     switch (_speed_set) {
260     case NED:
261         v[0] = get_V_north() * FT2M * -1.0;
262         v[1] = get_V_east() * FT2M * -1.0;
263         v[2] = get_V_down() * FT2M * -1.0;
264         break;
265     case UVW:
266         v[0] = get_uBody() * FT2M;
267         v[1] = get_vBody() * FT2M;
268         v[2] = get_wBody() * FT2M;
269         Math::tmul33(s.orient, v, v);
270         break;
271     case KNOTS:
272         v[0] = Atmosphere::spdFromVCAS(get_V_calibrated_kts()/MPS2KTS,
273                                        pressure, temp);
274         v[1] = 0;
275         v[2] = 0;
276         Math::tmul33(s.orient, v, v);
277         needCopy = true;
278         break;
279     case MACH:
280         v[0] = Atmosphere::spdFromMach(get_Mach_number(), temp);
281         v[1] = 0;
282         v[2] = 0;
283         Math::tmul33(s.orient, v, v);
284         needCopy = true;
285         break;
286     default:
287         v[0] = 0;
288         v[1] = 0;
289         v[2] = 0;
290         break;
291     }
292     if (!copyState)
293         _speed_set = UVW;       // change to this after initial setting
294     Math::set3(v, s.v);
295
296     if(copyState || needCopy)
297         model->setState(&s);
298
299     // wind
300     Math::tmul33(xyz2ned, wind, wind);
301     model->setWind(wind);
302
303     // air
304     model->setAir(pressure, temp, dens);
305
306     // Query a ground plane for each gear/hook/launchbar and
307     // write that value into the corresponding class.
308     _fdm->getAirplane()->getModel()->updateGround(&s);
309
310     Launchbar* l = model->getLaunchbar();
311     if (l)
312         l->setLaunchCmd(0.0<fgGetFloat("/controls/gear/catapult-launch-cmd"));
313 }
314
315 // All the settables:
316 //
317 // These are set below:
318 // _set_Accels_Local
319 // _set_Accels_Body
320 // _set_Accels_CG_Body 
321 // _set_Accels_Pilot_Body
322 // _set_Accels_CG_Body_N 
323 // _set_Velocities_Local
324 // _set_Velocities_Ground
325 // _set_Velocities_Wind_Body
326 // _set_Omega_Body
327 // _set_Euler_Rates
328 // _set_Euler_Angles
329 // _set_V_rel_wind
330 // _set_V_ground_speed
331 // _set_V_equiv_kts
332 // _set_V_calibrated_kts
333 // _set_Alpha
334 // _set_Beta
335 // _set_Mach_number
336 // _set_Climb_Rate
337 // _set_Tank1Fuel
338 // _set_Tank2Fuel
339 // _set_Altitude_AGL
340 // _set_Geodetic_Position
341 // _set_Runway_altitude
342
343 // Ignoring these, because they're unused:
344 // _set_Geocentric_Position
345 // _set_Geocentric_Rates
346 // _set_Cos_phi
347 // _set_Cos_theta
348 // _set_Earth_position_angle (WTF?)
349 // _set_Gamma_vert_rad
350 // _set_Inertias
351 // _set_T_Local_to_Body
352 // _set_CG_Position
353 // _set_Sea_Level_Radius
354
355 // Externally set via the weather code:
356 // _set_Velocities_Local_Airmass
357 // _set_Density
358 // _set_Static_pressure
359 // _set_Static_temperature
360 void YASim::copyFromYASim()
361 {
362     Airplane* airplane = _fdm->getAirplane();
363     Model* model = airplane->getModel();
364     State* s = model->getState();
365
366     // position
367     double lat, lon, alt;
368     sgCartToGeod(s->pos, &lat, &lon, &alt);
369     _set_Geodetic_Position(lat, lon, alt*M2FT);
370     _update_ground_elev_at_pos();
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         node->setFloatValue("caster-angle-deg", g->getCasterAngle() * RAD2DEG);
465         node->setFloatValue("rollspeed-ms", g->getRollSpeed());
466     }
467
468     Hook* h = airplane->getHook();
469     if(h) {
470         SGPropertyNode * node = fgGetNode("gear/tailhook", 0, true);
471         node->setFloatValue("position-norm", h->getCompressFraction());
472     }
473
474     Launchbar* l = airplane->getLaunchbar();
475     if(l) {
476         SGPropertyNode * node = fgGetNode("gear/launchbar", 0, true);
477         node->setFloatValue("position-norm", l->getCompressFraction());
478     }
479 }