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