]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
Latest YASim changes.
[flightgear.git] / src / FDM / YASim / YASim.cxx
1 #include <stdio.h>
2
3 #include <simgear/misc/sg_path.hxx>
4 #include <simgear/debug/logstream.hxx>
5 #include <simgear/xml/easyxml.hxx>
6 #include <Main/globals.hxx>
7 #include <Main/fg_props.hxx>
8 #include <Scenery/scenery.hxx>
9
10 #include "FGFDM.hpp"
11 #include "Atmosphere.hpp"
12 #include "Math.hpp"
13 #include "Airplane.hpp"
14 #include "Model.hpp"
15 #include "Integrator.hpp"
16 #include "Glue.hpp"
17 #include "Gear.hpp"
18 #include "PropEngine.hpp"
19 #include "PistonEngine.hpp"
20
21 #include "YASim.hxx"
22
23 using namespace yasim;
24
25 static const float RAD2DEG = 180/3.14159265358979323846;
26 static const float RAD2RPM = 9.54929658551;
27 static const float M2FT = 3.2808399;
28 static const float FT2M = 0.3048;
29 static const float MPS2KTS = 3600.0/1852.0;
30 static const float CM2GALS = 264.172037284; // gallons/cubic meter
31 static const float KG2LBS = 2.20462262185;
32 static const float W2HP = 1.3416e-3;
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
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         FGGearInterface fgg;
145         float pos[3];
146         g->getPosition(pos);
147         fgg.SetX(pos[0]); fgg.SetY(-pos[1]); fgg.SetZ(-pos[2]);
148         add_gear_unit(fgg);
149     }
150     for(i=0; i<m->numThrusters(); i++) {
151         FGEngInterface fge;
152         add_engine(fge);
153
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     if(get_Altitude() - get_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(get_Runway_altitude() - minGearZ*M2FT);
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()->stabilizeThrust();
193
194     set_inited(true);
195 }
196
197 void YASim::update(int iterations)
198 {
199     // If we're crashed, then we don't care
200     if(_fdm->getAirplane()->getModel()->isCrashed())
201       return;
202
203     int i;
204     for(i=0; i<iterations; i++) {
205             copyToYASim(false);
206             _fdm->iterate(_dt);
207             copyFromYASim();
208
209             printDEBUG();
210     }
211 }
212
213 void YASim::copyToYASim(bool copyState)
214 {
215     // Physical state
216     float lat = get_Latitude();
217     float lon = get_Longitude();
218     float alt = get_Altitude() * FT2M;
219     float roll = get_Phi();
220     float pitch = get_Theta();
221     float hdg = get_Psi();
222
223     // Environment
224     float wind[3];
225     wind[0] = get_V_north_airmass() * FT2M;
226     wind[1] = get_V_east_airmass() * FT2M;
227     wind[2] = get_V_down_airmass() * FT2M;
228     double ground = get_Runway_altitude() * FT2M;
229
230     // You'd this this would work, but it doesn't.  These values are
231     // always zero.  Use a "standard" pressure intstead.
232     //
233     // float pressure = get_Static_pressure();
234     // float temp = get_Static_temperature();
235     float pressure = Atmosphere::getStdPressure(alt);
236     float temp = Atmosphere::getStdTemperature(alt);
237
238     // Convert and set:
239     Model* model = _fdm->getAirplane()->getModel();
240     State s;
241     float xyz2ned[9];
242     Glue::xyz2nedMat(lat, lon, xyz2ned);
243
244     // position
245     Glue::geod2xyz(lat, lon, alt, s.pos);
246
247     // orientation
248     Glue::euler2orient(roll, pitch, hdg, s.orient);
249     Math::mmul33(s.orient, xyz2ned, s.orient);
250
251     // Copy in the existing velocity for now...
252     Math::set3(model->getState()->v, s.v);
253
254     if(copyState)
255         model->setState(&s);
256
257     // wind
258     Math::tmul33(xyz2ned, wind, wind);
259     model->setWind(wind);
260
261     // ground.  Calculate a cartesian coordinate for the ground under
262     // us, find the (geodetic) up vector normal to the ground, then
263     // use that to find the final (radius) term of the plane equation.
264     double xyz[3], gplane[3]; float up[3];
265     Glue::geod2xyz(lat, lon, ground, xyz);
266     Glue::geodUp(xyz, up); // FIXME, needless reverse computation...
267     int i;
268     for(i=0; i<3; i++) gplane[i] = up[i];
269     double rad = gplane[0]*xyz[0] + gplane[1]*xyz[1] + gplane[2]*xyz[2];
270     model->setGroundPlane(gplane, rad);
271
272     // air
273     model->setAir(pressure, temp);
274 }
275
276 // All the settables:
277 //
278 // These are set below:
279 // _set_Accels_Local
280 // _set_Accels_Body
281 // _set_Accels_CG_Body 
282 // _set_Accels_Pilot_Body
283 // _set_Accels_CG_Body_N 
284 // _set_Velocities_Local
285 // _set_Velocities_Ground
286 // _set_Velocities_Wind_Body
287 // _set_Omega_Body
288 // _set_Euler_Rates
289 // _set_Euler_Angles
290 // _set_V_rel_wind
291 // _set_V_ground_speed
292 // _set_V_equiv_kts
293 // _set_V_calibrated_kts
294 // _set_Alpha
295 // _set_Beta
296 // _set_Mach_number
297 // _set_Climb_Rate
298 // _set_Tank1Fuel
299 // _set_Tank2Fuel
300 // _set_Altitude_AGL
301 // _set_Geodetic_Position
302 // _set_Runway_altitude
303
304 // Ignoring these, because they're unused:
305 // _set_Geocentric_Position
306 // _set_Geocentric_Rates
307 // _set_Cos_phi
308 // _set_Cos_theta
309 // _set_Earth_position_angle (WTF?)
310 // _set_Gamma_vert_rad
311 // _set_Inertias
312 // _set_T_Local_to_Body
313 // _set_CG_Position
314 // _set_Sea_Level_Radius
315
316 // Externally set via the weather code:
317 // _set_Velocities_Local_Airmass
318 // _set_Density
319 // _set_Static_pressure
320 // _set_Static_temperature
321 void YASim::copyFromYASim()
322 {
323     Airplane* airplane = _fdm->getAirplane();
324     Model* model = airplane->getModel();
325     State* s = model->getState();
326
327     // position
328     double lat, lon, alt;
329     Glue::xyz2geod(s->pos, &lat, &lon, &alt);
330     _set_Geodetic_Position(lat, lon, alt*M2FT);
331
332     // UNUSED
333     //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
334
335     _set_Altitude_AGL(model->getAGL() * M2FT);
336
337     // useful conversion matrix
338     float xyz2ned[9];
339     Glue::xyz2nedMat(lat, lon, xyz2ned);
340
341     // velocity
342     float v[3];
343     Math::vmul33(xyz2ned, s->v, v);
344     _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
345     _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
346                                    M2FT*v[1]*M2FT*v[1]));
347     _set_Climb_Rate(-M2FT*v[2]);
348
349     // The HUD uses this, but inverts down (?!)
350     _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
351
352     // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
353
354     Math::vmul33(s->orient, s->v, v);
355     _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
356     _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
357
358     // These don't work, use a dummy based on altitude
359     // float P = get_Static_pressure();
360     // float T = get_Static_temperature();
361     float P = Atmosphere::getStdPressure(alt);
362     float T = Atmosphere::getStdTemperature(alt);
363     _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T)*MPS2KTS);
364     _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
365     _set_Mach_number(Atmosphere::calcMach(v[0], T));
366
367     // acceleration
368     Math::vmul33(xyz2ned, s->acc, v);
369     _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
370
371     Math::vmul33(s->orient, s->acc, v);
372     _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
373     _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
374
375     _fdm->getAirplane()->getPilotAccel(v);
376     _set_Accels_Pilot_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
377
378     // The one appears (!) to want inverted pilot acceleration
379     // numbers, in G's...
380     Math::mul3(1.0/9.8, v, v);
381     _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
382
383     // orientation
384     float alpha, beta;
385     Glue::calcAlphaBeta(s, &alpha, &beta);
386     _set_Alpha(alpha);
387     _set_Beta(beta);
388
389     float tmp[9];
390     Math::trans33(xyz2ned, tmp);
391     Math::mmul33(s->orient, tmp, tmp);
392     float roll, pitch, hdg;
393     Glue::orient2euler(tmp, &roll, &pitch, &hdg);
394     _set_Euler_Angles(roll, pitch, hdg);
395
396     // rotation
397     Math::vmul33(s->orient, s->rot, v);
398     _set_Omega_Body(v[0], -v[1], -v[2]);
399
400     Glue::calcEulerRates(s, &roll, &pitch, &hdg);
401     _set_Euler_Rates(roll, pitch, hdg);
402
403     // Fill out our engine and gear objects
404     int i;
405     for(i=0; i<get_num_gear(); i++) {
406         FGGearInterface* fgg = get_gear_unit(i);
407         Gear* g = airplane->getGear(i);
408         if(g->getBrake() != 0)
409             fgg->SetBrake(true);
410         if(g->getCompressFraction() != 0)
411             fgg->SetWoW(true);
412         else
413             fgg->SetWoW(false);
414         fgg->SetPosition(g->getExtension());
415     }
416
417     for(i=0; i<get_num_engines(); i++) {
418         FGEngInterface* fge = get_engine(i);
419         Thruster* t = model->getThruster(i);
420
421         fge->set_Running_Flag(true);
422         fge->set_Cranking_Flag(false);
423
424         // Note: assumes all tanks have the same fuel density!
425         fge->set_Fuel_Flow(CM2GALS * t->getFuelFlow()
426                            / airplane->getFuelDensity(0));
427
428         float tmp[3];
429         t->getThrust(tmp);
430         fge->set_prop_thrust(Math::mag3(tmp) * KG2LBS / 9.8);
431
432         PropEngine* pe = t->getPropEngine();
433         if(pe) {
434             fge->set_RPM(pe->getOmega() * RAD2RPM);
435
436             pe->getTorque(tmp);
437             float power = Math::mag3(tmp) * pe->getOmega();
438             float maxPower = pe->getPistonEngine()->getMaxPower();
439
440             fge->set_MaxHP(maxPower * W2HP);
441             fge->set_Percentage_Power(100 * power/maxPower);
442         }
443     }
444 }