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