major optimization updates
[debian/openrocket] / src / net / sf / openrocket / simulation / RK4SimulationStepper.java
1 package net.sf.openrocket.simulation;
2
3 import java.util.Arrays;
4 import java.util.Random;
5
6 import net.sf.openrocket.aerodynamics.AerodynamicForces;
7 import net.sf.openrocket.aerodynamics.FlightConditions;
8 import net.sf.openrocket.aerodynamics.WarningSet;
9 import net.sf.openrocket.logging.LogHelper;
10 import net.sf.openrocket.models.atmosphere.AtmosphericConditions;
11 import net.sf.openrocket.simulation.exception.SimulationException;
12 import net.sf.openrocket.simulation.listeners.SimulationListenerHelper;
13 import net.sf.openrocket.startup.Application;
14 import net.sf.openrocket.util.Coordinate;
15 import net.sf.openrocket.util.MathUtil;
16 import net.sf.openrocket.util.Quaternion;
17 import net.sf.openrocket.util.Rotation2D;
18
19
20 public class RK4SimulationStepper extends AbstractSimulationStepper {
21         
22         private static final LogHelper log = Application.getLogger();
23         
24         /** Random value with which to XOR the random seed value */
25         private static final int SEED_RANDOMIZATION = 0x23E3A01F;
26         
27
28         /**
29          * A recommended reasonably accurate time step.
30          */
31         public static final double RECOMMENDED_TIME_STEP = 0.05;
32         
33         /**
34          * A recommended maximum angle step value.
35          */
36         public static final double RECOMMENDED_ANGLE_STEP = 3 * Math.PI / 180;
37         
38         /**
39          * A random amount that is added to pitch and yaw coefficients, plus or minus.
40          */
41         public static final double PITCH_YAW_RANDOM = 0.0005;
42         
43         /**
44          * Maximum roll step allowed.  This is selected as an uneven division of the full
45          * circle so that the simulation will sample the most wind directions
46          */
47         private static final double MAX_ROLL_STEP_ANGLE = 2 * 28.32 * Math.PI / 180;
48         //      private static final double MAX_ROLL_STEP_ANGLE = 8.32 * Math.PI/180;
49         
50         private static final double MAX_ROLL_RATE_CHANGE = 2 * Math.PI / 180;
51         private static final double MAX_PITCH_CHANGE = 4 * Math.PI / 180;
52         
53         private static final double MIN_TIME_STEP = 0.001;
54         
55
56         private Random random;
57         
58         
59
60
61         @Override
62         public RK4SimulationStatus initialize(SimulationStatus original) {
63                 
64                 RK4SimulationStatus status = new RK4SimulationStatus();
65                 
66                 status.copyFrom(original);
67                 
68                 SimulationConditions sim = original.getSimulationConditions();
69                 status.setLaunchRodDirection(new Coordinate(
70                                 Math.sin(sim.getLaunchRodAngle()) * Math.cos(sim.getLaunchRodDirection()),
71                                 Math.sin(sim.getLaunchRodAngle()) * Math.sin(sim.getLaunchRodDirection()),
72                                 Math.cos(sim.getLaunchRodAngle())
73                                 ));
74                 
75                 this.random = new Random(original.getSimulationConditions().getRandomSeed() ^ SEED_RANDOMIZATION);
76                 
77                 return status;
78         }
79         
80         
81
82
83         @Override
84         public void step(SimulationStatus simulationStatus, double maxTimeStep) throws SimulationException {
85                 
86                 RK4SimulationStatus status = (RK4SimulationStatus) simulationStatus;
87                 DataStore store = new DataStore();
88                 
89
90                 ////////  Perform RK4 integration:  ////////
91                 
92                 RK4SimulationStatus status2;
93                 RK4Parameters k1, k2, k3, k4;
94                 
95                 /*
96                  * Start with previous time step which is used to compute the initial thrust estimate.
97                  * Don't make it longer than maxTimeStep, but at least MIN_TIME_STEP.
98                  */
99                 store.timestep = status.getPreviousTimeStep();
100                 store.timestep = MathUtil.max(MathUtil.min(store.timestep, maxTimeStep), MIN_TIME_STEP);
101                 checkNaN(store.timestep);
102                 
103                 /*
104                  * Compute the initial thrust estimate.  This is used for the first time step computation.
105                  */
106                 store.thrustForce = calculateThrust(status, store.timestep, status.getPreviousAcceleration(),
107                                 status.getPreviousAtmosphericConditions(), false);
108                 
109
110                 /*
111                  * Perform RK4 integration.  Decide the time step length after the first step.
112                  */
113
114                 //// First position, k1 = f(t, y)
115                 
116                 k1 = computeParameters(status, store);
117                 
118                 /*
119                  * Select the actual time step to use.  It is the minimum of the following:
120                  *  dt[0]:  the user-specified time step (or 1/5th of it if still on the launch rod)
121                  *  dt[1]:  the value of maxTimeStep
122                  *  dt[2]:  the maximum pitch step angle limit
123                  *  dt[3]:  the maximum roll step angle limit
124                  *  dt[4]:  the maximum roll rate change limit
125                  *  dt[5]:  the maximum pitch change limit
126                  *  dt[6]:  1/10th of the launch rod length if still on the launch rod
127                  *  dt[7]:  1.50 times the previous time step
128                  * 
129                  * The limits #5 and #6 are required since near the steady-state roll rate the roll rate
130                  * may oscillate significantly even between the sub-steps of the RK4 integration.
131                  * 
132                  * The step is still at least 1/20th of the user-selected time step.
133                  */
134                 double[] dt = new double[8];
135                 Arrays.fill(dt, Double.MAX_VALUE);
136                 
137                 dt[0] = status.getSimulationConditions().getTimeStep();
138                 dt[1] = maxTimeStep;
139                 dt[2] = status.getSimulationConditions().getMaximumAngleStep() / store.lateralPitchRate;
140                 dt[3] = Math.abs(MAX_ROLL_STEP_ANGLE / store.flightConditions.getRollRate());
141                 dt[4] = Math.abs(MAX_ROLL_RATE_CHANGE / store.rollAcceleration);
142                 dt[5] = Math.abs(MAX_PITCH_CHANGE / store.lateralPitchAcceleration);
143                 if (!status.isLaunchRodCleared()) {
144                         dt[0] /= 5.0;
145                         dt[6] = status.getSimulationConditions().getLaunchRodLength() / k1.v.length() / 10;
146                 }
147                 dt[7] = 1.5 * status.getPreviousTimeStep();
148                 
149                 store.timestep = Double.MAX_VALUE;
150                 int limitingValue = -1;
151                 for (int i = 0; i < dt.length; i++) {
152                         if (dt[i] < store.timestep) {
153                                 store.timestep = dt[i];
154                                 limitingValue = i;
155                         }
156                 }
157                 
158                 double minTimeStep = status.getSimulationConditions().getTimeStep() / 20;
159                 if (store.timestep < minTimeStep) {
160                         log.verbose("Too small time step " + store.timestep + " (limiting factor " + limitingValue + "), using " +
161                                         minTimeStep + " instead.");
162                         store.timestep = minTimeStep;
163                 } else {
164                         log.verbose("Selected time step " + store.timestep + " (limiting factor " + limitingValue + ")");
165                 }
166                 checkNaN(store.timestep);
167                 
168                 /*
169                  * Compute the correct thrust for this time step.  If the original thrust estimate differs more
170                  * than 10% from the true value then recompute the RK4 step 1.  The 10% error in step 1 is
171                  * diminished by it affecting only 1/6th of the total, so it's an acceptable error.
172                  */
173                 double thrustEstimate = store.thrustForce;
174                 store.thrustForce = calculateThrust(status, store.timestep, store.longitudinalAcceleration,
175                                 store.atmosphericConditions, true);
176                 double thrustDiff = Math.abs(store.thrustForce - thrustEstimate);
177                 // Log if difference over 1%, recompute if over 10%
178                 if (thrustDiff > 0.01 * thrustEstimate) {
179                         if (thrustDiff > 0.1 * thrustEstimate + 0.001) {
180                                 log.debug("Thrust estimate differs from correct value by " +
181                                                 (Math.rint(1000 * (thrustDiff + 0.000001) / thrustEstimate) / 10.0) + "%," +
182                                                 " estimate=" + thrustEstimate +
183                                                 " correct=" + store.thrustForce +
184                                                 " timestep=" + store.timestep +
185                                                 ", recomputing k1 parameters");
186                                 k1 = computeParameters(status, store);
187                         } else {
188                                 log.verbose("Thrust estimate differs from correct value by " +
189                                                 (Math.rint(1000 * (thrustDiff + 0.000001) / thrustEstimate) / 10.0) + "%," +
190                                                 " estimate=" + thrustEstimate +
191                                                 " correct=" + store.thrustForce +
192                                                 " timestep=" + store.timestep +
193                                                 ", error acceptable");
194                         }
195                 }
196                 
197                 // Store data
198                 // TODO: MEDIUM: Store acceleration etc of entire RK4 step, store should be cloned or something...
199                 storeData(status, store);
200                 
201
202                 //// Second position, k2 = f(t + h/2, y + k1*h/2)
203                 
204                 status2 = status.clone();
205                 status2.setSimulationTime(status.getSimulationTime() + store.timestep / 2);
206                 status2.setRocketPosition(status.getRocketPosition().add(k1.v.multiply(store.timestep / 2)));
207                 status2.setRocketVelocity(status.getRocketVelocity().add(k1.a.multiply(store.timestep / 2)));
208                 status2.setRocketOrientationQuaternion(status.getRocketOrientationQuaternion().multiplyLeft(Quaternion.rotation(k1.rv.multiply(store.timestep / 2))));
209                 status2.setRocketRotationVelocity(status.getRocketRotationVelocity().add(k1.ra.multiply(store.timestep / 2)));
210                 
211                 k2 = computeParameters(status2, store);
212                 
213
214                 //// Third position, k3 = f(t + h/2, y + k2*h/2)
215                 
216                 status2 = status.clone();
217                 status2.setSimulationTime(status.getSimulationTime() + store.timestep / 2);
218                 status2.setRocketPosition(status.getRocketPosition().add(k2.v.multiply(store.timestep / 2)));
219                 status2.setRocketVelocity(status.getRocketVelocity().add(k2.a.multiply(store.timestep / 2)));
220                 status2.setRocketOrientationQuaternion(status2.getRocketOrientationQuaternion().multiplyLeft(Quaternion.rotation(k2.rv.multiply(store.timestep / 2))));
221                 status2.setRocketRotationVelocity(status.getRocketRotationVelocity().add(k2.ra.multiply(store.timestep / 2)));
222                 
223                 k3 = computeParameters(status2, store);
224                 
225
226                 //// Fourth position, k4 = f(t + h, y + k3*h)
227                 
228                 status2 = status.clone();
229                 status2.setSimulationTime(status.getSimulationTime() + store.timestep);
230                 status2.setRocketPosition(status.getRocketPosition().add(k3.v.multiply(store.timestep)));
231                 status2.setRocketVelocity(status.getRocketVelocity().add(k3.a.multiply(store.timestep)));
232                 status2.setRocketOrientationQuaternion(status2.getRocketOrientationQuaternion().multiplyLeft(Quaternion.rotation(k3.rv.multiply(store.timestep))));
233                 status2.setRocketRotationVelocity(status.getRocketRotationVelocity().add(k3.ra.multiply(store.timestep)));
234                 
235                 k4 = computeParameters(status2, store);
236                 
237
238                 //// Sum all together,  y(n+1) = y(n) + h*(k1 + 2*k2 + 2*k3 + k4)/6
239                 
240
241
242                 Coordinate deltaV, deltaP, deltaR, deltaO;
243                 deltaV = k2.a.add(k3.a).multiply(2).add(k1.a).add(k4.a).multiply(store.timestep / 6);
244                 deltaP = k2.v.add(k3.v).multiply(2).add(k1.v).add(k4.v).multiply(store.timestep / 6);
245                 deltaR = k2.ra.add(k3.ra).multiply(2).add(k1.ra).add(k4.ra).multiply(store.timestep / 6);
246                 deltaO = k2.rv.add(k3.rv).multiply(2).add(k1.rv).add(k4.rv).multiply(store.timestep / 6);
247                 
248
249
250                 status.setRocketVelocity(status.getRocketVelocity().add(deltaV));
251                 status.setRocketPosition(status.getRocketPosition().add(deltaP));
252                 status.setRocketRotationVelocity(status.getRocketRotationVelocity().add(deltaR));
253                 status.setRocketOrientationQuaternion(status.getRocketOrientationQuaternion().multiplyLeft(Quaternion.rotation(deltaO)).normalizeIfNecessary());
254                 
255                 status.setSimulationTime(status.getSimulationTime() + store.timestep);
256                 
257                 status.setPreviousTimeStep(store.timestep);
258         }
259         
260         
261
262
263
264         private RK4Parameters computeParameters(RK4SimulationStatus status, DataStore dataStore)
265                         throws SimulationException {
266                 RK4Parameters params = new RK4Parameters();
267                 
268                 //              if (dataStore == null) {
269                 //                      dataStore = new DataStore();
270                 //              }
271                 
272                 calculateAcceleration(status, dataStore);
273                 params.a = dataStore.linearAcceleration;
274                 params.ra = dataStore.angularAcceleration;
275                 params.v = status.getRocketVelocity();
276                 params.rv = status.getRocketRotationVelocity();
277                 
278                 checkNaN(params.a);
279                 checkNaN(params.ra);
280                 checkNaN(params.v);
281                 checkNaN(params.rv);
282                 
283                 return params;
284         }
285         
286         
287
288
289
290         /**
291          * Calculate the linear and angular acceleration at the given status.  The results
292          * are stored in the fields {@link #linearAcceleration} and {@link #angularAcceleration}.
293          *  
294          * @param status   the status of the rocket.
295          * @throws SimulationException 
296          */
297         private void calculateAcceleration(RK4SimulationStatus status, DataStore store) throws SimulationException {
298                 
299                 // Call pre-listeners
300                 store.accelerationData = SimulationListenerHelper.firePreAccelerationCalculation(status);
301                 if (store.accelerationData != null) {
302                         return;
303                 }
304                 
305                 // Compute the forces affecting the rocket
306                 calculateForces(status, store);
307                 
308                 // Calculate mass data
309                 store.massData = calculateMassData(status);
310                 
311
312                 // Calculate the forces from the aerodynamic coefficients
313                 
314                 double dynP = (0.5 * store.flightConditions.getAtmosphericConditions().getDensity() *
315                                         MathUtil.pow2(store.flightConditions.getVelocity()));
316                 double refArea = store.flightConditions.getRefArea();
317                 double refLength = store.flightConditions.getRefLength();
318                 
319
320                 // Linear forces in rocket coordinates
321                 store.dragForce = store.forces.getCaxial() * dynP * refArea;
322                 double fN = store.forces.getCN() * dynP * refArea;
323                 double fSide = store.forces.getCside() * dynP * refArea;
324                 
325                 double forceZ = store.thrustForce - store.dragForce;
326                 
327                 store.linearAcceleration = new Coordinate(-fN / store.massData.getCG().weight,
328                                         -fSide / store.massData.getCG().weight,
329                                         forceZ / store.massData.getCG().weight);
330                 
331                 store.linearAcceleration = store.thetaRotation.rotateZ(store.linearAcceleration);
332                 
333                 // Convert into world coordinates and add effect of gravity
334                 store.linearAcceleration = status.getRocketOrientationQuaternion().rotate(store.linearAcceleration);
335                 
336                 store.gravity = modelGravity(status);
337                 store.linearAcceleration = store.linearAcceleration.sub(0, 0, store.gravity);
338                 
339
340                 // If still on the launch rod, project acceleration onto launch rod direction and
341                 // set angular acceleration to zero.
342                 if (!status.isLaunchRodCleared()) {
343                         
344                         store.linearAcceleration = status.getLaunchRodDirection().multiply(
345                                                 store.linearAcceleration.dot(status.getLaunchRodDirection()));
346                         store.angularAcceleration = Coordinate.NUL;
347                         store.rollAcceleration = 0;
348                         store.lateralPitchAcceleration = 0;
349                         
350                 } else {
351                         
352                         // Shift moments to CG
353                         double Cm = store.forces.getCm() - store.forces.getCN() * store.massData.getCG().x / refLength;
354                         double Cyaw = store.forces.getCyaw() - store.forces.getCside() * store.massData.getCG().x / refLength;
355                         
356                         // Compute moments
357                         double momX = -Cyaw * dynP * refArea * refLength;
358                         double momY = Cm * dynP * refArea * refLength;
359                         double momZ = store.forces.getCroll() * dynP * refArea * refLength;
360                         
361                         // Compute acceleration in rocket coordinates
362                         store.angularAcceleration = new Coordinate(momX / store.massData.getLongitudinalInertia(),
363                                                 momY / store.massData.getLongitudinalInertia(), momZ / store.massData.getRotationalInertia());
364                         
365                         store.rollAcceleration = store.angularAcceleration.z;
366                         // TODO: LOW: This should be hypot, but does it matter?
367                         store.lateralPitchAcceleration = MathUtil.max(Math.abs(store.angularAcceleration.x),
368                                                 Math.abs(store.angularAcceleration.y));
369                         
370                         store.angularAcceleration = store.thetaRotation.rotateZ(store.angularAcceleration);
371                         
372                         // Convert to world coordinates
373                         store.angularAcceleration = status.getRocketOrientationQuaternion().rotate(store.angularAcceleration);
374                         
375                 }
376                 
377                 // Call post-listeners
378                 store.accelerationData = SimulationListenerHelper.firePostAccelerationCalculation(status, store.accelerationData);
379         }
380         
381         
382
383         /**
384          * Calculate the aerodynamic forces into the data store.  This method also handles
385          * whether to include aerodynamic computation warnings or not.
386          */
387         private void calculateForces(RK4SimulationStatus status, DataStore store) throws SimulationException {
388                 
389                 // Call pre-listeners
390                 store.forces = SimulationListenerHelper.firePreAerodynamicCalculation(status);
391                 if (store.forces != null) {
392                         return;
393                 }
394                 
395                 // Compute flight conditions
396                 calculateFlightConditions(status, store);
397                 
398                 /*
399                  * Check whether to store warnings or not.  Warnings are ignored when on the 
400                  * launch rod or 0.25 seconds after departure, and when the velocity has dropped
401                  * below 20% of the max. velocity.
402                  */
403                 WarningSet warnings = status.getWarnings();
404                 status.setMaxZVelocity(MathUtil.max(status.getMaxZVelocity(), status.getRocketVelocity().z));
405                 
406                 if (!status.isLaunchRodCleared()) {
407                         warnings = null;
408                 } else {
409                         if (status.getRocketVelocity().z < 0.2 * status.getMaxZVelocity())
410                                 warnings = null;
411                         if (status.getStartWarningTime() < 0)
412                                 status.setStartWarningTime(status.getSimulationTime() + 0.25);
413                 }
414                 if (status.getSimulationTime() < status.getStartWarningTime())
415                         warnings = null;
416                 
417
418                 // Calculate aerodynamic forces
419                 store.forces = status.getSimulationConditions().getAerodynamicCalculator()
420                                 .getAerodynamicForces(status.getConfiguration(), store.flightConditions, warnings);
421                 
422
423                 // Add very small randomization to yaw & pitch moments to prevent over-perfect flight
424                 // TODO: HIGH: This should rather be performed as a listener
425                 store.forces.setCm(store.forces.getCm() + (PITCH_YAW_RANDOM * 2 * (random.nextDouble() - 0.5)));
426                 store.forces.setCyaw(store.forces.getCyaw() + (PITCH_YAW_RANDOM * 2 * (random.nextDouble() - 0.5)));
427                 
428
429                 // Call post-listeners
430                 store.forces = SimulationListenerHelper.firePostAerodynamicCalculation(status, store.forces);
431         }
432         
433         
434
435         /**
436          * Calculate and return the flight conditions for the current rocket status.
437          * Listeners can override these if necessary.
438          * <p>
439          * Additionally the fields thetaRotation and lateralPitchRate are defined in
440          * the data store, and can be used after calling this method.
441          */
442         private void calculateFlightConditions(RK4SimulationStatus status, DataStore store)
443                         throws SimulationException {
444                 
445                 // Call pre listeners, allow complete override
446                 store.flightConditions = SimulationListenerHelper.firePreFlightConditions(
447                                 status);
448                 if (store.flightConditions != null) {
449                         // Compute the store values
450                         store.thetaRotation = new Rotation2D(store.flightConditions.getTheta());
451                         store.lateralPitchRate = Math.hypot(store.flightConditions.getPitchRate(), store.flightConditions.getYawRate());
452                         return;
453                 }
454                 
455
456
457                 //// Atmospheric conditions
458                 AtmosphericConditions atmosphere = modelAtmosphericConditions(status);
459                 store.flightConditions = new FlightConditions(status.getConfiguration());
460                 store.flightConditions.setAtmosphericConditions(atmosphere);
461                 
462
463                 //// Local wind speed and direction
464                 Coordinate windSpeed = modelWindVelocity(status);
465                 Coordinate airSpeed = status.getRocketVelocity().add(windSpeed);
466                 airSpeed = status.getRocketOrientationQuaternion().invRotate(airSpeed);
467                 
468
469                 // Lateral direction:
470                 double len = MathUtil.hypot(airSpeed.x, airSpeed.y);
471                 if (len > 0.0001) {
472                         store.thetaRotation = new Rotation2D(airSpeed.y / len, airSpeed.x / len);
473                         store.flightConditions.setTheta(Math.atan2(airSpeed.y, airSpeed.x));
474                 } else {
475                         store.thetaRotation = Rotation2D.ID;
476                         store.flightConditions.setTheta(0);
477                 }
478                 
479                 double velocity = airSpeed.length();
480                 store.flightConditions.setVelocity(velocity);
481                 if (velocity > 0.01) {
482                         // aoa must be calculated from the monotonous cosine
483                         // sine can be calculated by a simple division
484                         store.flightConditions.setAOA(Math.acos(airSpeed.z / velocity), len / velocity);
485                 } else {
486                         store.flightConditions.setAOA(0);
487                 }
488                 
489
490                 // Roll, pitch and yaw rate
491                 Coordinate rot = status.getRocketOrientationQuaternion().invRotate(status.getRocketRotationVelocity());
492                 rot = store.thetaRotation.invRotateZ(rot);
493                 
494                 store.flightConditions.setRollRate(rot.z);
495                 if (len < 0.001) {
496                         store.flightConditions.setPitchRate(0);
497                         store.flightConditions.setYawRate(0);
498                         store.lateralPitchRate = 0;
499                 } else {
500                         store.flightConditions.setPitchRate(rot.y);
501                         store.flightConditions.setYawRate(rot.x);
502                         // TODO: LOW: set this as power of two?
503                         store.lateralPitchRate = MathUtil.hypot(rot.x, rot.y);
504                 }
505                 
506
507                 // Call post listeners
508                 FlightConditions c = SimulationListenerHelper.firePostFlightConditions(
509                                 status, store.flightConditions);
510                 if (c != store.flightConditions) {
511                         // Listeners changed the values, recalculate data store
512                         store.flightConditions = c;
513                         store.thetaRotation = new Rotation2D(store.flightConditions.getTheta());
514                         store.lateralPitchRate = Math.hypot(store.flightConditions.getPitchRate(), store.flightConditions.getYawRate());
515                 }
516                 
517         }
518         
519         
520
521         private void storeData(RK4SimulationStatus status, DataStore store) {
522                 
523                 FlightDataBranch data = status.getFlightData();
524                 boolean extra = status.getSimulationConditions().isCalculateExtras();
525                 
526                 data.addPoint();
527                 data.setValue(FlightDataType.TYPE_TIME, status.getSimulationTime());
528                 data.setValue(FlightDataType.TYPE_ALTITUDE, status.getRocketPosition().z);
529                 data.setValue(FlightDataType.TYPE_POSITION_X, status.getRocketPosition().x);
530                 data.setValue(FlightDataType.TYPE_POSITION_Y, status.getRocketPosition().y);
531                 
532                 if (extra) {
533                         data.setValue(FlightDataType.TYPE_POSITION_XY,
534                                         MathUtil.hypot(status.getRocketPosition().x, status.getRocketPosition().y));
535                         data.setValue(FlightDataType.TYPE_POSITION_DIRECTION,
536                                         Math.atan2(status.getRocketPosition().y, status.getRocketPosition().x));
537                         
538                         data.setValue(FlightDataType.TYPE_VELOCITY_XY,
539                                         MathUtil.hypot(status.getRocketVelocity().x, status.getRocketVelocity().y));
540                         
541                         if (store.linearAcceleration != null) {
542                                 data.setValue(FlightDataType.TYPE_ACCELERATION_XY,
543                                                 MathUtil.hypot(store.linearAcceleration.x, store.linearAcceleration.y));
544                                 
545                                 data.setValue(FlightDataType.TYPE_ACCELERATION_TOTAL, store.linearAcceleration.length());
546                         }
547                         
548                         if (store.flightConditions != null) {
549                                 double Re = (store.flightConditions.getVelocity() *
550                                                 status.getConfiguration().getLength() /
551                                                 store.flightConditions.getAtmosphericConditions().getKinematicViscosity());
552                                 data.setValue(FlightDataType.TYPE_REYNOLDS_NUMBER, Re);
553                         }
554                 }
555                 
556                 data.setValue(FlightDataType.TYPE_VELOCITY_Z, status.getRocketVelocity().z);
557                 if (store.linearAcceleration != null) {
558                         data.setValue(FlightDataType.TYPE_ACCELERATION_Z, store.linearAcceleration.z);
559                 }
560                 
561                 if (store.flightConditions != null) {
562                         data.setValue(FlightDataType.TYPE_VELOCITY_TOTAL, status.getRocketVelocity().length());
563                         data.setValue(FlightDataType.TYPE_MACH_NUMBER, store.flightConditions.getMach());
564                 }
565                 
566                 if (store.massData != null) {
567                         data.setValue(FlightDataType.TYPE_CG_LOCATION, store.massData.getCG().x);
568                 }
569                 if (status.isLaunchRodCleared()) {
570                         // Don't include CP and stability with huge launch AOA
571                         if (store.forces != null) {
572                                 data.setValue(FlightDataType.TYPE_CP_LOCATION, store.forces.getCP().x);
573                         }
574                         if (store.forces != null && store.flightConditions != null && store.massData != null) {
575                                 data.setValue(FlightDataType.TYPE_STABILITY,
576                                                 (store.forces.getCP().x - store.massData.getCG().x) / store.flightConditions.getRefLength());
577                         }
578                 }
579                 if (store.massData != null) {
580                         data.setValue(FlightDataType.TYPE_MASS, store.massData.getCG().weight);
581                         data.setValue(FlightDataType.TYPE_LONGITUDINAL_INERTIA, store.massData.getLongitudinalInertia());
582                         data.setValue(FlightDataType.TYPE_ROTATIONAL_INERTIA, store.massData.getRotationalInertia());
583                 }
584                 
585                 data.setValue(FlightDataType.TYPE_THRUST_FORCE, store.thrustForce);
586                 data.setValue(FlightDataType.TYPE_DRAG_FORCE, store.dragForce);
587                 
588                 if (status.isLaunchRodCleared() && store.forces != null) {
589                         if (store.massData != null && store.flightConditions != null) {
590                                 data.setValue(FlightDataType.TYPE_PITCH_MOMENT_COEFF,
591                                                 store.forces.getCm() - store.forces.getCN() * store.massData.getCG().x / store.flightConditions.getRefLength());
592                                 data.setValue(FlightDataType.TYPE_YAW_MOMENT_COEFF,
593                                                 store.forces.getCyaw() - store.forces.getCside() * store.massData.getCG().x / store.flightConditions.getRefLength());
594                         }
595                         data.setValue(FlightDataType.TYPE_NORMAL_FORCE_COEFF, store.forces.getCN());
596                         data.setValue(FlightDataType.TYPE_SIDE_FORCE_COEFF, store.forces.getCside());
597                         data.setValue(FlightDataType.TYPE_ROLL_MOMENT_COEFF, store.forces.getCroll());
598                         data.setValue(FlightDataType.TYPE_ROLL_FORCING_COEFF, store.forces.getCrollForce());
599                         data.setValue(FlightDataType.TYPE_ROLL_DAMPING_COEFF, store.forces.getCrollDamp());
600                         data.setValue(FlightDataType.TYPE_PITCH_DAMPING_MOMENT_COEFF,
601                                         store.forces.getPitchDampingMoment());
602                 }
603                 
604                 if (store.forces != null) {
605                         data.setValue(FlightDataType.TYPE_DRAG_COEFF, store.forces.getCD());
606                         data.setValue(FlightDataType.TYPE_AXIAL_DRAG_COEFF, store.forces.getCaxial());
607                         data.setValue(FlightDataType.TYPE_FRICTION_DRAG_COEFF, store.forces.getFrictionCD());
608                         data.setValue(FlightDataType.TYPE_PRESSURE_DRAG_COEFF, store.forces.getPressureCD());
609                         data.setValue(FlightDataType.TYPE_BASE_DRAG_COEFF, store.forces.getBaseCD());
610                 }
611                 
612                 if (store.flightConditions != null) {
613                         data.setValue(FlightDataType.TYPE_REFERENCE_LENGTH, store.flightConditions.getRefLength());
614                         data.setValue(FlightDataType.TYPE_REFERENCE_AREA, store.flightConditions.getRefArea());
615                         
616                         data.setValue(FlightDataType.TYPE_PITCH_RATE, store.flightConditions.getPitchRate());
617                         data.setValue(FlightDataType.TYPE_YAW_RATE, store.flightConditions.getYawRate());
618                         data.setValue(FlightDataType.TYPE_ROLL_RATE, store.flightConditions.getRollRate());
619                         
620                         data.setValue(FlightDataType.TYPE_AOA, store.flightConditions.getAOA());
621                 }
622                 
623
624                 if (extra) {
625                         Coordinate c = status.getRocketOrientationQuaternion().rotateZ();
626                         double theta = Math.atan2(c.z, MathUtil.hypot(c.x, c.y));
627                         double phi = Math.atan2(c.y, c.x);
628                         if (phi < -(Math.PI - 0.0001))
629                                 phi = Math.PI;
630                         data.setValue(FlightDataType.TYPE_ORIENTATION_THETA, theta);
631                         data.setValue(FlightDataType.TYPE_ORIENTATION_PHI, phi);
632                 }
633                 
634                 data.setValue(FlightDataType.TYPE_WIND_VELOCITY, store.windSpeed);
635                 
636                 if (store.flightConditions != null) {
637                         data.setValue(FlightDataType.TYPE_AIR_TEMPERATURE,
638                                         store.flightConditions.getAtmosphericConditions().getTemperature());
639                         data.setValue(FlightDataType.TYPE_AIR_PRESSURE,
640                                         store.flightConditions.getAtmosphericConditions().getPressure());
641                         data.setValue(FlightDataType.TYPE_SPEED_OF_SOUND,
642                                         store.flightConditions.getAtmosphericConditions().getMachSpeed());
643                 }
644                 
645
646                 data.setValue(FlightDataType.TYPE_TIME_STEP, store.timestep);
647                 data.setValue(FlightDataType.TYPE_COMPUTATION_TIME,
648                                 (System.nanoTime() - status.getSimulationStartWallTime()) / 1000000000.0);
649         }
650         
651         
652
653
654         private static class RK4Parameters {
655                 /** Linear acceleration */
656                 public Coordinate a;
657                 /** Linear velocity */
658                 public Coordinate v;
659                 /** Rotational acceleration */
660                 public Coordinate ra;
661                 /** Rotational velocity */
662                 public Coordinate rv;
663         }
664         
665         private static class DataStore {
666                 public double timestep = Double.NaN;
667                 
668                 public AccelerationData accelerationData;
669                 
670                 public AtmosphericConditions atmosphericConditions;
671                 
672                 public FlightConditions flightConditions;
673                 
674                 public double longitudinalAcceleration = Double.NaN;
675                 
676                 public MassData massData;
677                 
678                 public Coordinate linearAcceleration;
679                 public Coordinate angularAcceleration;
680                 
681                 // set by calculateFlightConditions and calculateAcceleration:
682                 public AerodynamicForces forces;
683                 public double windSpeed = Double.NaN;
684                 public double gravity = Double.NaN;
685                 public double thrustForce = Double.NaN;
686                 public double dragForce = Double.NaN;
687                 public double lateralPitchRate = Double.NaN;
688                 
689                 public double rollAcceleration = Double.NaN;
690                 public double lateralPitchAcceleration = Double.NaN;
691                 
692                 public Rotation2D thetaRotation;
693                 
694         }
695         
696 }