]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
Interpolate the twist linearly over the wing.
[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 #include <Model/model.hxx>
8 #include <Main/location.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 static const float INHG2PA = 3386.389;
34 static const float SLUG2KG = 14.59390;
35
36 void YASim::printDEBUG()
37 {
38     static int debugCount = 0;
39     
40     debugCount++;
41     if(debugCount >= 3) {
42         debugCount = 0;
43
44 //      printf("N1 %5.1f N2 %5.1f FF %7.1f EPR %4.2f EGT %6.1f\n",
45 //             fgGetFloat("/engines/engine[0]/n1"),
46 //             fgGetFloat("/engines/engine[0]/n2"),
47 //             fgGetFloat("/engines/engine[0]/fuel-flow-gph"),
48 //             fgGetFloat("/engines/engine[0]/epr"),
49 //             fgGetFloat("/engines/engine[0]/egt"));
50
51 //      printf("gear: %f\n", fgGetFloat("/controls/gear-down"));
52
53 //      printf("alpha %5.1f beta %5.1f\n", get_Alpha()*57.3, get_Beta()*57.3);
54
55 //      printf("pilot: %f %f %f\n",
56 //             fgGetDouble("/sim/view/pilot/x-offset-m"),
57 //             fgGetDouble("/sim/view/pilot/y-offset-m"),
58 //             fgGetDouble("/sim/view/pilot/z-offset-m"));
59     }
60 }
61
62 YASim::YASim(double dt)
63 {
64 //     set_delta_t(dt);
65     _fdm = new FGFDM();
66
67     _dt = dt;
68
69     _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
70 }
71
72 void YASim::report()
73 {
74     Airplane* a = _fdm->getAirplane();
75
76     float aoa = a->getCruiseAoA() * RAD2DEG;
77     float tail = -1 * a->getTailIncidence() * RAD2DEG;
78     float drag = 1000 * a->getDragCoefficient();
79
80     SG_LOG(SG_FLIGHT,SG_INFO,"YASim solution results:");
81     SG_LOG(SG_FLIGHT,SG_INFO,"       Iterations: "<<a->getSolutionIterations());
82     SG_LOG(SG_FLIGHT,SG_INFO," Drag Coefficient: "<< drag);
83     SG_LOG(SG_FLIGHT,SG_INFO,"       Lift Ratio: "<<a->getLiftRatio());
84     SG_LOG(SG_FLIGHT,SG_INFO,"       Cruise AoA: "<< aoa);
85     SG_LOG(SG_FLIGHT,SG_INFO,"   Tail Incidence: "<< tail);
86     SG_LOG(SG_FLIGHT,SG_INFO,"Approach Elevator: "<<a->getApproachElevator());
87     
88
89     float cg[3];
90     char buf[256];
91     a->getModel()->getBody()->getCG(cg);
92     sprintf(buf, "            CG: %.3f, %.3f, %.3f", cg[0], cg[1], cg[2]);
93     SG_LOG(SG_FLIGHT, SG_INFO, buf);
94
95     if(a->getFailureMsg()) {
96         SG_LOG(SG_FLIGHT, SG_ALERT, "YASim SOLUTION FAILURE:");
97         SG_LOG(SG_FLIGHT, SG_ALERT, a->getFailureMsg());
98         exit(1);
99     }
100 }
101
102 void YASim::bind()
103 {
104     // Run the superclass bind to set up a bunch of property ties
105     FGInterface::bind();
106
107     // Now UNtie the ones that we are going to set ourselves.
108     fgUntie("/consumables/fuel/tank[0]/level-gal_us");
109     fgUntie("/consumables/fuel/tank[1]/level-gal_us");
110
111     char buf[256];
112     for(int i=0; i<_fdm->getAirplane()->getModel()->numThrusters(); i++) {
113         sprintf(buf, "/engines/engine[%d]/fuel-flow-gph", i); fgUntie(buf);
114         sprintf(buf, "/engines/engine[%d]/rpm", i);           fgUntie(buf);
115         sprintf(buf, "/engines/engine[%d]/mp-osi", i);        fgUntie(buf);
116         sprintf(buf, "/engines/engine[%d]/egt-degf", i);      fgUntie(buf);
117     }
118
119 }
120
121 void YASim::init()
122 {
123     Airplane* a = _fdm->getAirplane();
124     Model* m = a->getModel();
125
126     // Superclass hook
127     common_init();
128
129     m->setCrashed(false);
130
131     // Build a filename and parse it
132     SGPath f(globals->get_fg_root());
133     f.append("Aircraft-yasim");
134     f.append(fgGetString("/sim/aero"));
135     f.concat(".xml");
136     readXML(f.str(), *_fdm);
137
138     // Compile it into a real airplane, and tell the user what they got
139     a->compile();
140     report();
141
142     _fdm->init();
143
144     // Create some FG{Eng|Gear}Interface objects
145     int i;
146     for(i=0; i<a->numGear(); i++) {
147         Gear* g = a->getGear(i);
148         SGPropertyNode * node = fgGetNode("gear/gear", i, true);
149         float pos[3];
150         g->getPosition(pos);
151         node->setDoubleValue("xoffset-in", pos[0]);
152         node->setDoubleValue("yoffset-in", pos[1]);
153         node->setDoubleValue("zoffset-in", pos[2]);
154     }
155     for(i=0; i<m->numThrusters(); i++) {
156         // Sanify the initial input conditions
157         char buf[64];
158         sprintf(buf, "/controls/throttle[%d]", i);        fgSetFloat(buf, 0);
159         sprintf(buf, "/controls/mixture[%d]", i);         fgSetFloat(buf, 1);
160         sprintf(buf, "/controls/propeller-pitch[%d]", i); fgSetFloat(buf, 1);
161         sprintf(buf, "/controls/afterburner[%d]", i);     fgSetFloat(buf, 0);
162     }
163
164     fgSetFloat("/controls/slats", 0);
165     fgSetFloat("/controls/spoilers", 0);
166
167     // Are we at ground level?  If so, lift the plane up so the gear
168     // clear the ground.
169     double runway_altitude = get_Runway_altitude();
170     fgSetBool("/controls/gear-down", false);
171     if(get_Altitude() - runway_altitude < 50) {
172         float minGearZ = 1e18;
173         for(i=0; i<a->numGear(); i++) {
174             Gear* g = a->getGear(i);
175             float pos[3];
176             g->getPosition(pos);
177             if(pos[2] < minGearZ)
178                 minGearZ = pos[2];
179         }
180         _set_Altitude(runway_altitude - minGearZ*M2FT);
181         fgSetBool("/controls/gear-down", true);
182     }
183
184     // The pilot's eyepoint
185     float pilot[3];
186     a->getPilotPos(pilot);
187 //     fgSetFloat("/sim/view/pilot/x-offset-m", -pilot[0]);
188 //     fgSetFloat("/sim/view/pilot/y-offset-m", -pilot[1]);
189 //     fgSetFloat("/sim/view/pilot/z-offset-m", pilot[2]);
190
191     // Blank the state, and copy in ours
192     State s;
193     m->setState(&s);
194     copyToYASim(true);
195
196     _fdm->getExternalInput();
197     _fdm->getAirplane()->initEngines();
198
199     set_inited(true);
200 }
201
202 void YASim::update(double dt)
203 {
204     if (is_suspended())
205       return;
206
207     int iterations = _calc_multiloop(dt);
208
209     // If we're crashed, then we don't care
210     if(_fdm->getAirplane()->getModel()->isCrashed())
211       return;
212
213     int i;
214     for(i=0; i<iterations; i++) {
215             copyToYASim(false);
216             _fdm->iterate(_dt);
217             copyFromYASim();
218
219             printDEBUG();
220     }
221 }
222
223 void YASim::copyToYASim(bool copyState)
224 {
225     // Physical state
226     float lat = get_Latitude();
227     float lon = get_Longitude();
228     float alt = get_Altitude() * FT2M;
229     float roll = get_Phi();
230     float pitch = get_Theta();
231     float hdg = get_Psi();
232
233     // Environment
234     float wind[3];
235     wind[0] = get_V_north_airmass() * FT2M * -1.0;
236     wind[1] = get_V_east_airmass() * FT2M * -1.0;
237     wind[2] = get_V_down_airmass() * FT2M * -1.0;
238
239     // Get ground elevation from the FGinterface's FGlocation data
240     double ground = getACModel()->get3DModel()->getFGLocation()->get_cur_elev_m();
241     // cout << "YASIM: ground = " << ground << endl;
242
243     float pressure = fgGetFloat("/environment/pressure-inhg") * INHG2PA;
244     float temp = fgGetFloat("/environment/temperature-degc") + 273.15;
245     float dens = fgGetFloat("/environment/density-slugft3") 
246         * SLUG2KG * M2FT*M2FT*M2FT;
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, dens);
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     float P = fgGetDouble("/environment/pressure-inhg") * INHG2PA;
376     float T = fgGetDouble("/environment/temperature-degC") + 273.15;
377     float D = fgGetFloat("/environment/density-slugft3")
378         *SLUG2KG * M2FT*M2FT*M2FT;
379     _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T, D)*MPS2KTS);
380     _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
381     _set_Mach_number(Atmosphere::calcMach(v[0], T));
382
383     // acceleration
384     Math::vmul33(xyz2ned, s->acc, v);
385     _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
386
387     Math::vmul33(s->orient, s->acc, v);
388     _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
389     _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
390
391     _fdm->getAirplane()->getPilotAccel(v);
392     _set_Accels_Pilot_Body(-M2FT*v[0], M2FT*v[1], M2FT*v[2]);
393
394     // There is no property for pilot G's, but I need it for a panel
395     // instrument.  Hack this in here, and REMOVE IT WHEN IT FINDS A
396     // REAL HOME!
397     fgSetFloat("/accelerations/pilot-g", -v[2]/9.8);
398
399     // The one appears (!) to want inverted pilot acceleration
400     // numbers, in G's...
401     Math::mul3(1.0/9.8, v, v);
402     _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
403
404     // orientation
405     float alpha, beta;
406     Glue::calcAlphaBeta(s, &alpha, &beta);
407     _set_Alpha(alpha);
408     _set_Beta(beta);
409
410     float tmp[9];
411     Math::trans33(xyz2ned, tmp);
412     Math::mmul33(s->orient, tmp, tmp);
413     float roll, pitch, hdg;
414     Glue::orient2euler(tmp, &roll, &pitch, &hdg);
415     _set_Euler_Angles(roll, pitch, hdg);
416
417     // rotation
418     Math::vmul33(s->orient, s->rot, v);
419     _set_Omega_Body(v[0], -v[1], -v[2]);
420
421     Glue::calcEulerRates(s, &roll, &pitch, &hdg);
422     _set_Euler_Rates(roll, pitch, hdg);
423
424     // Fill out our engine and gear objects
425     int i;
426     for(i=0; i<airplane->numGear(); i++) {
427         Gear* g = airplane->getGear(i);
428         SGPropertyNode * node = fgGetNode("gear/gear", i, true);
429         node->setBoolValue("has-brake", g->getBrake() != 0);
430         node->setBoolValue("wow", g->getCompressFraction() != 0);
431         node->setFloatValue("compression-norm", g->getCompressFraction());
432     }
433
434     for(i=0; i<model->numThrusters(); i++) {
435         SGPropertyNode * node = fgGetNode("engines/engine", i, true);
436         Thruster* t = model->getThruster(i);
437
438         node->setBoolValue("running", t->isRunning());
439         node->setBoolValue("cranking", t->isCranking());
440
441         float tmp[3];
442         t->getThrust(tmp);
443         node->setDoubleValue("prop-thrust", Math::mag3(tmp) * KG2LBS / 9.8);
444
445         PropEngine* pe = t->getPropEngine();
446         if(pe) {
447             node->setDoubleValue("rpm", pe->getOmega() * RAD2RPM);
448
449             pe->getTorque(tmp);
450             float power = Math::mag3(tmp) * pe->getOmega();
451             float maxPower = pe->getPistonEngine()->getMaxPower();
452
453             node->setDoubleValue("max-hp", maxPower * W2HP);
454             node->setDoubleValue("power-pct", 100 * power/maxPower);
455         }
456     }
457 }