1 package net.sf.openrocket.rocketcomponent;
3 import java.util.Collection;
4 import java.util.Collections;
5 import java.util.EventListener;
6 import java.util.HashMap;
7 import java.util.Iterator;
8 import java.util.LinkedList;
10 import java.util.UUID;
12 import net.sf.openrocket.l10n.Translator;
13 import net.sf.openrocket.logging.LogHelper;
14 import net.sf.openrocket.motor.Motor;
15 import net.sf.openrocket.startup.Application;
16 import net.sf.openrocket.util.ArrayList;
17 import net.sf.openrocket.util.Chars;
18 import net.sf.openrocket.util.Coordinate;
19 import net.sf.openrocket.util.MathUtil;
20 import net.sf.openrocket.util.StateChangeListener;
21 import net.sf.openrocket.util.UniqueID;
25 * Base for all rocket components. This is the "starting point" for all rocket trees.
26 * It provides the actual implementations of several methods defined in RocketComponent
27 * (eg. the rocket listener lists) and the methods defined in RocketComponent call these.
28 * It also defines some other methods that concern the whole rocket, and helper methods
29 * that keep information about the program state.
31 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
34 public class Rocket extends RocketComponent {
35 private static final LogHelper log = Application.getLogger();
36 private static final Translator trans = Application.getTranslator();
38 public static final double DEFAULT_REFERENCE_LENGTH = 0.01;
42 * List of component change listeners.
44 private List<EventListener> listenerList = new ArrayList<EventListener>();
47 * When freezeList != null, events are not dispatched but stored in the list.
48 * When the structure is thawed, a single combined event will be fired.
50 private List<ComponentChangeEvent> freezeList = null;
54 private int massModID;
55 private int aeroModID;
56 private int treeModID;
57 private int functionalModID;
60 private ReferenceType refType = ReferenceType.MAXIMUM; // Set in constructor
61 private double customReferenceLength = DEFAULT_REFERENCE_LENGTH;
64 // The default configuration used in dialogs
65 private final Configuration defaultConfiguration;
68 private String designer = "";
69 private String revision = "";
72 // Motor configuration list
73 private ArrayList<String> motorConfigurationIDs = new ArrayList<String>();
74 private HashMap<String, String> motorConfigurationNames = new HashMap<String, String>();
76 motorConfigurationIDs.add(null);
80 // Does the rocket have a perfect finish (a notable amount of laminar flow)
81 private boolean perfectFinish = false;
85 ///////////// Constructor /////////////
88 super(RocketComponent.Position.AFTER);
89 modID = UniqueID.next();
93 functionalModID = modID;
94 defaultConfiguration = new Configuration(this);
99 public String getDesigner() {
104 public void setDesigner(String s) {
108 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
112 public String getRevision() {
117 public void setRevision(String s) {
121 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
125 * Return the number of stages in this rocket.
127 * @return the number of stages in this rocket.
129 public int getStageCount() {
131 return this.getChildCount();
136 * Return the non-negative modification ID of this rocket. The ID is changed
137 * every time any change occurs in the rocket. This can be used to check
138 * whether it is necessary to void cached data in cases where listeners can not
139 * or should not be used.
141 * Three other modification IDs are also available, {@link #getMassModID()},
142 * {@link #getAerodynamicModID()} {@link #getTreeModID()}, which change every time
143 * a mass change, aerodynamic change, or tree change occur. Even though the values
144 * of the different modification ID's may be equal, they should be treated totally
147 * Note that undo events restore the modification IDs that were in use at the
148 * corresponding undo level. Subsequent modifications, however, produce modIDs
149 * distinct from those already used.
151 * @return a unique ID number for this modification state.
153 public int getModID() {
158 * Return the non-negative mass modification ID of this rocket. See
159 * {@link #getModID()} for details.
161 * @return a unique ID number for this mass-modification state.
163 public int getMassModID() {
168 * Return the non-negative aerodynamic modification ID of this rocket. See
169 * {@link #getModID()} for details.
171 * @return a unique ID number for this aerodynamic-modification state.
173 public int getAerodynamicModID() {
178 * Return the non-negative tree modification ID of this rocket. See
179 * {@link #getModID()} for details.
181 * @return a unique ID number for this tree-modification state.
183 public int getTreeModID() {
188 * Return the non-negative functional modificationID of this rocket.
189 * This changes every time a functional change occurs.
191 * @return a unique ID number for this functional modification state.
193 public int getFunctionalModID() {
194 return functionalModID;
200 public ReferenceType getReferenceType() {
205 public void setReferenceType(ReferenceType type) {
209 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
213 public double getCustomReferenceLength() {
215 return customReferenceLength;
218 public void setCustomReferenceLength(double length) {
219 if (MathUtil.equals(customReferenceLength, length))
222 this.customReferenceLength = Math.max(length, 0.001);
224 if (refType == ReferenceType.CUSTOM) {
225 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
234 * Set whether the rocket has a perfect finish. This will affect whether the
235 * boundary layer is assumed to be fully turbulent or not.
237 * @param perfectFinish whether the finish is perfect.
239 public void setPerfectFinish(boolean perfectFinish) {
240 if (this.perfectFinish == perfectFinish)
242 this.perfectFinish = perfectFinish;
243 fireComponentChangeEvent(ComponentChangeEvent.AERODYNAMIC_CHANGE);
249 * Get whether the rocket has a perfect finish.
251 * @return the perfectFinish
253 public boolean isPerfectFinish() {
254 return perfectFinish;
262 * Make a deep copy of the Rocket structure. This method is exposed as public to allow
263 * for undo/redo system functionality.
265 @SuppressWarnings("unchecked")
267 public Rocket copyWithOriginalID() {
268 Rocket copy = (Rocket) super.copyWithOriginalID();
269 copy.motorConfigurationIDs = this.motorConfigurationIDs.clone();
270 copy.motorConfigurationNames =
271 (HashMap<String, String>) this.motorConfigurationNames.clone();
272 copy.resetListeners();
278 * Load the rocket structure from the source. The method loads the fields of this
279 * Rocket object and copies the references to siblings from the <code>source</code>.
280 * The object <code>source</code> should not be used after this call, as it is in
283 * This method is meant to be used in conjunction with undo/redo functionality,
284 * and therefore fires an UNDO_EVENT, masked with all applicable mass/aerodynamic/tree
287 @SuppressWarnings("unchecked")
288 public void loadFrom(Rocket r) {
290 // Store list of components to invalidate after event has been fired
291 List<RocketComponent> toInvalidate = this.copyFrom(r);
293 int type = ComponentChangeEvent.UNDO_CHANGE | ComponentChangeEvent.NONFUNCTIONAL_CHANGE;
294 if (this.massModID != r.massModID)
295 type |= ComponentChangeEvent.MASS_CHANGE;
296 if (this.aeroModID != r.aeroModID)
297 type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
298 // Loading a rocket is always a tree change since the component objects change
299 type |= ComponentChangeEvent.TREE_CHANGE;
301 this.modID = r.modID;
302 this.massModID = r.massModID;
303 this.aeroModID = r.aeroModID;
304 this.treeModID = r.treeModID;
305 this.functionalModID = r.functionalModID;
306 this.refType = r.refType;
307 this.customReferenceLength = r.customReferenceLength;
309 this.motorConfigurationIDs = r.motorConfigurationIDs.clone();
310 this.motorConfigurationNames =
311 (HashMap<String, String>) r.motorConfigurationNames.clone();
312 this.perfectFinish = r.perfectFinish;
314 String id = defaultConfiguration.getMotorConfigurationID();
315 if (!this.motorConfigurationIDs.contains(id))
316 defaultConfiguration.setMotorConfigurationID(null);
318 this.checkComponentStructure();
320 fireComponentChangeEvent(type);
322 // Invalidate obsolete components after event
323 for (RocketComponent c : toInvalidate) {
331 /////// Implement the ComponentChangeListener lists
334 * Creates a new EventListenerList for this component. This is necessary when cloning
337 public void resetListeners() {
338 // System.out.println("RESETTING LISTENER LIST of Rocket "+this);
339 listenerList = new ArrayList<EventListener>();
343 public void printListeners() {
344 System.out.println("" + this + " has " + listenerList.size() + " listeners:");
346 for( EventListener l : listenerList ) {
347 System.out.println(" " + (i) + ": " + l);
353 public void addComponentChangeListener(ComponentChangeListener l) {
356 log.verbose("Added ComponentChangeListener " + l + ", current number of listeners is " +
357 listenerList.size());
361 public void removeComponentChangeListener(ComponentChangeListener l) {
362 listenerList.remove(l);
363 log.verbose("Removed ComponentChangeListener " + l + ", current number of listeners is " +
364 listenerList.size());
369 public void addChangeListener(EventListener l) {
372 log.verbose("Added ChangeListener " + l + ", current number of listeners is " +
373 listenerList.size());
377 public void removeChangeListener(EventListener l) {
378 listenerList.remove(l);
379 log.verbose("Removed ChangeListener " + l + ", current number of listeners is " +
380 listenerList.size());
385 protected void fireComponentChangeEvent(ComponentChangeEvent e) {
386 mutex.lock("fireComponentChangeEvent");
390 // Update modification ID's only for normal (not undo/redo) events
391 if (!e.isUndoChange()) {
392 modID = UniqueID.next();
393 if (e.isMassChange())
395 if (e.isAerodynamicChange())
397 if (e.isTreeChange())
399 if (e.getType() != ComponentChangeEvent.NONFUNCTIONAL_CHANGE)
400 functionalModID = modID;
403 // Check whether frozen
404 if (freezeList != null) {
405 log.debug("Rocket is in frozen state, adding event " + e + " info freeze list");
410 log.debug("Firing rocket change event " + e);
412 // Notify all components first
413 Iterator<RocketComponent> iterator = this.iterator(true);
414 while (iterator.hasNext()) {
415 iterator.next().componentChanged(e);
418 // Notify all listeners
419 // Copy the list before iterating to prevent concurrent modification exceptions.
420 EventListener[] list = listenerList.toArray( new EventListener[0] );
421 for ( EventListener l : list ) {
422 if ( l instanceof ComponentChangeListener ) {
423 ((ComponentChangeListener) l ).componentChanged(e);
424 } else if ( l instanceof StateChangeListener ) {
425 ((StateChangeListener) l ).stateChanged(e);
429 mutex.unlock("fireComponentChangeEvent");
435 * Freezes the rocket structure from firing any events. This may be performed to
436 * combine several actions on the structure into a single large action.
437 * <code>thaw()</code> must always be called afterwards.
439 * NOTE: Always use a try/finally to ensure <code>thaw()</code> is called:
441 * Rocket r = c.getRocket();
452 public void freeze() {
454 if (freezeList == null) {
455 freezeList = new LinkedList<ComponentChangeEvent>();
456 log.debug("Freezing Rocket");
458 Application.getExceptionHandler().handleErrorCondition("Attempting to freeze Rocket when it is already frozen, " +
459 "freezeList=" + freezeList);
464 * Thaws a frozen rocket structure and fires a combination of the events fired during
465 * the freeze. The event type is a combination of those fired and the source is the
466 * last component to have been an event source.
472 if (freezeList == null) {
473 Application.getExceptionHandler().handleErrorCondition("Attempting to thaw Rocket when it is not frozen");
476 if (freezeList.size() == 0) {
477 log.warn("Thawing rocket with no changes made");
482 log.debug("Thawing rocket, freezeList=" + freezeList);
486 for (ComponentChangeEvent e : freezeList) {
487 type = type | e.getType();
492 fireComponentChangeEvent(new ComponentChangeEvent((RocketComponent) c, type));
498 //////// Motor configurations ////////
502 * Return the default configuration. This should be used in the user interface
503 * to ensure a consistent rocket configuration between dialogs. It should NOT
504 * be used in simulations not relating to the UI.
506 * @return the default {@link Configuration}.
508 public Configuration getDefaultConfiguration() {
510 return defaultConfiguration;
515 * Return an array of the motor configuration IDs. This array is guaranteed
516 * to contain the <code>null</code> ID as the first element.
518 * @return an array of the motor configuration IDs.
520 public String[] getMotorConfigurationIDs() {
522 return motorConfigurationIDs.toArray(new String[0]);
526 * Add a new motor configuration ID to the motor configurations. The new ID
529 * @return the new motor configuration ID.
531 public String newMotorConfigurationID() {
533 String id = UUID.randomUUID().toString();
534 motorConfigurationIDs.add(id);
535 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
540 * Add a specified motor configuration ID to the motor configurations.
542 * @param id the motor configuration ID.
543 * @return true if successful, false if the ID was already used.
545 public boolean addMotorConfigurationID(String id) {
547 if (id == null || motorConfigurationIDs.contains(id))
549 motorConfigurationIDs.add(id);
550 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
555 * Remove a motor configuration ID from the configuration IDs. The <code>null</code>
556 * ID cannot be removed, and an attempt to remove it will be silently ignored.
558 * @param id the motor configuration ID to remove
560 public void removeMotorConfigurationID(String id) {
564 motorConfigurationIDs.remove(id);
565 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
570 * Check whether <code>id</code> is a valid motor configuration ID.
572 * @param id the configuration ID.
573 * @return whether a motor configuration with that ID exists.
575 public boolean isMotorConfigurationID(String id) {
577 return motorConfigurationIDs.contains(id);
583 * Check whether the given motor configuration ID has motors defined for it.
585 * @param id the motor configuration ID (may be invalid).
586 * @return whether any motors are defined for it.
588 public boolean hasMotors(String id) {
593 Iterator<RocketComponent> iterator = this.iterator();
594 while (iterator.hasNext()) {
595 RocketComponent c = iterator.next();
597 if (c instanceof MotorMount) {
598 MotorMount mount = (MotorMount) c;
599 if (!mount.isMotorMount())
601 if (mount.getMotor(id) != null) {
611 * Return the user-set name of the motor configuration. If no name has been set,
612 * returns an empty string (not null).
614 * @param id the motor configuration id
615 * @return the configuration name
617 public String getMotorConfigurationName(String id) {
619 if (!isMotorConfigurationID(id))
621 String s = motorConfigurationNames.get(id);
629 * Set the name of the motor configuration. A name can be unset by passing
630 * <code>null</code> or an empty string.
632 * @param id the motor configuration id
633 * @param name the name for the motor configuration
635 public void setMotorConfigurationName(String id, String name) {
637 motorConfigurationNames.put(id, name);
638 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
643 * Return either the motor configuration name (if set) or its description.
645 * @param id the motor configuration ID.
646 * @return a textual representation of the configuration
648 public String getMotorConfigurationNameOrDescription(String id) {
652 name = getMotorConfigurationName(id);
653 if (name != null && !name.equals(""))
656 return getMotorConfigurationDescription(id);
660 * Return a description for the motor configuration, generated from the motor
661 * designations of the components.
663 * @param id the motor configuration ID.
664 * @return a textual representation of the configuration
666 @SuppressWarnings("null")
667 public String getMotorConfigurationDescription(String id) {
672 // Generate the description
674 // First iterate over each stage and store the designations of each motor
675 List<List<String>> list = new ArrayList<List<String>>();
676 List<String> currentList = null;
678 Iterator<RocketComponent> iterator = this.iterator();
679 while (iterator.hasNext()) {
680 RocketComponent c = iterator.next();
682 if (c instanceof Stage) {
684 currentList = new ArrayList<String>();
685 list.add(currentList);
687 } else if (c instanceof MotorMount) {
689 MotorMount mount = (MotorMount) c;
690 Motor motor = mount.getMotor(id);
692 if (mount.isMotorMount() && motor != null) {
693 String designation = motor.getDesignation(mount.getMotorDelay(id));
695 for (int i = 0; i < mount.getMotorCount(); i++) {
696 currentList.add(designation);
704 if (motorCount == 0) {
706 return trans.get("Rocket.motorCount.Nomotor");
709 // Change multiple occurrences of a motor to n x motor
710 List<String> stages = new ArrayList<String>();
712 for (List<String> stage : list) {
713 String stageName = "";
714 String previous = null;
717 Collections.sort(stage);
718 for (String current : stage) {
719 if (current.equals(previous)) {
725 if (previous != null) {
728 s = "" + count + Chars.TIMES + previous;
733 if (stageName.equals(""))
736 stageName = stageName + "," + s;
744 if (previous != null) {
747 s = "" + count + Chars.TIMES + previous;
752 if (stageName.equals(""))
755 stageName = stageName + "," + s;
758 stages.add(stageName);
762 for (int i = 0; i < stages.size(); i++) {
763 String s = stages.get(i);
769 name = name + "; " + s;
777 //////// Obligatory component information
781 public String getComponentName() {
783 return trans.get("Rocket.compname.Rocket");
787 public Coordinate getComponentCG() {
788 return new Coordinate(0, 0, 0, 0);
792 public double getComponentMass() {
797 public double getLongitudinalUnitInertia() {
802 public double getRotationalUnitInertia() {
807 public Collection<Coordinate> getComponentBounds() {
808 return Collections.emptyList();
812 public boolean isAerodynamic() {
817 public boolean isMassive() {
822 public boolean allowsChildren() {
827 * Allows only <code>Stage</code> components to be added to the type Rocket.
830 public boolean isCompatible(Class<? extends RocketComponent> type) {
831 return (Stage.class.isAssignableFrom(type));