709ce4640f9df16e835e1dd9e45c3c0804f4b09d
[debian/openrocket] / src / net / sf / openrocket / document / Simulation.java
1 package net.sf.openrocket.document;
2
3 import java.util.List;
4
5 import javax.swing.event.ChangeEvent;
6 import javax.swing.event.ChangeListener;
7
8 import net.sf.openrocket.aerodynamics.AerodynamicCalculator;
9 import net.sf.openrocket.aerodynamics.BarrowmanCalculator;
10 import net.sf.openrocket.aerodynamics.WarningSet;
11 import net.sf.openrocket.logging.LogHelper;
12 import net.sf.openrocket.masscalc.BasicMassCalculator;
13 import net.sf.openrocket.masscalc.MassCalculator;
14 import net.sf.openrocket.rocketcomponent.Configuration;
15 import net.sf.openrocket.rocketcomponent.Rocket;
16 import net.sf.openrocket.simulation.BasicEventSimulationEngine;
17 import net.sf.openrocket.simulation.FlightData;
18 import net.sf.openrocket.simulation.GUISimulationConditions;
19 import net.sf.openrocket.simulation.RK4SimulationStepper;
20 import net.sf.openrocket.simulation.SimulationConditions;
21 import net.sf.openrocket.simulation.SimulationEngine;
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
32 /**
33  * A class defining a simulation, its conditions and simulated data.
34  * <p>
35  * This class is not thread-safe and enforces single-threaded access with a
36  * SafetyMutex.
37  * 
38  * @author Sampo Niskanen <sampo.niskanen@iki.fi>
39  */
40 public class Simulation implements ChangeSource, Cloneable {
41         private static final LogHelper log = Application.getLogger();
42         
43         public static enum Status {
44                 /** Up-to-date */
45                 UPTODATE,
46
47                 /** Loaded from file, status probably up-to-date */
48                 LOADED,
49
50                 /** Data outdated */
51                 OUTDATED,
52
53                 /** Imported external data */
54                 EXTERNAL,
55
56                 /** Not yet simulated */
57                 NOT_SIMULATED
58         }
59         
60         private SafetyMutex mutex = SafetyMutex.newInstance();
61         
62         private final Rocket rocket;
63         
64         private String name = "";
65         
66         private Status status = Status.NOT_SIMULATED;
67         
68         /** The conditions to use */
69         // TODO: HIGH: Change to use actual conditions class??
70         private GUISimulationConditions conditions;
71         
72         private ArrayList<String> simulationListeners = new ArrayList<String>();
73         
74         private final Class<? extends SimulationEngine> simulationEngineClass = BasicEventSimulationEngine.class;
75         private Class<? extends SimulationStepper> simulationStepperClass = RK4SimulationStepper.class;
76         private Class<? extends AerodynamicCalculator> aerodynamicCalculatorClass = BarrowmanCalculator.class;
77         private Class<? extends MassCalculator> massCalculatorClass = BasicMassCalculator.class;
78         
79
80
81         /** Listeners for this object */
82         private List<ChangeListener> listeners = new ArrayList<ChangeListener>();
83         
84
85         /** The conditions actually used in the previous simulation, or null */
86         private GUISimulationConditions simulatedConditions = null;
87         private String simulatedMotors = null;
88         private FlightData simulatedData = null;
89         private int simulatedRocketID = -1;
90         
91         
92         /**
93          * Create a new simulation for the rocket.  The initial motor configuration is
94          * taken from the default rocket configuration.
95          * 
96          * @param rocket        the rocket associated with the simulation.
97          */
98         public Simulation(Rocket rocket) {
99                 this.rocket = rocket;
100                 this.status = Status.NOT_SIMULATED;
101                 
102                 conditions = new GUISimulationConditions(rocket);
103                 conditions.setMotorConfigurationID(
104                                 rocket.getDefaultConfiguration().getMotorConfigurationID());
105                 conditions.addChangeListener(new ConditionListener());
106         }
107         
108         
109         public Simulation(Rocket rocket, Status status, String name, GUISimulationConditions conditions,
110                         List<String> listeners, FlightData data) {
111                 
112                 if (rocket == null)
113                         throw new IllegalArgumentException("rocket cannot be null");
114                 if (status == null)
115                         throw new IllegalArgumentException("status cannot be null");
116                 if (name == null)
117                         throw new IllegalArgumentException("name cannot be null");
118                 if (conditions == null)
119                         throw new IllegalArgumentException("conditions cannot be null");
120                 
121                 this.rocket = rocket;
122                 
123                 if (status == Status.UPTODATE) {
124                         this.status = Status.LOADED;
125                 } else if (data == null) {
126                         this.status = Status.NOT_SIMULATED;
127                 } else {
128                         this.status = status;
129                 }
130                 
131                 this.name = name;
132                 
133                 this.conditions = conditions;
134                 conditions.addChangeListener(new ConditionListener());
135                 
136                 if (listeners != null) {
137                         this.simulationListeners.addAll(listeners);
138                 }
139                 
140
141                 if (data != null && this.status != Status.NOT_SIMULATED) {
142                         simulatedData = data;
143                         if (this.status == Status.LOADED) {
144                                 simulatedConditions = conditions.clone();
145                                 simulatedRocketID = rocket.getModID();
146                         }
147                 }
148                 
149         }
150         
151         
152         /**
153          * Return the rocket associated with this simulation.
154          * 
155          * @return      the rocket.
156          */
157         public Rocket getRocket() {
158                 mutex.verify();
159                 return rocket;
160         }
161         
162         
163         /**
164          * Return a newly created Configuration for this simulation.  The configuration
165          * has the motor ID set and all stages active.
166          * 
167          * @return      a newly created Configuration of the launch conditions.
168          */
169         public Configuration getConfiguration() {
170                 mutex.verify();
171                 Configuration c = new Configuration(rocket);
172                 c.setMotorConfigurationID(conditions.getMotorConfigurationID());
173                 c.setAllStages();
174                 return c;
175         }
176         
177         /**
178          * Returns the simulation conditions attached to this simulation.  The conditions
179          * may be modified freely, and the status of the simulation will change to reflect
180          * the changes.
181          * 
182          * @return the simulation conditions.
183          */
184         public GUISimulationConditions getConditions() {
185                 mutex.verify();
186                 return conditions;
187         }
188         
189         
190         /**
191          * Get the list of simulation listeners.  The returned list is the one used by
192          * this object; changes to it will reflect changes in the simulation.
193          * 
194          * @return      the actual list of simulation listeners.
195          */
196         public List<String> getSimulationListeners() {
197                 mutex.verify();
198                 return simulationListeners;
199         }
200         
201         
202         /**
203          * Return the user-defined name of the simulation.
204          * 
205          * @return      the name for the simulation.
206          */
207         public String getName() {
208                 mutex.verify();
209                 return name;
210         }
211         
212         /**
213          * Set the user-defined name of the simulation.  Setting the name to
214          * null yields an empty name.
215          * 
216          * @param name  the name of the simulation.
217          */
218         public void setName(String name) {
219                 mutex.lock("setName");
220                 try {
221                         if (this.name.equals(name))
222                                 return;
223                         
224                         if (name == null)
225                                 this.name = "";
226                         else
227                                 this.name = name;
228                         
229                         fireChangeEvent();
230                 } finally {
231                         mutex.unlock("setName");
232                 }
233         }
234         
235         
236         /**
237          * Returns the status of this simulation.  This method examines whether the
238          * simulation has been outdated and returns {@link Status#OUTDATED} accordingly.
239          * 
240          * @return the status
241          * @see Status
242          */
243         public Status getStatus() {
244                 mutex.verify();
245                 
246                 if (status == Status.UPTODATE || status == Status.LOADED) {
247                         if (rocket.getFunctionalModID() != simulatedRocketID ||
248                                         !conditions.equals(simulatedConditions))
249                                 return Status.OUTDATED;
250                 }
251                 
252                 return status;
253         }
254         
255         
256
257         /**
258          * Simulate the flight.
259          * 
260          * @param additionalListeners   additional simulation listeners (those defined by the simulation are used in any case)
261          * @throws SimulationException  if a problem occurs during simulation
262          */
263         public void simulate(SimulationListener... additionalListeners)
264                                                 throws SimulationException {
265                 mutex.lock("simulate");
266                 try {
267                         
268                         if (this.status == Status.EXTERNAL) {
269                                 throw new SimulationException("Cannot simulate imported simulation.");
270                         }
271                         
272                         SimulationEngine simulator;
273                         
274                         try {
275                                 simulator = simulationEngineClass.newInstance();
276                         } catch (InstantiationException e) {
277                                 throw new IllegalStateException("Cannot instantiate simulator.", e);
278                         } catch (IllegalAccessException e) {
279                                 throw new IllegalStateException("Cannot access simulator instance?! BUG!", e);
280                         } catch (NullPointerException e) {
281                                 throw new IllegalStateException("Simulator null", e);
282                         }
283                         
284                         SimulationConditions simulationConditions = conditions.toSimulationConditions();
285                         for (SimulationListener l : additionalListeners) {
286                                 simulationConditions.getSimulationListenerList().add(l);
287                         }
288                         
289                         for (String className : simulationListeners) {
290                                 SimulationListener l = null;
291                                 try {
292                                         Class<?> c = Class.forName(className);
293                                         l = (SimulationListener) c.newInstance();
294                                 } catch (Exception e) {
295                                         throw new SimulationListenerException("Could not instantiate listener of " +
296                                                         "class: " + className, e);
297                                 }
298                                 simulationConditions.getSimulationListenerList().add(l);
299                         }
300                         
301                         long t1, t2;
302                         log.debug("Simulation: calling simulator");
303                         t1 = System.currentTimeMillis();
304                         simulatedData = simulator.simulate(simulationConditions);
305                         t2 = System.currentTimeMillis();
306                         log.debug("Simulation: returning from simulator, simulation took " + (t2 - t1) + "ms");
307                         
308                         // Set simulated info after simulation, will not be set in case of exception
309                         simulatedConditions = conditions.clone();
310                         simulatedMotors = getConfiguration().getMotorConfigurationDescription();
311                         simulatedRocketID = rocket.getFunctionalModID();
312                         
313                         status = Status.UPTODATE;
314                         fireChangeEvent();
315                 } finally {
316                         mutex.unlock("simulate");
317                 }
318         }
319         
320         
321         /**
322          * Return the conditions used in the previous simulation, or <code>null</code>
323          * if this simulation has not been run.
324          * 
325          * @return      the conditions used in the previous simulation, or <code>null</code>.
326          */
327         public GUISimulationConditions getSimulatedConditions() {
328                 mutex.verify();
329                 return simulatedConditions;
330         }
331         
332         /**
333          * Return the warnings generated in the previous simulation, or
334          * <code>null</code> if this simulation has not been run.  This is the same
335          * warning set as contained in the <code>FlightData</code> object.
336          * 
337          * @return      the warnings during the previous simulation, or <code>null</code>.
338          * @see         FlightData#getWarningSet()
339          */
340         public WarningSet getSimulatedWarnings() {
341                 mutex.verify();
342                 if (simulatedData == null)
343                         return null;
344                 return simulatedData.getWarningSet();
345         }
346         
347         
348         /**
349          * Return a string describing the motor configuration of the previous simulation,
350          * or <code>null</code> if this simulation has not been run.
351          * 
352          * @return      a description of the motor configuration of the previous simulation, or
353          *                      <code>null</code>.
354          * @see         Rocket#getMotorConfigurationNameOrDescription(String)
355          */
356         public String getSimulatedMotorDescription() {
357                 mutex.verify();
358                 return simulatedMotors;
359         }
360         
361         /**
362          * Return the flight data of the previous simulation, or <code>null</code> if
363          * this simulation has not been run.
364          * 
365          * @return      the flight data of the previous simulation, or <code>null</code>.
366          */
367         public FlightData getSimulatedData() {
368                 mutex.verify();
369                 return simulatedData;
370         }
371         
372         
373
374         /**
375          * Returns a copy of this simulation suitable for cut/copy/paste operations.  
376          * This excludes any simulated data.
377          *  
378          * @return      a copy of this simulation and its conditions.
379          */
380         public Simulation copy() {
381                 mutex.lock("copy");
382                 try {
383                         
384                         Simulation copy = (Simulation) super.clone();
385                         
386                         copy.mutex = SafetyMutex.newInstance();
387                         copy.status = Status.NOT_SIMULATED;
388                         copy.conditions = this.conditions.clone();
389                         copy.simulationListeners = this.simulationListeners.clone();
390                         copy.listeners = new ArrayList<ChangeListener>();
391                         copy.simulatedConditions = null;
392                         copy.simulatedMotors = null;
393                         copy.simulatedData = null;
394                         copy.simulatedRocketID = -1;
395                         
396                         return copy;
397                         
398                 } catch (CloneNotSupportedException e) {
399                         throw new BugException("Clone not supported, BUG", e);
400                 } finally {
401                         mutex.unlock("copy");
402                 }
403         }
404         
405         
406         /**
407          * Create a duplicate of this simulation with the specified rocket.  The new
408          * simulation is in non-simulated state.
409          * 
410          * @param newRocket             the rocket for the new simulation.
411          * @return                              a new simulation with the same conditions and properties.
412          */
413         public Simulation duplicateSimulation(Rocket newRocket) {
414                 mutex.lock("duplicateSimulation");
415                 try {
416                         Simulation copy = new Simulation(newRocket);
417                         
418                         copy.name = this.name;
419                         copy.conditions.copyFrom(this.conditions);
420                         copy.simulationListeners = this.simulationListeners.clone();
421                         copy.simulationStepperClass = this.simulationStepperClass;
422                         copy.aerodynamicCalculatorClass = this.aerodynamicCalculatorClass;
423                         
424                         return copy;
425                 } finally {
426                         mutex.unlock("duplicateSimulation");
427                 }
428         }
429         
430         
431
432         @Override
433         public void addChangeListener(ChangeListener listener) {
434                 mutex.verify();
435                 listeners.add(listener);
436         }
437         
438         @Override
439         public void removeChangeListener(ChangeListener listener) {
440                 mutex.verify();
441                 listeners.remove(listener);
442         }
443         
444         protected void fireChangeEvent() {
445                 ChangeListener[] ls = listeners.toArray(new ChangeListener[0]);
446                 ChangeEvent e = new ChangeEvent(this);
447                 for (ChangeListener l : ls) {
448                         l.stateChanged(e);
449                 }
450         }
451         
452         
453
454
455         private class ConditionListener implements ChangeListener {
456                 
457                 private Status oldStatus = null;
458                 
459                 @Override
460                 public void stateChanged(ChangeEvent e) {
461                         if (getStatus() != oldStatus) {
462                                 oldStatus = getStatus();
463                                 fireChangeEvent();
464                         }
465                 }
466         }
467 }