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