]> git.mxchange.org Git - flightgear.git/blob - src/FDM/YASim/YASim.cxx
Initial revision of Andy Ross's YASim code. This is (Y)et (A)nother Flight
[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/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
20 #include "YASim.hxx"
21
22 using namespace yasim;
23
24 static const float RAD2DEG = 180/3.14159265358979323846;
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
30 void YASim::printDEBUG()
31 {
32     static int debugCount = 0;
33     
34     debugCount++;
35     if(debugCount >= 3) {
36         debugCount = 0;
37
38 //      printf("RPM %.1f FF %.1f\n",
39 //             fgGetFloat("/engines/engine[0]/rpm"),
40 //             fgGetFloat("/engines/engine[0]/fuel-flow-gph"));
41
42 //      printf("gear: %f\n", fgGetFloat("/controls/gear-down"));
43
44 //      printf("alpha %5.1f beta %5.1f\n", get_Alpha()*57.3, get_Beta()*57.3);
45
46 //      printf("pilot: %f %f %f\n",
47 //             fgGetDouble("/sim/view/pilot/x-offset-m"),
48 //             fgGetDouble("/sim/view/pilot/y-offset-m"),
49 //             fgGetDouble("/sim/view/pilot/z-offset-m"));
50     }
51 }
52
53 YASim::YASim(double dt)
54 {
55     set_delta_t(dt);
56     _fdm = new FGFDM();
57
58     // Because the integration method is via fourth-order Runge-Kutta,
59     // we only get an "output" state for every 4 times the internal
60     // forces are calculated.  So divide dt by four to account for
61     // this, and only run an iteration every fourth time through
62     // update.
63     _dt = dt * 4;
64     _fdm->getAirplane()->getModel()->getIntegrator()->setInterval(_dt);
65     _updateCount = 0;
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::init()
97 {
98     Airplane* a = _fdm->getAirplane();
99     Model* m = a->getModel();
100
101     // Superclass hook
102     common_init();
103
104     // Build a filename and parse it
105     SGPath f(globals->get_fg_root());
106     f.append("Aircraft");
107     f.append(fgGetString("/sim/aircraft"));
108     f.concat(".xml");
109     readXML(f.str(), *_fdm);
110
111     // Compile it into a real airplane, and tell the user what they got
112     a->compile();
113     report();
114
115     _fdm->init();
116
117     // Lift the plane up so the gear clear the ground
118     float minGearZ = 1e18;
119     for(int i=0; i<a->numGear(); i++) {
120         Gear* g = a->getGear(i);
121         float pos[3];
122         g->getPosition(pos);
123         if(pos[2] < minGearZ)
124             minGearZ = pos[2];
125     }
126     _set_Altitude(get_Altitude() - minGearZ*M2FT);
127
128     // The pilot's eyepoint
129     float pilot[3];
130     a->getPilotPos(pilot);
131     fgSetFloat("/sim/view/pilot/x-offset-m", -pilot[0]);
132     fgSetFloat("/sim/view/pilot/y-offset-m", -pilot[1]);
133     fgSetFloat("/sim/view/pilot/z-offset-m", pilot[2]);
134
135     // Blank the state, and copy in ours
136     State s;
137     m->setState(&s);
138
139     copyToYASim(true);
140     set_inited(true);
141 }
142
143 bool YASim::update(int iterations)
144 {
145     for(int i=0; i<iterations; i++) {
146         // Remember, update only every 4th call
147         _updateCount++;
148         if(_updateCount >= 4) {
149
150             copyToYASim(false);
151             _fdm->iterate(_dt);
152             copyFromYASim();
153
154             printDEBUG();
155
156             _updateCount = 0;
157         }
158     }
159
160     return true; // what does this mean?
161 }
162
163 void YASim::copyToYASim(bool copyState)
164 {
165     // Physical state
166     float lat = get_Latitude();
167     float lon = get_Longitude();
168     float alt = get_Altitude() * FT2M;
169     float roll = get_Phi();
170     float pitch = get_Theta();
171     float hdg = get_Psi();
172
173     // Environment
174     float wind[3];
175     wind[0] = get_V_north_airmass() * FT2M;
176     wind[1] = get_V_east_airmass() * FT2M;
177     wind[2] = get_V_down_airmass() * FT2M;
178     double ground = get_Runway_altitude() * FT2M;
179
180     // You'd this this would work, but it doesn't.  These values are
181     // always zero.  Use a "standard" pressure intstead.
182     //
183     // float pressure = get_Static_pressure();
184     // float temp = get_Static_temperature();
185     float pressure = Atmosphere::getStdPressure(alt);
186     float temp = Atmosphere::getStdTemperature(alt);
187
188     // Convert and set:
189     Model* model = _fdm->getAirplane()->getModel();
190     State s;
191     float xyz2ned[9];
192     Glue::xyz2nedMat(lat, lon, xyz2ned);
193
194     // position
195     Glue::geod2xyz(lat, lon, alt, s.pos);
196
197     // orientation
198     Glue::euler2orient(roll, pitch, hdg, s.orient);
199     Math::mmul33(s.orient, xyz2ned, s.orient);
200
201     // Copy in the existing velocity for now...
202     Math::set3(model->getState()->v, s.v);
203
204     if(copyState)
205         model->setState(&s);
206
207     // wind
208     Math::tmul33(xyz2ned, wind, wind);
209     model->setWind(wind);
210
211     // ground.  Calculate a cartesian coordinate for the ground under
212     // us, find the (geodetic) up vector normal to the ground, then
213     // use that to find the final (radius) term of the plane equation.
214     double xyz[3], gplane[3]; float up[3];
215     Glue::geod2xyz(lat, lon, ground, xyz);
216     Glue::geodUp(xyz, up); // FIXME, needless reverse computation...
217     for(int i=0; i<3; i++) gplane[i] = up[i];
218     double rad = gplane[0]*xyz[0] + gplane[1]*xyz[1] + gplane[2]*xyz[2];
219     model->setGroundPlane(gplane, rad);
220
221     // air
222     model->setAir(pressure, temp);
223 }
224
225 // All the settables:
226 //
227 // These are set below:
228 // _set_Accels_Local
229 // _set_Accels_Body
230 // _set_Accels_CG_Body 
231 // _set_Accels_Pilot_Body
232 // _set_Accels_CG_Body_N 
233 // _set_Velocities_Local
234 // _set_Velocities_Ground
235 // _set_Velocities_Wind_Body
236 // _set_Omega_Body
237 // _set_Euler_Rates
238 // _set_Euler_Angles
239 // _set_V_rel_wind
240 // _set_V_ground_speed
241 // _set_V_equiv_kts
242 // _set_V_calibrated_kts
243 // _set_Alpha
244 // _set_Beta
245 // _set_Mach_number
246 // _set_Climb_Rate
247 // _set_Tank1Fuel
248 // _set_Tank2Fuel
249 // _set_Altitude_AGL
250 // _set_Geodetic_Position
251 // _set_Runway_altitude
252
253 // Ignoring these, because they're unused:
254 // _set_Geocentric_Position
255 // _set_Geocentric_Rates
256 // _set_Cos_phi
257 // _set_Cos_theta
258 // _set_Earth_position_angle (WTF?)
259 // _set_Gamma_vert_rad
260 // _set_Inertias
261 // _set_T_Local_to_Body
262 // _set_CG_Position
263 // _set_Sea_Level_Radius
264
265 // Externally set via the weather code:
266 // _set_Velocities_Local_Airmass
267 // _set_Density
268 // _set_Static_pressure
269 // _set_Static_temperature
270 void YASim::copyFromYASim()
271 {
272     Model* model = _fdm->getAirplane()->getModel();
273     State* s = model->getState();
274
275     // position
276     double lat, lon, alt;
277     Glue::xyz2geod(s->pos, &lat, &lon, &alt);
278     _set_Geodetic_Position(lat, lon, alt*M2FT);
279
280     // UNUSED
281     //_set_Geocentric_Position(Glue::geod2geocLat(lat), lon, alt*M2FT);
282
283     // FIXME: there's a normal vector available too, use it.
284     float groundMSL = scenery.get_cur_elev();
285     _set_Runway_altitude(groundMSL*M2FT);
286     _set_Altitude_AGL((alt - groundMSL)*M2FT);
287
288     // useful conversion matrix
289     float xyz2ned[9];
290     Glue::xyz2nedMat(lat, lon, xyz2ned);
291
292     // velocity
293     float v[3];
294     Math::vmul33(xyz2ned, s->v, v);
295     _set_Velocities_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
296     _set_V_ground_speed(Math::sqrt(M2FT*v[0]*M2FT*v[0] +
297                                    M2FT*v[1]*M2FT*v[1]));
298     _set_Climb_Rate(-M2FT*v[2]);
299
300     // The HUD uses this, but inverts down (?!)
301     _set_Velocities_Ground(M2FT*v[0], M2FT*v[1], -M2FT*v[2]);
302
303     // _set_Geocentric_Rates(M2FT*v[0], M2FT*v[1], M2FT*v[2]); // UNUSED
304
305     Math::vmul33(s->orient, s->v, v);
306     _set_Velocities_Wind_Body(v[0]*M2FT, -v[1]*M2FT, -v[2]*M2FT);
307     _set_V_rel_wind(Math::mag3(v)*M2FT); // units?
308
309     // These don't work, use a dummy based on altitude
310     // float P = get_Static_pressure();
311     // float T = get_Static_temperature();
312     float P = Atmosphere::getStdPressure(alt);
313     float T = Atmosphere::getStdTemperature(alt);
314     _set_V_equiv_kts(Atmosphere::calcVEAS(v[0], P, T)*MPS2KTS);
315     _set_V_calibrated_kts(Atmosphere::calcVCAS(v[0], P, T)*MPS2KTS);
316     _set_Mach_number(Atmosphere::calcMach(v[0], T));
317
318     // acceleration
319     Math::vmul33(xyz2ned, s->acc, v);
320     _set_Accels_Local(M2FT*v[0], M2FT*v[1], M2FT*v[2]);
321
322     Math::vmul33(s->orient, s->acc, v);
323     _set_Accels_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
324     _set_Accels_CG_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
325
326     _fdm->getAirplane()->getPilotAccel(v);
327     _set_Accels_Pilot_Body(M2FT*v[0], -M2FT*v[1], -M2FT*v[2]);
328
329     // The one appears (!) to want inverted pilot acceleration
330     // numbers, in G's...
331     Math::mul3(1.0/9.8, v, v);
332     _set_Accels_CG_Body_N(v[0], -v[1], -v[2]);
333
334     // orientation
335     float alpha, beta;
336     Glue::calcAlphaBeta(s, &alpha, &beta);
337     _set_Alpha(alpha);
338     _set_Beta(beta);
339
340     float tmp[9];
341     Math::trans33(xyz2ned, tmp);
342     Math::mmul33(s->orient, tmp, tmp);
343     float roll, pitch, hdg;
344     Glue::orient2euler(tmp, &roll, &pitch, &hdg);
345     _set_Euler_Angles(roll, pitch, hdg);
346
347     // rotation
348     Math::vmul33(s->orient, s->rot, v);
349     _set_Omega_Body(v[0], -v[1], -v[2]);
350
351     Glue::calcEulerRates(s, &roll, &pitch, &hdg);
352     _set_Euler_Rates(roll, pitch, hdg);
353 }