1 package net.sf.openrocket.rocketcomponent;
3 import java.util.ArrayList;
4 import java.util.Collection;
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.Iterator;
8 import java.util.LinkedList;
10 import java.util.UUID;
12 import javax.swing.event.ChangeListener;
13 import javax.swing.event.EventListenerList;
15 import net.sf.openrocket.motor.Motor;
16 import net.sf.openrocket.util.Coordinate;
17 import net.sf.openrocket.util.MathUtil;
21 * Base for all rocket components. This is the "starting point" for all rocket trees.
22 * It provides the actual implementations of several methods defined in RocketComponent
23 * (eg. the rocket listener lists) and the methods defined in RocketComponent call these.
24 * It also defines some other methods that concern the whole rocket, and helper methods
25 * that keep information about the program state.
27 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
30 public class Rocket extends RocketComponent {
31 public static final double DEFAULT_REFERENCE_LENGTH = 0.01;
33 private static final boolean DEBUG_LISTENERS = false;
37 * The next modification ID to use. This variable may only be accessed via
38 * the synchronized {@link #getNextModID()} method!
40 private static int nextModID = 1;
44 * List of component change listeners.
46 private EventListenerList listenerList = new EventListenerList();
49 * When freezeList != null, events are not dispatched but stored in the list.
50 * When the structure is thawed, a single combined event will be fired.
52 private List<ComponentChangeEvent> freezeList = null;
56 private int massModID;
57 private int aeroModID;
58 private int treeModID;
59 private int functionalModID;
62 private ReferenceType refType = ReferenceType.MAXIMUM; // Set in constructor
63 private double customReferenceLength = DEFAULT_REFERENCE_LENGTH;
66 // The default configuration used in dialogs
67 private final Configuration defaultConfiguration;
70 private String designer = "";
71 private String revision = "";
74 // Motor configuration list
75 private ArrayList<String> motorConfigurationIDs = new ArrayList<String>();
76 private HashMap<String, String> motorConfigurationNames = new HashMap<String, String>();
78 motorConfigurationIDs.add(null);
82 // Does the rocket have a perfect finish (a notable amount of laminar flow)
83 private boolean perfectFinish = false;
87 ///////////// Constructor /////////////
90 super(RocketComponent.Position.AFTER);
91 modID = getNextModID();
95 functionalModID = modID;
96 defaultConfiguration = new Configuration(this);
101 public String getDesigner() {
105 public void setDesigner(String s) {
109 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
113 public String getRevision() {
117 public void setRevision(String s) {
121 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
128 * Return the number of stages in this rocket.
130 * @return the number of stages in this rocket.
132 public int getStageCount() {
133 return this.getChildCount();
139 * Return the non-negative modification ID of this rocket. The ID is changed
140 * every time any change occurs in the rocket. This can be used to check
141 * whether it is necessary to void cached data in cases where listeners can not
142 * or should not be used.
144 * Three other modification IDs are also available, {@link #getMassModID()},
145 * {@link #getAerodynamicModID()} {@link #getTreeModID()}, which change every time
146 * a mass change, aerodynamic change, or tree change occur. Even though the values
147 * of the different modification ID's may be equal, they should be treated totally
150 * Note that undo events restore the modification IDs that were in use at the
151 * corresponding undo level. Subsequent modifications, however, produce modIDs
152 * distinct from those already used.
154 * @return a unique ID number for this modification state.
156 public int getModID() {
161 * Return the non-negative mass modification ID of this rocket. See
162 * {@link #getModID()} for details.
164 * @return a unique ID number for this mass-modification state.
166 public int getMassModID() {
171 * Return the non-negative aerodynamic modification ID of this rocket. See
172 * {@link #getModID()} for details.
174 * @return a unique ID number for this aerodynamic-modification state.
176 public int getAerodynamicModID() {
181 * Return the non-negative tree modification ID of this rocket. See
182 * {@link #getModID()} for details.
184 * @return a unique ID number for this tree-modification state.
186 public int getTreeModID() {
191 * Return the non-negative functional modificationID of this rocket.
192 * This changes every time a functional change occurs.
194 * @return a unique ID number for this functional modification state.
196 public int getFunctionalModID() {
197 return functionalModID;
203 public ReferenceType getReferenceType() {
207 public void setReferenceType(ReferenceType type) {
211 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
215 public double getCustomReferenceLength() {
216 return customReferenceLength;
219 public void setCustomReferenceLength(double length) {
220 if (MathUtil.equals(customReferenceLength, length))
223 this.customReferenceLength = Math.max(length,0.001);
225 if (refType == ReferenceType.CUSTOM) {
226 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
235 * Set whether the rocket has a perfect finish. This will affect whether the
236 * boundary layer is assumed to be fully turbulent or not.
238 * @param perfectFinish whether the finish is perfect.
240 public void setPerfectFinish(boolean perfectFinish) {
241 if (this.perfectFinish == perfectFinish)
243 this.perfectFinish = perfectFinish;
244 fireComponentChangeEvent(ComponentChangeEvent.AERODYNAMIC_CHANGE);
250 * Get whether the rocket has a perfect finish.
252 * @return the perfectFinish
254 public boolean isPerfectFinish() {
255 return perfectFinish;
261 * Return a new unique modification ID. This method is thread-safe.
263 * @return a new modification ID unique to this session.
265 private synchronized int getNextModID() {
274 * Make a deep copy of the Rocket structure. This is a helper method which simply
275 * casts the result of the superclass method to a Rocket.
277 @SuppressWarnings("unchecked")
279 public Rocket copy() {
280 Rocket copy = (Rocket)super.copy();
281 copy.motorConfigurationIDs = (ArrayList<String>) this.motorConfigurationIDs.clone();
282 copy.motorConfigurationNames =
283 (HashMap<String, String>) this.motorConfigurationNames.clone();
284 copy.resetListeners();
290 * Load the rocket structure from the source. The method loads the fields of this
291 * Rocket object and copies the references to siblings from the <code>source</code>.
292 * The object <code>source</code> should not be used after this call, as it is in
295 * This method is meant to be used in conjunction with undo/redo functionality,
296 * and therefore fires an UNDO_EVENT, masked with all applicable mass/aerodynamic/tree
299 @SuppressWarnings("unchecked")
300 public void loadFrom(Rocket r) {
303 int type = ComponentChangeEvent.UNDO_CHANGE | ComponentChangeEvent.NONFUNCTIONAL_CHANGE;
304 if (this.massModID != r.massModID)
305 type |= ComponentChangeEvent.MASS_CHANGE;
306 if (this.aeroModID != r.aeroModID)
307 type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
308 if (this.treeModID != r.treeModID)
309 type |= ComponentChangeEvent.TREE_CHANGE;
311 this.modID = r.modID;
312 this.massModID = r.massModID;
313 this.aeroModID = r.aeroModID;
314 this.treeModID = r.treeModID;
315 this.functionalModID = r.functionalModID;
316 this.refType = r.refType;
317 this.customReferenceLength = r.customReferenceLength;
319 this.motorConfigurationIDs = (ArrayList<String>) r.motorConfigurationIDs.clone();
320 this.motorConfigurationNames =
321 (HashMap<String, String>) r.motorConfigurationNames.clone();
322 this.perfectFinish = r.perfectFinish;
324 String id = defaultConfiguration.getMotorConfigurationID();
325 if (!this.motorConfigurationIDs.contains(id))
326 defaultConfiguration.setMotorConfigurationID(null);
328 fireComponentChangeEvent(type);
334 /////// Implement the ComponentChangeListener lists
337 * Creates a new EventListenerList for this component. This is necessary when cloning
340 public void resetListeners() {
341 // System.out.println("RESETTING LISTENER LIST of Rocket "+this);
342 listenerList = new EventListenerList();
346 public void printListeners() {
347 System.out.println(""+this+" has "+listenerList.getListenerCount()+" listeners:");
348 Object[] list = listenerList.getListenerList();
349 for (int i=1; i<list.length; i+=2)
350 System.out.println(" "+((i+1)/2)+": "+list[i]);
354 public void addComponentChangeListener(ComponentChangeListener l) {
355 listenerList.add(ComponentChangeListener.class,l);
357 System.out.println(this+": Added listner (now "+listenerList.getListenerCount()+
361 public void removeComponentChangeListener(ComponentChangeListener l) {
362 listenerList.remove(ComponentChangeListener.class, l);
364 System.out.println(this+": Removed listner (now "+listenerList.getListenerCount()+
370 public void addChangeListener(ChangeListener l) {
371 listenerList.add(ChangeListener.class,l);
373 System.out.println(this+": Added listner (now "+listenerList.getListenerCount()+
377 public void removeChangeListener(ChangeListener l) {
378 listenerList.remove(ChangeListener.class, l);
380 System.out.println(this+": Removed listner (now "+listenerList.getListenerCount()+
386 protected void fireComponentChangeEvent(ComponentChangeEvent e) {
388 // Update modification ID's only for normal (not undo/redo) events
389 if (!e.isUndoChange()) {
390 modID = getNextModID();
391 if (e.isMassChange())
393 if (e.isAerodynamicChange())
395 if (e.isTreeChange())
397 if (e.getType() != ComponentChangeEvent.NONFUNCTIONAL_CHANGE)
398 functionalModID = modID;
402 System.out.println("FIRING "+e);
404 // Check whether frozen
405 if (freezeList != null) {
410 // Notify all components first
411 Iterator<RocketComponent> iterator = this.deepIterator(true);
412 while (iterator.hasNext()) {
413 iterator.next().componentChanged(e);
416 // Notify all listeners
417 Object[] listeners = listenerList.getListenerList();
418 for (int i = listeners.length-2; i>=0; i-=2) {
419 if (listeners[i] == ComponentChangeListener.class) {
420 ((ComponentChangeListener) listeners[i+1]).componentChanged(e);
421 } else if (listeners[i] == ChangeListener.class) {
422 ((ChangeListener) listeners[i+1]).stateChanged(e);
429 * Freezes the rocket structure from firing any events. This may be performed to
430 * combine several actions on the structure into a single large action.
431 * <code>thaw()</code> must always be called afterwards.
433 * NOTE: Always use a try/finally to ensure <code>thaw()</code> is called:
435 * Rocket r = c.getRocket();
446 public void freeze() {
447 if (freezeList == null)
448 freezeList = new LinkedList<ComponentChangeEvent>();
452 * Thaws a frozen rocket structure and fires a combination of the events fired during
453 * the freeze. The event type is a combination of those fired and the source is the
454 * last component to have been an event source.
459 if (freezeList == null)
461 if (freezeList.size()==0) {
468 for (ComponentChangeEvent e: freezeList) {
469 type = type | e.getType();
474 fireComponentChangeEvent(new ComponentChangeEvent((RocketComponent)c,type));
480 //////// Motor configurations ////////
484 * Return the default configuration. This should be used in the user interface
485 * to ensure a consistent rocket configuration between dialogs. It should NOT
486 * be used in simulations not relating to the UI.
488 * @return the default {@link Configuration}.
490 public Configuration getDefaultConfiguration() {
491 return defaultConfiguration;
496 * Return an array of the motor configuration IDs. This array is guaranteed
497 * to contain the <code>null</code> ID as the first element.
499 * @return an array of the motor configuration IDs.
501 public String[] getMotorConfigurationIDs() {
502 return motorConfigurationIDs.toArray(new String[0]);
506 * Add a new motor configuration ID to the motor configurations. The new ID
509 * @return the new motor configuration ID.
511 public String newMotorConfigurationID() {
512 String id = UUID.randomUUID().toString();
513 motorConfigurationIDs.add(id);
514 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
519 * Add a specified motor configuration ID to the motor configurations.
521 * @param id the motor configuration ID.
522 * @return true if successful, false if the ID was already used.
524 public boolean addMotorConfigurationID(String id) {
525 if (id == null || motorConfigurationIDs.contains(id))
527 motorConfigurationIDs.add(id);
528 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
533 * Remove a motor configuration ID from the configuration IDs. The <code>null</code>
534 * ID cannot be removed, and an attempt to remove it will be silently ignored.
536 * @param id the motor configuration ID to remove
538 public void removeMotorConfigurationID(String id) {
541 motorConfigurationIDs.remove(id);
542 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
547 * Check whether <code>id</code> is a valid motor configuration ID.
549 * @param id the configuration ID.
550 * @return whether a motor configuration with that ID exists.
552 public boolean isMotorConfigurationID(String id) {
553 return motorConfigurationIDs.contains(id);
559 * Check whether the given motor configuration ID has motors defined for it.
561 * @param id the motor configuration ID (may be invalid).
562 * @return whether any motors are defined for it.
564 public boolean hasMotors(String id) {
565 Iterator<RocketComponent> iterator = this.deepIterator();
566 while (iterator.hasNext()) {
567 RocketComponent c = iterator.next();
569 if (c instanceof MotorMount) {
570 MotorMount mount = (MotorMount) c;
571 if (!mount.isMotorMount())
573 if (mount.getMotor(id) != null) {
583 * Return the user-set name of the motor configuration. If no name has been set,
584 * returns an empty string (not null).
586 * @param id the motor configuration id
587 * @return the configuration name
589 public String getMotorConfigurationName(String id) {
590 String s = motorConfigurationNames.get(id);
598 * Set the name of the motor configuration. A name can be unset by passing
599 * <code>null</code> or an empty string.
601 * @param id the motor configuration id
602 * @param name the name for the motor configuration
604 public void setMotorConfigurationName(String id, String name) {
605 motorConfigurationNames.put(id,name);
606 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
611 * Return either the motor configuration name (if set) or its description.
613 * @param id the motor configuration ID.
614 * @return a textual representation of the configuration
616 public String getMotorConfigurationNameOrDescription(String id) {
619 name = motorConfigurationNames.get(id);
620 if (name != null && !name.equals(""))
623 return getMotorConfigurationDescription(id);
627 * Return a description for the motor configuration, generated from the motor
628 * designations of the components.
630 * @param id the motor configuration ID.
631 * @return a textual representation of the configuration
633 @SuppressWarnings("null")
634 public String getMotorConfigurationDescription(String id) {
638 if (!motorConfigurationIDs.contains(id)) {
639 throw new IllegalArgumentException("Motor configuration ID does not exist: "+id);
642 // Generate the description
644 // First iterate over each stage and store the designations of each motor
645 List<List<String>> list = new ArrayList<List<String>>();
646 List<String> currentList = null;
648 Iterator<RocketComponent> iterator = this.deepIterator();
649 while (iterator.hasNext()) {
650 RocketComponent c = iterator.next();
652 if (c instanceof Stage) {
654 currentList = new ArrayList<String>();
655 list.add(currentList);
657 } else if (c instanceof MotorMount) {
659 MotorMount mount = (MotorMount) c;
660 Motor motor = mount.getMotor(id);
662 if (mount.isMotorMount() && motor != null) {
663 String designation = motor.getDesignation(mount.getMotorDelay(id));
665 for (int i=0; i < mount.getMotorCount(); i++) {
666 currentList.add(designation);
674 if (motorCount == 0) {
675 return "[No motors]";
678 // Change multiple occurrences of a motor to n x motor
679 List<String> stages = new ArrayList<String>();
681 for (List<String> stage: list) {
682 String stageName = "";
683 String previous = null;
686 Collections.sort(stage);
687 for (String current: stage) {
688 if (current.equals(previous)) {
694 if (previous != null) {
697 s = "" + count + "\u00d7" + previous;
702 if (stageName.equals(""))
705 stageName = stageName + "," + s;
713 if (previous != null) {
716 s = "" + count + "\u00d7" + previous;
721 if (stageName.equals(""))
724 stageName = stageName + "," + s;
727 stages.add(stageName);
731 for (int i=0; i < stages.size(); i++) {
732 String s = stages.get(i);
738 name = name + "; " + s;
746 //////// Obligatory component information
750 public String getComponentName() {
755 public Coordinate getComponentCG() {
756 return new Coordinate(0,0,0,0);
760 public double getComponentMass() {
765 public double getLongitudalUnitInertia() {
770 public double getRotationalUnitInertia() {
775 public Collection<Coordinate> getComponentBounds() {
776 return Collections.emptyList();
780 public boolean isAerodynamic() {
785 public boolean isMassive() {
790 * Allows only <code>Stage</code> components to be added to the type Rocket.
793 public boolean isCompatible(Class<? extends RocketComponent> type) {
794 return (Stage.class.isAssignableFrom(type));