]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
Moved "scenery" from being declaried in scenery.cxx to being declared
[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 <Scenery/scenery.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
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 =
164       fgGetDouble("/environment/ground-elevation-m") * SG_METER_TO_FEET;
165     fgSetBool("/controls/gear-down", false);
166     if(get_Altitude() - runway_altitude < 50) {
167         float minGearZ = 1e18;
168         for(i=0; i<a->numGear(); i++) {
169             Gear* g = a->getGear(i);
170             float pos[3];
171             g->getPosition(pos);
172             if(pos[2] < minGearZ)
173                 minGearZ = pos[2];
174         }
175         _set_Altitude(runway_altitude - minGearZ*M2FT);
176         fgSetBool("/controls/gear-down", true);
177     }
178
179     // The pilot's eyepoint
180     float pilot[3];
181     a->getPilotPos(pilot);
182 //     fgSetFloat("/sim/view/pilot/x-offset-m", -pilot[0]);
183 //     fgSetFloat("/sim/view/pilot/y-offset-m", -pilot[1]);
184 //     fgSetFloat("/sim/view/pilot/z-offset-m", pilot[2]);
185
186     // Blank the state, and copy in ours
187     State s;
188     m->setState(&s);
189     copyToYASim(true);
190
191     _fdm->getExternalInput();
192     _fdm->getAirplane()->initEngines();
193
194     set_inited(true);
195 }
196
197 void YASim::update(double dt)
198 {
199     if (is_suspended())
200       return;
201
202     int iterations = _calc_multiloop(dt);
203
204     // If we're crashed, then we don't care
205     if(_fdm->getAirplane()->getModel()->isCrashed())
206       return;
207
208     int i;
209     for(i=0; i<iterations; i++) {
210             copyToYASim(false);
211             _fdm->iterate(_dt);
212             copyFromYASim();
213
214             printDEBUG();
215     }
216 }
217
218 void YASim::copyToYASim(bool copyState)
219 {
220     // Physical state
221     float lat = get_Latitude();
222     float lon = get_Longitude();
223     float alt = get_Altitude() * FT2M;
224     float roll = get_Phi();
225     float pitch = get_Theta();
226     float hdg = get_Psi();
227
228     // Environment
229     float wind[3];
230     wind[0] = get_V_north_airmass() * FT2M * -1.0;
231     wind[1] = get_V_east_airmass() * FT2M * -1.0;
232     wind[2] = get_V_down_airmass() * FT2M * -1.0;
233
234     // The ground elevation doesn't come from FGInterface; query it
235     // from the scenery and set it for others to find.
236     double ground = globals->get_scenery()->get_cur_elev();
237     _set_Runway_altitude(ground * FT2M);
238     // cout << "YASIM: ground = " << ground << endl;
239
240     // You'd this this would work, but it doesn't.  These values are
241     // always zero.  Use a "standard" pressure intstead.
242     //
243     // float pressure = get_Static_pressure();
244     // float temp = get_Static_temperature();
245     float pressure = Atmosphere::getStdPressure(alt);
246     float temp = Atmosphere::getStdTemperature(alt);
247
248     // Convert and set:
249     Model* model = _fdm->getAirplane()->getModel();
250     State s;
251     float xyz2ned[9];
252     Glue::xyz2nedMat(lat, lon, xyz2ned);
253
254     // position
255     Glue::geod2xyz(lat, lon, alt, s.pos);
256
257     // orientation
258     Glue::euler2orient(roll, pitch, hdg, s.orient);
259     Math::mmul33(s.orient, xyz2ned, s.orient);
260
261     // Copy in the existing velocity for now...
262     Math::set3(model->getState()->v, s.v);
263
264     if(copyState)
265         model->setState(&s);
266
267     // wind
268     Math::tmul33(xyz2ned, wind, wind);
269     model->setWind(wind);
270
271     // ground.  Calculate a cartesian coordinate for the ground under
272     // us, find the (geodetic) up vector normal to the ground, then
273     // use that to find the final (radius) term of the plane equation.
274     double xyz[3], gplane[3]; float up[3];
275     Glue::geod2xyz(lat, lon, ground, xyz);
276     Glue::geodUp(xyz, up); // FIXME, needless reverse computation...
277     int i;
278     for(i=0; i<3; i++) gplane[i] = up[i];
279     double rad = gplane[0]*xyz[0] + gplane[1]*xyz[1] + gplane[2]*xyz[2];
280     model->setGroundPlane(gplane, rad);
281
282     // air
283     model->setAir(pressure, temp);
284 }
285
286 // All the settables:
287 //
288 // These are set below:
289 // _set_Accels_Local
290 // _set_Accels_Body
291 // _set_Accels_CG_Body 
292 // _set_Accels_Pilot_Body
293 // _set_Accels_CG_Body_N 
294 // _set_Velocities_Local
295 // _set_Velocities_Ground
296 // _set_Velocities_Wind_Body
297 // _set_Omega_Body
298 // _set_Euler_Rates
299 // _set_Euler_Angles
300 // _set_V_rel_wind
301 // _set_V_ground_speed
302 // _set_V_equiv_kts
303 // _set_V_calibrated_kts
304 // _set_Alpha
305 // _set_Beta
306 // _set_Mach_number
307 // _set_Climb_Rate
308 // _set_Tank1Fuel
309 // _set_Tank2Fuel
310 // _set_Altitude_AGL
311 // _set_Geodetic_Position
312 // _set_Runway_altitude
313
314 // Ignoring these, because they're unused:
315 // _set_Geocentric_Position
316 // _set_Geocentric_Rates
317 // _set_Cos_phi
318 // _set_Cos_theta
319 // _set_Earth_position_angle (WTF?)
320 // _set_Gamma_vert_rad
321 // _set_Inertias
322 // _set_T_Local_to_Body
323 // _set_CG_Position
324 // _set_Sea_Level_Radius
325
326 // Externally set via the weather code:
327 // _set_Velocities_Local_Airmass
328 // _set_Density
329 // _set_Static_pressure
330 // _set_Static_temperature
331 void YASim::copyFromYASim()
332 {
333     Airplane* airplane = _fdm->getAirplane();
334     Model* model = airplane->getModel();
335     State* s = model->getState();
336
337     // position
338     double lat, lon, alt;
339     Glue::xyz2geod(s->pos, &lat, &lon, &alt);
340     _set_Geodetic_Position(lat, lon, alt*M2FT);
341
342     // UNUSED
343     //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
344
345     _set_Altitude_AGL(model->getAGL() * M2FT);
346
347     // useful conversion matrix
348     float xyz2ned[9];
349     Glue::xyz2nedMat(lat, lon, xyz2ned);
350
351     // velocity
352     float v[3];
353     Math::vmul33(xyz2ned, s->v, v);
354     _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
355     _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
356                                    M2FT*v[1]*M2FT*v[1]));
357     _set_Climb_Rate(-M2FT*v[2]);
358
359     // The HUD uses this, but inverts down (?!)
360     _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
361
362     // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
363
364     // Airflow velocity.
365     float wind[3];
366     wind[0] = get_V_north_airmass() * FT2M * -1.0;  // Wind in NED
367     wind[1] = get_V_east_airmass() * FT2M * -1.0;
368     wind[2] = get_V_down_airmass() * FT2M * -1.0;
369     Math::tmul33(xyz2ned, wind, wind);              // Wind in global
370     Math::sub3(s->v, wind, v);                      // V - wind in global
371     Math::vmul33(s->orient, s->v, v);               // to body coordinates
372     _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
373     _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
374
375
376     // These don't work, use a dummy based on altitude
377     // float P = get_Static_pressure();
378     // float T = get_Static_temperature();
379     float P = Atmosphere::getStdPressure(alt);
380     float T = Atmosphere::getStdTemperature(alt);
381     _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T)*MPS2KTS);
382     _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
383     _set_Mach_number(Atmosphere::calcMach(v[0], T));
384
385     // acceleration
386     Math::vmul33(xyz2ned, s->acc, v);
387     _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
388
389     Math::vmul33(s->orient, s->acc, v);
390     _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
391     _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
392
393     _fdm->getAirplane()->getPilotAccel(v);
394     _set_Accels_Pilot_Body(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
395
396     // The one appears (!) to want inverted pilot acceleration
397     // numbers, in G's...
398     Math::mul3(1.0/9.8, v, v);
399     _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
400
401     // orientation
402     float alpha, beta;
403     Glue::calcAlphaBeta(s, &alpha, &beta);
404     _set_Alpha(alpha);
405     _set_Beta(beta);
406
407     float tmp[9];
408     Math::trans33(xyz2ned, tmp);
409     Math::mmul33(s->orient, tmp, tmp);
410     float roll, pitch, hdg;
411     Glue::orient2euler(tmp, &roll, &pitch, &hdg);
412     _set_Euler_Angles(roll, pitch, hdg);
413
414     // rotation
415     Math::vmul33(s->orient, s->rot, v);
416     _set_Omega_Body(v[0], -v[1], -v[2]);
417
418     Glue::calcEulerRates(s, &roll, &pitch, &hdg);
419     _set_Euler_Rates(roll, pitch, hdg);
420
421     // Fill out our engine and gear objects
422     int i;
423     for(i=0; i<airplane->numGear(); i++) {
424         Gear* g = airplane->getGear(i);
425         SGPropertyNode * node = fgGetNode("gear/gear", i, true);
426         node->setBoolValue("has-brake", g->getBrake() != 0);
427         node->setBoolValue("wow", g->getCompressFraction() != 0);
428         node->setFloatValue("compression-norm", g->getCompressFraction());
429     }
430
431     for(i=0; i<model->numThrusters(); i++) {
432         SGPropertyNode * node = fgGetNode("engines/engine", i, true);
433         Thruster* t = model->getThruster(i);
434
435         node->setBoolValue("running", t->isRunning());
436         node->setBoolValue("cranking", t->isCranking());
437
438         // Note: assumes all tanks have the same fuel density!
439         node->setDoubleValue("fuel-flow-gph", CM2GALS * t->getFuelFlow()
440                              / airplane->getFuelDensity(0));
441
442         float tmp[3];
443         t->getThrust(tmp);
444         node->setDoubleValue("prop-thrust", Math::mag3(tmp) * KG2LBS / 9.8);
445
446         PropEngine* pe = t->getPropEngine();
447         if(pe) {
448             node->setDoubleValue("rpm", pe->getOmega() * RAD2RPM);
449
450             pe->getTorque(tmp);
451             float power = Math::mag3(tmp) * pe->getOmega();
452             float maxPower = pe->getPistonEngine()->getMaxPower();
453
454             node->setDoubleValue("max-hp", maxPower * W2HP);
455             node->setDoubleValue("power-pct", 100 * power/maxPower);
456         }
457     }
458 }