create changelog entry
[debian/openrocket] / core / src / net / sf / openrocket / simulation / listeners / example / StopSimulationListener.java
1 package net.sf.openrocket.simulation.listeners.example;
2
3 import net.sf.openrocket.simulation.FlightEvent;
4 import net.sf.openrocket.simulation.SimulationStatus;
5 import net.sf.openrocket.simulation.exception.SimulationException;
6 import net.sf.openrocket.simulation.listeners.AbstractSimulationListener;
7
8 /**
9  * A simulation listener that stops the simulation after a specified number of steps or
10  * after a specified abount of simulation time.
11  * 
12  * @author Sampo Niskanen <sampo.niskanen@iki.fi>
13  */
14 public class StopSimulationListener extends AbstractSimulationListener {
15         
16         private final int REPORT = 500;
17         
18         private final double stopTime;
19         private final int stopStep;
20         
21         private int step = 0;
22         
23         private long startTime = -1;
24         private long time = -1;
25         
26         public StopSimulationListener(double t, int n) {
27                 stopTime = t;
28                 stopStep = n;
29         }
30         
31         @Override
32         public boolean handleFlightEvent(SimulationStatus status, FlightEvent event) {
33                 
34                 if (event.getType() == FlightEvent.Type.LAUNCH) {
35                         System.out.println("Simulation starting.");
36                         time = System.nanoTime();
37                         startTime = System.nanoTime();
38                 }
39                 
40                 return true;
41         }
42         
43         
44         @Override
45         public void postStep(SimulationStatus status) throws SimulationException {
46                 step++;
47                 if ((step % REPORT) == 0) {
48                         long t = System.nanoTime();
49                         
50                         System.out.printf("Step %4d, time=%.3f, took %d us/step (avg. %d us/step)\n",
51                                         step, status.getSimulationTime(), (t - time) / 1000 / REPORT, (t - startTime) / 1000 / step);
52                         time = t;
53                 }
54                 if (status.getSimulationTime() >= stopTime || step >= stopStep) {
55                         System.out.printf("Stopping simulation, step=%d time=%.3f\n", step, status.getSimulationTime());
56                         status.getEventQueue().add(new FlightEvent(FlightEvent.Type.SIMULATION_END,
57                                         status.getSimulationTime(), null));
58                 }
59         }
60         
61 }