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.CustomExpression;
17 import net.sf.openrocket.simulation.FlightData;
18 import net.sf.openrocket.simulation.RK4SimulationStepper;
19 import net.sf.openrocket.simulation.SimulationConditions;
20 import net.sf.openrocket.simulation.SimulationEngine;
21 import net.sf.openrocket.simulation.SimulationOptions;
22 import net.sf.openrocket.simulation.SimulationStepper;
23 import net.sf.openrocket.simulation.exception.SimulationException;
24 import net.sf.openrocket.simulation.exception.SimulationListenerException;
25 import net.sf.openrocket.simulation.listeners.SimulationListener;
26 import net.sf.openrocket.startup.Application;
27 import net.sf.openrocket.util.ArrayList;
28 import net.sf.openrocket.util.BugException;
29 import net.sf.openrocket.util.ChangeSource;
30 import net.sf.openrocket.util.SafetyMutex;
31 import net.sf.openrocket.util.StateChangeListener;
34 * A class defining a simulation, its conditions and simulated data.
36 * This class is not thread-safe and enforces single-threaded access with a
39 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
41 public class Simulation implements ChangeSource, Cloneable {
42 private static final LogHelper log = Application.getLogger();
44 public static enum Status {
48 /** Loaded from file, status probably up-to-date */
54 /** Imported external data */
57 /** Not yet simulated */
61 private SafetyMutex mutex = SafetyMutex.newInstance();
63 private final Rocket rocket;
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>();
74 private ArrayList<CustomExpression> customExpressions = new ArrayList<CustomExpression>();
76 private final Class<? extends SimulationEngine> simulationEngineClass = BasicEventSimulationEngine.class;
77 private Class<? extends SimulationStepper> simulationStepperClass = RK4SimulationStepper.class;
78 private Class<? extends AerodynamicCalculator> aerodynamicCalculatorClass = BarrowmanCalculator.class;
79 private Class<? extends MassCalculator> massCalculatorClass = BasicMassCalculator.class;
81 /** Listeners for this object */
82 private List<EventListener> listeners = new ArrayList<EventListener>();
85 /** The conditions actually used in the previous simulation, or null */
86 private SimulationOptions simulatedConditions = null;
87 private String simulatedMotors = null;
88 private FlightData simulatedData = null;
89 private int simulatedRocketID = -1;
93 * Create a new simulation for the rocket. The initial motor configuration is
94 * taken from the default rocket configuration.
96 * @param rocket the rocket associated with the simulation.
98 public Simulation(Rocket rocket) {
100 this.status = Status.NOT_SIMULATED;
102 options = new SimulationOptions(rocket);
103 options.setMotorConfigurationID(
104 rocket.getDefaultConfiguration().getMotorConfigurationID());
105 options.addChangeListener(new ConditionListener());
109 public Simulation(Rocket rocket, Status status, String name, SimulationOptions options,
110 List<String> listeners, FlightData data) {
113 throw new IllegalArgumentException("rocket cannot be null");
115 throw new IllegalArgumentException("status cannot be null");
117 throw new IllegalArgumentException("name cannot be null");
119 throw new IllegalArgumentException("options cannot be null");
121 this.rocket = rocket;
123 if (status == Status.UPTODATE) {
124 this.status = Status.LOADED;
125 } else if (data == null) {
126 this.status = Status.NOT_SIMULATED;
128 this.status = status;
133 this.options = options;
134 options.addChangeListener(new ConditionListener());
136 if (listeners != null) {
137 this.simulationListeners.addAll(listeners);
141 if (data != null && this.status != Status.NOT_SIMULATED) {
142 simulatedData = data;
143 if (this.status == Status.LOADED) {
144 simulatedConditions = options.clone();
145 simulatedRocketID = rocket.getModID();
151 public void addCustomExpression(CustomExpression expression){
152 this.status = Simulation.Status.OUTDATED;
153 log.debug("Simulation must be run again to update custom expression.");
154 customExpressions.add(expression);
157 public void removeCustomExpression(CustomExpression expression){
158 customExpressions.remove(expression);
161 public ArrayList<CustomExpression> getCustomExpressions(){
162 return customExpressions;
167 * Return the rocket associated with this simulation.
169 * @return the rocket.
171 public Rocket getRocket() {
178 * Return a newly created Configuration for this simulation. The configuration
179 * has the motor ID set and all stages active.
181 * @return a newly created Configuration of the launch conditions.
183 public Configuration getConfiguration() {
185 Configuration c = new Configuration(rocket);
186 c.setMotorConfigurationID(options.getMotorConfigurationID());
192 * Returns the simulation options attached to this simulation. The options
193 * may be modified freely, and the status of the simulation will change to reflect
196 * @return the simulation conditions.
198 public SimulationOptions getOptions() {
205 * Get the list of simulation listeners. The returned list is the one used by
206 * this object; changes to it will reflect changes in the simulation.
208 * @return the actual list of simulation listeners.
210 public List<String> getSimulationListeners() {
212 return simulationListeners;
217 * Return the user-defined name of the simulation.
219 * @return the name for the simulation.
221 public String getName() {
227 * Set the user-defined name of the simulation. Setting the name to
228 * null yields an empty name.
230 * @param name the name of the simulation.
232 public void setName(String name) {
233 mutex.lock("setName");
235 if (this.name.equals(name))
245 mutex.unlock("setName");
251 * Returns the status of this simulation. This method examines whether the
252 * simulation has been outdated and returns {@link Status#OUTDATED} accordingly.
257 public Status getStatus() {
260 if (status == Status.UPTODATE || status == Status.LOADED) {
261 if (rocket.getFunctionalModID() != simulatedRocketID ||
262 !options.equals(simulatedConditions))
263 return Status.OUTDATED;
272 * Simulate the flight.
274 * @param additionalListeners additional simulation listeners (those defined by the simulation are used in any case)
275 * @throws SimulationException if a problem occurs during simulation
277 public void simulate(SimulationListener... additionalListeners)
278 throws SimulationException {
279 mutex.lock("simulate");
282 if (this.status == Status.EXTERNAL) {
283 throw new SimulationException("Cannot simulate imported simulation.");
286 SimulationEngine simulator;
289 simulator = simulationEngineClass.newInstance();
290 } catch (InstantiationException e) {
291 throw new IllegalStateException("Cannot instantiate simulator.", e);
292 } catch (IllegalAccessException e) {
293 throw new IllegalStateException("Cannot access simulator instance?! BUG!", e);
296 SimulationConditions simulationConditions = options.toSimulationConditions();
297 simulationConditions.setSimulation(this);
298 for (SimulationListener l : additionalListeners) {
299 simulationConditions.getSimulationListenerList().add(l);
302 for (String className : simulationListeners) {
303 SimulationListener l = null;
305 Class<?> c = Class.forName(className);
306 l = (SimulationListener) c.newInstance();
307 } catch (Exception e) {
308 throw new SimulationListenerException("Could not instantiate listener of " +
309 "class: " + className, e);
311 simulationConditions.getSimulationListenerList().add(l);
315 log.debug("Simulation: calling simulator");
316 t1 = System.currentTimeMillis();
317 simulatedData = simulator.simulate(simulationConditions);
318 t2 = System.currentTimeMillis();
319 log.debug("Simulation: returning from simulator, simulation took " + (t2 - t1) + "ms");
321 // Set simulated info after simulation, will not be set in case of exception
322 simulatedConditions = options.clone();
323 simulatedMotors = getConfiguration().getMotorConfigurationDescription();
324 simulatedRocketID = rocket.getFunctionalModID();
326 status = Status.UPTODATE;
329 mutex.unlock("simulate");
335 * Return the conditions used in the previous simulation, or <code>null</code>
336 * if this simulation has not been run.
338 * @return the conditions used in the previous simulation, or <code>null</code>.
340 public SimulationOptions getSimulatedConditions() {
342 return simulatedConditions;
346 * Return the warnings generated in the previous simulation, or
347 * <code>null</code> if this simulation has not been run. This is the same
348 * warning set as contained in the <code>FlightData</code> object.
350 * @return the warnings during the previous simulation, or <code>null</code>.
351 * @see FlightData#getWarningSet()
353 public WarningSet getSimulatedWarnings() {
355 if (simulatedData == null)
357 return simulatedData.getWarningSet();
362 * Return a string describing the motor configuration of the previous simulation,
363 * or <code>null</code> if this simulation has not been run.
365 * @return a description of the motor configuration of the previous simulation, or
367 * @see Rocket#getMotorConfigurationNameOrDescription(String)
369 public String getSimulatedMotorDescription() {
371 return simulatedMotors;
375 * Return the flight data of the previous simulation, or <code>null</code> if
376 * this simulation has not been run.
378 * @return the flight data of the previous simulation, or <code>null</code>.
380 public FlightData getSimulatedData() {
382 return simulatedData;
388 * Returns a copy of this simulation suitable for cut/copy/paste operations.
389 * The rocket refers to the same instance as the original simulation.
390 * This excludes any simulated data.
392 * @return a copy of this simulation and its conditions.
394 public Simulation copy() {
398 Simulation copy = (Simulation) super.clone();
400 copy.mutex = SafetyMutex.newInstance();
401 copy.status = Status.NOT_SIMULATED;
402 copy.options = this.options.clone();
403 copy.simulationListeners = this.simulationListeners.clone();
404 copy.listeners = new ArrayList<EventListener>();
405 copy.simulatedConditions = null;
406 copy.simulatedMotors = null;
407 copy.simulatedData = null;
408 copy.simulatedRocketID = -1;
412 } catch (CloneNotSupportedException e) {
413 throw new BugException("Clone not supported, BUG", e);
415 mutex.unlock("copy");
421 * Create a duplicate of this simulation with the specified rocket. The new
422 * simulation is in non-simulated state.
424 * @param newRocket the rocket for the new simulation.
425 * @return a new simulation with the same conditions and properties.
427 public Simulation duplicateSimulation(Rocket newRocket) {
428 mutex.lock("duplicateSimulation");
430 Simulation copy = new Simulation(newRocket);
432 copy.name = this.name;
433 copy.options.copyFrom(this.options);
434 copy.simulationListeners = this.simulationListeners.clone();
435 copy.simulationStepperClass = this.simulationStepperClass;
436 copy.aerodynamicCalculatorClass = this.aerodynamicCalculatorClass;
440 mutex.unlock("duplicateSimulation");
447 public void addChangeListener(EventListener listener) {
449 listeners.add(listener);
453 public void removeChangeListener(EventListener listener) {
455 listeners.remove(listener);
458 protected void fireChangeEvent() {
459 EventObject e = new EventObject(this);
460 // Copy the list before iterating to prevent concurrent modification exceptions.
461 EventListener[] ls = listeners.toArray(new EventListener[0]);
462 for (EventListener l : ls) {
463 if ( l instanceof StateChangeListener ) {
464 ((StateChangeListener)l).stateChanged(e);
472 private class ConditionListener implements StateChangeListener {
474 private Status oldStatus = null;
477 public void stateChanged(EventObject e) {
478 if (getStatus() != oldStatus) {
479 oldStatus = getStatus();