]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
Patch from Melchior Franz:
[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     SG_LOG(SG_FLIGHT,SG_INFO,"Approach Elevator: "<<a->getApproachElevator());
83     
84
85     float cg[3];
86     char buf[256];
87     a->getModel()->getBody()->getCG(cg);
88     sprintf(buf, "            CG: %.1f, %.1f, %.1f", cg[0], cg[1], cg[2]);
89     SG_LOG(SG_FLIGHT, SG_INFO, buf);
90
91     if(a->getFailureMsg()) {
92         SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
93         SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
94         exit(1);
95     }
96 }
97
98 void YASim::bind()
99 {
100     // Run the superclass bind to set up a bunch of property ties
101     FGInterface::bind();
102
103     // Now UNtie the ones that we are going to set ourselves.
104     fgUntie("/consumables/fuel/tank[0]/level-gal_us");
105     fgUntie("/consumables/fuel/tank[1]/level-gal_us");
106
107     char buf[256];
108     for(int i=0; i<_fdm->getAirplane()->getModel()->numThrusters(); i++) {
109         sprintf(buf, "/engines/engine[%d]/fuel-flow-gph", i); fgUntie(buf);
110         sprintf(buf, "/engines/engine[%d]/rpm", i);           fgUntie(buf);
111         sprintf(buf, "/engines/engine[%d]/mp-osi", i);        fgUntie(buf);
112         sprintf(buf, "/engines/engine[%d]/egt-degf", i);      fgUntie(buf);
113     }
114
115 }
116
117 void YASim::init()
118 {
119     Airplane* a = _fdm->getAirplane();
120     Model* m = a->getModel();
121
122     // Superclass hook
123     common_init();
124
125     m->setCrashed(false);
126
127     // Build a filename and parse it
128     SGPath f(globals->get_fg_root());
129     f.append("Aircraft-yasim");
130     f.append(fgGetString("/sim/aero"));
131     f.concat(".xml");
132     readXML(f.str(), *_fdm);
133
134     // Compile it into a real airplane, and tell the user what they got
135     a->compile();
136     report();
137
138     _fdm->init();
139
140     // Create some FG{Eng|Gear}Interface objects
141     int i;
142     for(i=0; i<a->numGear(); i++) {
143         Gear* g = a->getGear(i);
144         SGPropertyNode * node = fgGetNode("gear/gear", i, true);
145         float pos[3];
146         g->getPosition(pos);
147         node->setDoubleValue("xoffset-in", pos[0]);
148         node->setDoubleValue("yoffset-in", pos[1]);
149         node->setDoubleValue("zoffset-in", pos[2]);
150     }
151     for(i=0; i<m->numThrusters(); i++) {
152         // Sanify the initial input conditions
153         char buf[64];
154         sprintf(buf, "/controls/throttle[%d]", i);        fgSetFloat(buf, 0);
155         sprintf(buf, "/controls/mixture[%d]", i);         fgSetFloat(buf, 1);
156         sprintf(buf, "/controls/propeller-pitch[%d]", i); fgSetFloat(buf, 1);
157         sprintf(buf, "/controls/afterburner[%d]", i);     fgSetFloat(buf, 0);
158     }
159
160     fgSetFloat("/controls/slats", 0);
161     fgSetFloat("/controls/spoilers", 0);
162
163     // Are we at ground level?  If so, lift the plane up so the gear
164     // clear the ground.
165     double runway_altitude = get_Runway_altitude();
166     fgSetBool("/controls/gear-down", false);
167     if(get_Altitude() - runway_altitude < 50) {
168         float minGearZ = 1e18;
169         for(i=0; i<a->numGear(); i++) {
170             Gear* g = a->getGear(i);
171             float pos[3];
172             g->getPosition(pos);
173             if(pos[2] < minGearZ)
174                 minGearZ = pos[2];
175         }
176         _set_Altitude(runway_altitude - minGearZ*M2FT);
177         fgSetBool("/controls/gear-down", true);
178     }
179
180     // The pilot's eyepoint
181     float pilot[3];
182     a->getPilotPos(pilot);
183 //     fgSetFloat("/sim/view/pilot/x-offset-m", -pilot[0]);
184 //     fgSetFloat("/sim/view/pilot/y-offset-m", -pilot[1]);
185 //     fgSetFloat("/sim/view/pilot/z-offset-m", pilot[2]);
186
187     // Blank the state, and copy in ours
188     State s;
189     m->setState(&s);
190     copyToYASim(true);
191
192     _fdm->getExternalInput();
193     _fdm->getAirplane()->initEngines();
194
195     set_inited(true);
196 }
197
198 void YASim::update(double dt)
199 {
200     if (is_suspended())
201       return;
202
203     int iterations = _calc_multiloop(dt);
204
205     // If we're crashed, then we don't care
206     if(_fdm->getAirplane()->getModel()->isCrashed())
207       return;
208
209     int i;
210     for(i=0; i<iterations; i++) {
211             copyToYASim(false);
212             _fdm->iterate(_dt);
213             copyFromYASim();
214
215             printDEBUG();
216     }
217 }
218
219 void YASim::copyToYASim(bool copyState)
220 {
221     // Physical state
222     float lat = get_Latitude();
223     float lon = get_Longitude();
224     float alt = get_Altitude() * FT2M;
225     float roll = get_Phi();
226     float pitch = get_Theta();
227     float hdg = get_Psi();
228
229     // Environment
230     float wind[3];
231     wind[0] = get_V_north_airmass() * FT2M * -1.0;
232     wind[1] = get_V_east_airmass() * FT2M * -1.0;
233     wind[2] = get_V_down_airmass() * FT2M * -1.0;
234
235     // Get ground elevation from the FGinterface's FGlocation data
236     double ground = getACModel()->get3DModel()->getFGLocation()->get_cur_elev_m();
237     // cout << "YASIM: ground = " << ground << endl;
238
239     float pressure = fgGetDouble("/environment/pressure-inhg") * INHG2PA;
240     float temp = fgGetDouble("/environment/temperature-degC") + 273.15;
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     Glue::geod2xyz(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     // Copy in the existing velocity for now...
256     Math::set3(model->getState()->v, s.v);
257
258     if(copyState)
259         model->setState(&s);
260
261     // wind
262     Math::tmul33(xyz2ned, wind, wind);
263     model->setWind(wind);
264
265     // ground.  Calculate a cartesian coordinate for the ground under
266     // us, find the (geodetic) up vector normal to the ground, then
267     // use that to find the final (radius) term of the plane equation.
268     double xyz[3], gplane[3]; float up[3];
269     Glue::geod2xyz(lat, lon, ground, xyz);
270     Glue::geodUp(xyz, up); // FIXME, needless reverse computation...
271     int i;
272     for(i=0; i<3; i++) gplane[i] = up[i];
273     double rad = gplane[0]*xyz[0] + gplane[1]*xyz[1] + gplane[2]*xyz[2];
274     model->setGroundPlane(gplane, rad);
275
276     // air
277     model->setAir(pressure, temp);
278 }
279
280 // All the settables:
281 //
282 // These are set below:
283 // _set_Accels_Local
284 // _set_Accels_Body
285 // _set_Accels_CG_Body 
286 // _set_Accels_Pilot_Body
287 // _set_Accels_CG_Body_N 
288 // _set_Velocities_Local
289 // _set_Velocities_Ground
290 // _set_Velocities_Wind_Body
291 // _set_Omega_Body
292 // _set_Euler_Rates
293 // _set_Euler_Angles
294 // _set_V_rel_wind
295 // _set_V_ground_speed
296 // _set_V_equiv_kts
297 // _set_V_calibrated_kts
298 // _set_Alpha
299 // _set_Beta
300 // _set_Mach_number
301 // _set_Climb_Rate
302 // _set_Tank1Fuel
303 // _set_Tank2Fuel
304 // _set_Altitude_AGL
305 // _set_Geodetic_Position
306 // _set_Runway_altitude
307
308 // Ignoring these, because they're unused:
309 // _set_Geocentric_Position
310 // _set_Geocentric_Rates
311 // _set_Cos_phi
312 // _set_Cos_theta
313 // _set_Earth_position_angle (WTF?)
314 // _set_Gamma_vert_rad
315 // _set_Inertias
316 // _set_T_Local_to_Body
317 // _set_CG_Position
318 // _set_Sea_Level_Radius
319
320 // Externally set via the weather code:
321 // _set_Velocities_Local_Airmass
322 // _set_Density
323 // _set_Static_pressure
324 // _set_Static_temperature
325 void YASim::copyFromYASim()
326 {
327     Airplane* airplane = _fdm->getAirplane();
328     Model* model = airplane->getModel();
329     State* s = model->getState();
330
331     // position
332     double lat, lon, alt;
333     Glue::xyz2geod(s->pos, &lat, &lon, &alt);
334     _set_Geodetic_Position(lat, lon, alt*M2FT);
335
336     // UNUSED
337     //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
338
339     _set_Altitude_AGL(model->getAGL() * M2FT);
340
341     // useful conversion matrix
342     float xyz2ned[9];
343     Glue::xyz2nedMat(lat, lon, xyz2ned);
344
345     // velocity
346     float v[3];
347     Math::vmul33(xyz2ned, s->v, v);
348     _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
349     _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
350                                    M2FT*v[1]*M2FT*v[1]));
351     _set_Climb_Rate(-M2FT*v[2]);
352
353     // The HUD uses this, but inverts down (?!)
354     _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
355
356     // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
357
358     // Airflow velocity.
359     float wind[3];
360     wind[0] = get_V_north_airmass() * FT2M * -1.0;  // Wind in NED
361     wind[1] = get_V_east_airmass() * FT2M * -1.0;
362     wind[2] = get_V_down_airmass() * FT2M * -1.0;
363     Math::tmul33(xyz2ned, wind, wind);              // Wind in global
364     Math::sub3(s->v, wind, v);                      // V - wind in global
365     Math::vmul33(s->orient, s->v, v);               // to body coordinates
366     _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
367     _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
368
369
370     float P = fgGetDouble("/environment/pressure-inhg") * INHG2PA;
371     float T = fgGetDouble("/environment/temperature-degC") + 273.15;
372     _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T)*MPS2KTS);
373     _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
374     _set_Mach_number(Atmosphere::calcMach(v[0], T));
375
376     // acceleration
377     Math::vmul33(xyz2ned, s->acc, v);
378     _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
379
380     Math::vmul33(s->orient, s->acc, v);
381     _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
382     _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
383
384     _fdm->getAirplane()->getPilotAccel(v);
385     _set_Accels_Pilot_Body(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
386
387     // The one appears (!) to want inverted pilot acceleration
388     // numbers, in G's...
389     Math::mul3(1.0/9.8, v, v);
390     _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
391
392     // orientation
393     float alpha, beta;
394     Glue::calcAlphaBeta(s, &alpha, &beta);
395     _set_Alpha(alpha);
396     _set_Beta(beta);
397
398     float tmp[9];
399     Math::trans33(xyz2ned, tmp);
400     Math::mmul33(s->orient, tmp, tmp);
401     float roll, pitch, hdg;
402     Glue::orient2euler(tmp, &roll, &pitch, &hdg);
403     _set_Euler_Angles(roll, pitch, hdg);
404
405     // rotation
406     Math::vmul33(s->orient, s->rot, v);
407     _set_Omega_Body(v[0], -v[1], -v[2]);
408
409     Glue::calcEulerRates(s, &roll, &pitch, &hdg);
410     _set_Euler_Rates(roll, pitch, hdg);
411
412     // Fill out our engine and gear objects
413     int i;
414     for(i=0; i<airplane->numGear(); i++) {
415         Gear* g = airplane->getGear(i);
416         SGPropertyNode * node = fgGetNode("gear/gear", i, true);
417         node->setBoolValue("has-brake", g->getBrake() != 0);
418         node->setBoolValue("wow", g->getCompressFraction() != 0);
419         node->setFloatValue("compression-norm", g->getCompressFraction());
420     }
421
422     for(i=0; i<model->numThrusters(); i++) {
423         SGPropertyNode * node = fgGetNode("engines/engine", i, true);
424         Thruster* t = model->getThruster(i);
425
426         node->setBoolValue("running", t->isRunning());
427         node->setBoolValue("cranking", t->isCranking());
428
429         // Note: assumes all tanks have the same fuel density!
430         node->setDoubleValue("fuel-flow-gph", CM2GALS * t->getFuelFlow()
431                              / airplane->getFuelDensity(0));
432
433         float tmp[3];
434         t->getThrust(tmp);
435         node->setDoubleValue("prop-thrust", Math::mag3(tmp) * KG2LBS / 9.8);
436
437         PropEngine* pe = t->getPropEngine();
438         if(pe) {
439             node->setDoubleValue("rpm", pe->getOmega() * RAD2RPM);
440
441             pe->getTorque(tmp);
442             float power = Math::mag3(tmp) * pe->getOmega();
443             float maxPower = pe->getPistonEngine()->getMaxPower();
444
445             node->setDoubleValue("max-hp", maxPower * W2HP);
446             node->setDoubleValue("power-pct", 100 * power/maxPower);
447         }
448     }
449 }