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