1 package net.sf.openrocket.document;
3 import java.util.EventListener;
4 import java.util.EventObject;
7 import net.sf.openrocket.aerodynamics.AerodynamicCalculator;
8 import net.sf.openrocket.aerodynamics.BarrowmanCalculator;
9 import net.sf.openrocket.aerodynamics.WarningSet;
10 import net.sf.openrocket.logging.LogHelper;
11 import net.sf.openrocket.masscalc.BasicMassCalculator;
12 import net.sf.openrocket.masscalc.MassCalculator;
13 import net.sf.openrocket.rocketcomponent.Configuration;
14 import net.sf.openrocket.rocketcomponent.Rocket;
15 import net.sf.openrocket.simulation.BasicEventSimulationEngine;
16 import net.sf.openrocket.simulation.FlightData;
17 import net.sf.openrocket.simulation.RK4SimulationStepper;
18 import net.sf.openrocket.simulation.SimulationConditions;
19 import net.sf.openrocket.simulation.SimulationEngine;
20 import net.sf.openrocket.simulation.SimulationOptions;
21 import net.sf.openrocket.simulation.SimulationStepper;
22 import net.sf.openrocket.simulation.exception.SimulationException;
23 import net.sf.openrocket.simulation.exception.SimulationListenerException;
24 import net.sf.openrocket.simulation.listeners.SimulationListener;
25 import net.sf.openrocket.startup.Application;
26 import net.sf.openrocket.util.ArrayList;
27 import net.sf.openrocket.util.BugException;
28 import net.sf.openrocket.util.ChangeSource;
29 import net.sf.openrocket.util.SafetyMutex;
30 import net.sf.openrocket.util.StateChangeListener;
33 * A class defining a simulation, its conditions and simulated data.
35 * This class is not thread-safe and enforces single-threaded access with a
38 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
40 public class Simulation implements ChangeSource, Cloneable {
41 private static final LogHelper log = Application.getLogger();
43 public static enum Status {
47 /** Loaded from file, status probably up-to-date */
53 /** Imported external data */
56 /** Not yet simulated */
60 private SafetyMutex mutex = SafetyMutex.newInstance();
62 private final Rocket rocket;
63 private final OpenRocketDocument document;
65 private String name = "";
67 private Status status = Status.NOT_SIMULATED;
69 /** The conditions to use */
70 // TODO: HIGH: Change to use actual conditions class??
71 private SimulationOptions options;
73 private ArrayList<String> simulationListeners = new ArrayList<String>();
75 private final Class<? extends SimulationEngine> simulationEngineClass = BasicEventSimulationEngine.class;
76 private Class<? extends SimulationStepper> simulationStepperClass = RK4SimulationStepper.class;
77 private Class<? extends AerodynamicCalculator> aerodynamicCalculatorClass = BarrowmanCalculator.class;
78 private Class<? extends MassCalculator> massCalculatorClass = BasicMassCalculator.class;
80 /** Listeners for this object */
81 private List<EventListener> listeners = new ArrayList<EventListener>();
84 /** The conditions actually used in the previous simulation, or null */
85 private SimulationOptions simulatedConditions = null;
86 private String simulatedMotors = null;
87 private FlightData simulatedData = null;
88 private int simulatedRocketID = -1;
92 * Create a new simulation for the rocket. Parent document should also be provided.
93 * The initial motor configuration is taken from the default rocket configuration.
95 * @param rocket the rocket associated with the simulation.
97 public Simulation(OpenRocketDocument doc, Rocket rocket) {
98 // It may seem silly to pass in the document and rocket, since usually when called we
99 // use doc.getRocket, but I guess there is some reason; when cloning a simulation + rocket we don't need
100 // to make a duplicate of the undo data etc stored in the document. --Richard
102 this.rocket = rocket;
103 this.status = Status.NOT_SIMULATED;
105 options = new SimulationOptions(rocket);
106 options.setMotorConfigurationID(
107 rocket.getDefaultConfiguration().getMotorConfigurationID());
108 options.addChangeListener(new ConditionListener());
112 public Simulation(OpenRocketDocument doc, Rocket rocket, Status status, String name, SimulationOptions options,
113 List<String> listeners, FlightData data) {
116 throw new IllegalArgumentException("rocket cannot be null");
118 throw new IllegalArgumentException("status cannot be null");
120 throw new IllegalArgumentException("name cannot be null");
122 throw new IllegalArgumentException("options cannot be null");
124 this.rocket = rocket;
127 if (status == Status.UPTODATE) {
128 this.status = Status.LOADED;
129 } else if (data == null) {
130 this.status = Status.NOT_SIMULATED;
132 this.status = status;
137 this.options = options;
138 options.addChangeListener(new ConditionListener());
140 if (listeners != null) {
141 this.simulationListeners.addAll(listeners);
145 if (data != null && this.status != Status.NOT_SIMULATED) {
146 simulatedData = data;
147 if (this.status == Status.LOADED) {
148 simulatedConditions = options.clone();
149 simulatedRocketID = rocket.getModID();
156 * Return the parent document for this simulation
158 public OpenRocketDocument getDocument(){
163 * Return the rocket associated with this simulation.
165 * @return the rocket.
167 public Rocket getRocket() {
174 * Return a newly created Configuration for this simulation. The configuration
175 * has the motor ID set and all stages active.
177 * @return a newly created Configuration of the launch conditions.
179 public Configuration getConfiguration() {
181 Configuration c = new Configuration(rocket);
182 c.setMotorConfigurationID(options.getMotorConfigurationID());
188 * Returns the simulation options attached to this simulation. The options
189 * may be modified freely, and the status of the simulation will change to reflect
192 * @return the simulation conditions.
194 public SimulationOptions getOptions() {
201 * Get the list of simulation listeners. The returned list is the one used by
202 * this object; changes to it will reflect changes in the simulation.
204 * @return the actual list of simulation listeners.
206 public List<String> getSimulationListeners() {
208 return simulationListeners;
213 * Return the user-defined name of the simulation.
215 * @return the name for the simulation.
217 public String getName() {
223 * Set the user-defined name of the simulation. Setting the name to
224 * null yields an empty name.
226 * @param name the name of the simulation.
228 public void setName(String name) {
229 mutex.lock("setName");
231 if (this.name.equals(name))
241 mutex.unlock("setName");
247 * Returns the status of this simulation. This method examines whether the
248 * simulation has been outdated and returns {@link Status#OUTDATED} accordingly.
253 public Status getStatus() {
256 if (status == Status.UPTODATE || status == Status.LOADED) {
257 if (rocket.getFunctionalModID() != simulatedRocketID ||
258 !options.equals(simulatedConditions))
259 return Status.OUTDATED;
268 * Simulate the flight.
270 * @param additionalListeners additional simulation listeners (those defined by the simulation are used in any case)
271 * @throws SimulationException if a problem occurs during simulation
273 public void simulate(SimulationListener... additionalListeners)
274 throws SimulationException {
275 mutex.lock("simulate");
278 if (this.status == Status.EXTERNAL) {
279 throw new SimulationException("Cannot simulate imported simulation.");
282 SimulationEngine simulator;
285 simulator = simulationEngineClass.newInstance();
286 } catch (InstantiationException e) {
287 throw new IllegalStateException("Cannot instantiate simulator.", e);
288 } catch (IllegalAccessException e) {
289 throw new IllegalStateException("Cannot access simulator instance?! BUG!", e);
292 SimulationConditions simulationConditions = options.toSimulationConditions();
293 simulationConditions.setSimulation(this);
294 for (SimulationListener l : additionalListeners) {
295 simulationConditions.getSimulationListenerList().add(l);
298 for (String className : simulationListeners) {
299 SimulationListener l = null;
301 Class<?> c = Class.forName(className);
302 l = (SimulationListener) c.newInstance();
303 } catch (Exception e) {
304 throw new SimulationListenerException("Could not instantiate listener of " +
305 "class: " + className, e);
307 simulationConditions.getSimulationListenerList().add(l);
311 log.debug("Simulation: calling simulator");
312 t1 = System.currentTimeMillis();
313 simulatedData = simulator.simulate(simulationConditions);
314 t2 = System.currentTimeMillis();
315 log.debug("Simulation: returning from simulator, simulation took " + (t2 - t1) + "ms");
317 // Set simulated info after simulation, will not be set in case of exception
318 simulatedConditions = options.clone();
319 simulatedMotors = getConfiguration().getMotorConfigurationDescription();
320 simulatedRocketID = rocket.getFunctionalModID();
322 status = Status.UPTODATE;
325 mutex.unlock("simulate");
331 * Return the conditions used in the previous simulation, or <code>null</code>
332 * if this simulation has not been run.
334 * @return the conditions used in the previous simulation, or <code>null</code>.
336 public SimulationOptions getSimulatedConditions() {
338 return simulatedConditions;
342 * Return the warnings generated in the previous simulation, or
343 * <code>null</code> if this simulation has not been run. This is the same
344 * warning set as contained in the <code>FlightData</code> object.
346 * @return the warnings during the previous simulation, or <code>null</code>.
347 * @see FlightData#getWarningSet()
349 public WarningSet getSimulatedWarnings() {
351 if (simulatedData == null)
353 return simulatedData.getWarningSet();
358 * Return a string describing the motor configuration of the previous simulation,
359 * or <code>null</code> if this simulation has not been run.
361 * @return a description of the motor configuration of the previous simulation, or
363 * @see Rocket#getMotorConfigurationNameOrDescription(String)
365 public String getSimulatedMotorDescription() {
367 return simulatedMotors;
371 * Return the flight data of the previous simulation, or <code>null</code> if
372 * this simulation has not been run.
374 * @return the flight data of the previous simulation, or <code>null</code>.
376 public FlightData getSimulatedData() {
378 return simulatedData;
384 * Returns a copy of this simulation suitable for cut/copy/paste operations.
385 * The rocket refers to the same instance as the original simulation.
386 * This excludes any simulated data.
388 * @return a copy of this simulation and its conditions.
390 public Simulation copy() {
394 Simulation copy = (Simulation) super.clone();
396 copy.mutex = SafetyMutex.newInstance();
397 copy.status = Status.NOT_SIMULATED;
398 copy.options = this.options.clone();
399 copy.simulationListeners = this.simulationListeners.clone();
400 copy.listeners = new ArrayList<EventListener>();
401 copy.simulatedConditions = null;
402 copy.simulatedMotors = null;
403 copy.simulatedData = null;
404 copy.simulatedRocketID = -1;
408 } catch (CloneNotSupportedException e) {
409 throw new BugException("Clone not supported, BUG", e);
411 mutex.unlock("copy");
417 * Create a duplicate of this simulation with the specified rocket. The new
418 * simulation is in non-simulated state.
420 * @param newRocket the rocket for the new simulation.
421 * @return a new simulation with the same conditions and properties.
423 public Simulation duplicateSimulation(Rocket newRocket) {
424 mutex.lock("duplicateSimulation");
426 Simulation copy = new Simulation(document, newRocket);
428 copy.name = this.name;
429 copy.options.copyFrom(this.options);
430 copy.simulationListeners = this.simulationListeners.clone();
431 copy.simulationStepperClass = this.simulationStepperClass;
432 copy.aerodynamicCalculatorClass = this.aerodynamicCalculatorClass;
436 mutex.unlock("duplicateSimulation");
443 public void addChangeListener(EventListener listener) {
445 listeners.add(listener);
449 public void removeChangeListener(EventListener listener) {
451 listeners.remove(listener);
454 protected void fireChangeEvent() {
455 EventObject e = new EventObject(this);
456 // Copy the list before iterating to prevent concurrent modification exceptions.
457 EventListener[] ls = listeners.toArray(new EventListener[0]);
458 for (EventListener l : ls) {
459 if ( l instanceof StateChangeListener ) {
460 ((StateChangeListener)l).stateChanged(e);
468 private class ConditionListener implements StateChangeListener {
470 private Status oldStatus = null;
473 public void stateChanged(EventObject e) {
474 if (getStatus() != oldStatus) {
475 oldStatus = getStatus();