1 package net.sf.openrocket.rocketcomponent;
4 import java.util.ArrayDeque;
5 import java.util.Collection;
6 import java.util.Deque;
7 import java.util.Iterator;
9 import java.util.NoSuchElementException;
11 import javax.swing.event.ChangeListener;
13 import net.sf.openrocket.logging.LogHelper;
14 import net.sf.openrocket.startup.Application;
15 import net.sf.openrocket.util.ArrayList;
16 import net.sf.openrocket.util.BugException;
17 import net.sf.openrocket.util.ChangeSource;
18 import net.sf.openrocket.util.Coordinate;
19 import net.sf.openrocket.util.Invalidator;
20 import net.sf.openrocket.util.LineStyle;
21 import net.sf.openrocket.util.MathUtil;
22 import net.sf.openrocket.util.SafetyMutex;
23 import net.sf.openrocket.util.UniqueID;
26 public abstract class RocketComponent implements ChangeSource, Cloneable, Iterable<RocketComponent>,
27 Visitable<ComponentVisitor, RocketComponent> {
28 private static final LogHelper log = Application.getLogger();
31 * Text is suitable to the form
32 * Position relative to: <title>
34 public enum Position {
35 /** Position relative to the top of the parent component. */
36 TOP("Top of the parent component"),
37 /** Position relative to the middle of the parent component. */
38 MIDDLE("Middle of the parent component"),
39 /** Position relative to the bottom of the parent component. */
40 BOTTOM("Bottom of the parent component"),
41 /** Position after the parent component (for body components). */
42 AFTER("After the parent component"),
43 /** Specify an absolute X-coordinate position. */
44 ABSOLUTE("Tip of the nose cone");
48 Position(String title) {
53 public String toString() {
59 * A safety mutex that can be used to prevent concurrent access to this component.
61 protected SafetyMutex mutex = SafetyMutex.newInstance();
63 //////// Parent/child trees
65 * Parent component of the current component, or null if none exists.
67 private RocketComponent parent = null;
70 * List of child components of this component.
72 private ArrayList<RocketComponent> children = new ArrayList<RocketComponent>();
75 //////// Parameters common to all components:
78 * Characteristic length of the component. This is used in calculating the coordinate
79 * transformations and positions of other components in reference to this component.
80 * This may and should be used as the "true" length of the component, where applicable.
81 * By default it is zero, i.e. no translation.
83 protected double length = 0;
86 * Positioning of this component relative to the parent component.
88 protected Position relativePosition;
91 * Offset of the position of this component relative to the normal position given by
92 * relativePosition. By default zero, i.e. no position change.
94 protected double position = 0;
97 // Color of the component, null means to use the default color
98 private Color color = null;
99 private LineStyle lineStyle = null;
103 private double overrideMass = 0;
104 private boolean massOverriden = false;
105 private double overrideCGX = 0;
106 private boolean cgOverriden = false;
108 private boolean overrideSubcomponents = false;
111 // User-given name of the component
112 private String name = null;
114 // User-specified comment
115 private String comment = "";
117 // Unique ID of the component
118 private String id = null;
121 * Used to invalidate the component after calling {@link #copyFrom(RocketComponent)}.
123 private Invalidator invalidator = new Invalidator(this);
126 //// NOTE !!! All fields must be copied in the method copyFrom()! ////
131 * Default constructor. Sets the name of the component to the component's static name
132 * and the relative position of the component.
134 public RocketComponent(Position relativePosition) {
135 // These must not fire any events, due to Rocket undo system initialization
136 this.name = getComponentName();
137 this.relativePosition = relativePosition;
141 //////////// Methods that must be implemented ////////////
145 * Static component name. The name may not vary of the parameters, it must be static.
147 public abstract String getComponentName(); // Static component type name
150 * Return the component mass (regardless of mass overriding).
152 public abstract double getComponentMass(); // Mass of non-overridden component
155 * Return the component CG and mass (regardless of CG or mass overriding).
157 public abstract Coordinate getComponentCG(); // CG of non-overridden component
161 * Return the longitudinal (around the y- or z-axis) unitary moment of inertia.
162 * The unitary moment of inertia is the moment of inertia with the assumption that
163 * the mass of the component is one kilogram. The inertia is measured in
164 * respect to the non-overridden CG.
166 * @return the longitudinal unitary moment of inertia of this component.
168 public abstract double getLongitudinalUnitInertia();
172 * Return the rotational (around the x-axis) unitary moment of inertia.
173 * The unitary moment of inertia is the moment of inertia with the assumption that
174 * the mass of the component is one kilogram. The inertia is measured in
175 * respect to the non-overridden CG.
177 * @return the rotational unitary moment of inertia of this component.
179 public abstract double getRotationalUnitInertia();
183 * Test whether this component allows any children components. This method must
184 * return true if and only if {@link #isCompatible(Class)} returns true for any
185 * rocket component class.
187 * @return <code>true</code> if children can be attached to this component, <code>false</code> otherwise.
189 public abstract boolean allowsChildren();
192 * Test whether the given component type can be added to this component. This type safety
193 * is enforced by the <code>addChild()</code> methods. The return value of this method
194 * may change to reflect the current state of this component (e.g. two components of some
195 * type cannot be placed as children).
197 * @param type The RocketComponent class type to add.
198 * @return Whether such a component can be added.
200 public abstract boolean isCompatible(Class<? extends RocketComponent> type);
203 /* Non-abstract helper method */
205 * Test whether the given component can be added to this component. This is equivalent
206 * to calling <code>isCompatible(c.getClass())</code>.
208 * @param c Component to test.
209 * @return Whether the component can be added.
210 * @see #isCompatible(Class)
212 public final boolean isCompatible(RocketComponent c) {
214 return isCompatible(c.getClass());
220 * Return a collection of bounding coordinates. The coordinates must be such that
221 * the component is fully enclosed in their convex hull.
223 * @return a collection of coordinates that bound the component.
225 public abstract Collection<Coordinate> getComponentBounds();
228 * Return true if the component may have an aerodynamic effect on the rocket.
230 public abstract boolean isAerodynamic();
233 * Return true if the component may have an effect on the rocket's mass.
235 public abstract boolean isMassive();
241 //////////// Methods that may be overridden ////////////
245 * Shift the coordinates in the array corresponding to radial movement. A component
246 * that has a radial position must shift the coordinates in this array suitably.
247 * If the component is clustered, then a new array must be returned with a
248 * coordinate for each cluster.
250 * The default implementation simply returns the array, and thus produces no shift.
252 * @param c an array of coordinates to shift.
253 * @return an array of shifted coordinates. The method may modify the contents
254 * of the passed array and return the array itself.
256 public Coordinate[] shiftCoordinates(Coordinate[] c) {
263 * Called when any component in the tree fires a ComponentChangeEvent. This is by
264 * default a no-op, but subclasses may override this method to e.g. invalidate
265 * cached data. The overriding method *must* call
266 * <code>super.componentChanged(e)</code> at some point.
268 * @param e The event fired
270 protected void componentChanged(ComponentChangeEvent e) {
279 * Return the user-provided name of the component, or the component base
280 * name if the user-provided name is empty. This can be used in the UI.
282 * @return A string describing the component.
285 public final String toString() {
287 if (name.length() == 0)
288 return getComponentName();
295 * Create a string describing the basic component structure from this component downwards.
296 * @return a string containing the rocket structure
298 public final String toDebugString() {
299 mutex.lock("toDebugString");
301 StringBuilder sb = new StringBuilder();
303 return sb.toString();
305 mutex.unlock("toDebugString");
309 private void toDebugString(StringBuilder sb) {
310 sb.append(this.getClass().getSimpleName()).append('@').append(System.identityHashCode(this));
311 sb.append("[\"").append(this.getName()).append('"');
312 for (RocketComponent c : this.children) {
321 * Make a deep copy of the rocket component tree structure from this component
322 * downwards for copying purposes. Each component in the copy will be assigned
323 * a new component ID, making it a safe copy. This method does not fire any events.
325 * @return A deep copy of the structure.
327 public final RocketComponent copy() {
328 RocketComponent clone = copyWithOriginalID();
330 Iterator<RocketComponent> iterator = clone.iterator(true);
331 while (iterator.hasNext()) {
332 iterator.next().newID();
340 * Make a deep copy of the rocket component tree structure from this component
341 * downwards while maintaining the component ID's. The purpose of this method is
342 * to allow copies to be created with the original ID's for the purpose of the
343 * undo/redo mechanism. This method should not be used for other purposes,
344 * such as copy/paste. This method does not fire any events.
346 * This method must be overridden by any component that refers to mutable objects,
347 * or if some fields should not be copied. This should be performed by
348 * <code>RocketComponent c = super.copyWithOriginalID();</code> and then cloning/modifying
349 * the appropriate fields.
351 * This is not performed as serializing/deserializing for performance reasons.
353 * @return A deep copy of the structure.
355 protected RocketComponent copyWithOriginalID() {
356 mutex.lock("copyWithOriginalID");
359 RocketComponent clone;
361 clone = (RocketComponent) this.clone();
362 } catch (CloneNotSupportedException e) {
363 throw new BugException("CloneNotSupportedException encountered, report a bug!", e);
367 clone.mutex = SafetyMutex.newInstance();
369 // Reset all parent/child information
371 clone.children = new ArrayList<RocketComponent>();
373 // Add copied children to the structure without firing events.
374 for (RocketComponent child : this.children) {
375 RocketComponent childCopy = child.copyWithOriginalID();
376 // Don't use add method since it fires events
377 clone.children.add(childCopy);
378 childCopy.parent = clone;
381 this.checkComponentStructure();
382 clone.checkComponentStructure();
386 mutex.unlock("copyWithOriginalID");
392 * Accept a visitor to this RocketComponent in the component hierarchy.
394 * @param theVisitor the visitor that will be called back with a reference to this RocketComponent
397 public void accept(final ComponentVisitor theVisitor) {
398 theVisitor.visit(this);
401 ////////////// Methods that may not be overridden ////////////
405 ////////// Common parameter setting/getting //////////
408 * Return the color of the object to use in 2D figures, or <code>null</code>
409 * to use the default color.
411 public final Color getColor() {
417 * Set the color of the object to use in 2D figures.
419 public final void setColor(Color c) {
420 if ((color == null && c == null) ||
421 (color != null && color.equals(c)))
426 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
430 public final LineStyle getLineStyle() {
435 public final void setLineStyle(LineStyle style) {
436 if (this.lineStyle == style)
439 this.lineStyle = style;
440 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
447 * Get the current override mass. The mass is not necessarily in use
450 * @return the override mass
452 public final double getOverrideMass() {
458 * Set the current override mass. The mass is not set to use by this
461 * @param m the override mass
463 public final void setOverrideMass(double m) {
464 if (MathUtil.equals(m, overrideMass))
467 overrideMass = Math.max(m, 0);
469 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
473 * Return whether mass override is active for this component. This does NOT
474 * take into account whether a parent component is overriding the mass.
476 * @return whether the mass is overridden
478 public final boolean isMassOverridden() {
480 return massOverriden;
484 * Set whether the mass is currently overridden.
486 * @param o whether the mass is overridden
488 public final void setMassOverridden(boolean o) {
489 if (massOverriden == o) {
494 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
502 * Return the current override CG. The CG is not necessarily overridden.
504 * @return the override CG
506 public final Coordinate getOverrideCG() {
508 return getComponentCG().setX(overrideCGX);
512 * Return the x-coordinate of the current override CG.
514 * @return the x-coordinate of the override CG.
516 public final double getOverrideCGX() {
522 * Set the current override CG to (x,0,0).
524 * @param x the x-coordinate of the override CG to set.
526 public final void setOverrideCGX(double x) {
527 if (MathUtil.equals(overrideCGX, x))
530 this.overrideCGX = x;
531 if (isCGOverridden())
532 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
534 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
538 * Return whether the CG is currently overridden.
540 * @return whether the CG is overridden
542 public final boolean isCGOverridden() {
548 * Set whether the CG is currently overridden.
550 * @param o whether the CG is overridden
552 public final void setCGOverridden(boolean o) {
553 if (cgOverriden == o) {
558 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
564 * Return whether the mass and/or CG override overrides all subcomponent values
565 * as well. The default implementation is a normal getter/setter implementation,
566 * however, subclasses are allowed to override this behavior if some subclass
567 * always or never overrides subcomponents. In this case the subclass should
568 * also override {@link #isOverrideSubcomponentsEnabled()} to return
569 * <code>false</code>.
571 * @return whether the current mass and/or CG override overrides subcomponents as well.
573 public boolean getOverrideSubcomponents() {
575 return overrideSubcomponents;
580 * Set whether the mass and/or CG override overrides all subcomponent values
581 * as well. See {@link #getOverrideSubcomponents()} for details.
583 * @param override whether the mass and/or CG override overrides all subcomponent.
585 public void setOverrideSubcomponents(boolean override) {
586 if (overrideSubcomponents == override) {
590 overrideSubcomponents = override;
591 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
595 * Return whether the option to override all subcomponents is enabled or not.
596 * The default implementation returns <code>false</code> if neither mass nor
597 * CG is overridden, <code>true</code> otherwise.
599 * This method may be overridden if the setting of overriding subcomponents
602 * @return whether the option to override subcomponents is currently enabled.
604 public boolean isOverrideSubcomponentsEnabled() {
606 return isCGOverridden() || isMassOverridden();
613 * Get the user-defined name of the component.
615 public final String getName() {
621 * Set the user-defined name of the component. If name==null, sets the name to
622 * the default name, currently the component name.
624 public final void setName(String name) {
625 if (this.name.equals(name)) {
629 if (name == null || name.matches("^\\s*$"))
630 this.name = getComponentName();
633 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
638 * Return the comment of the component. The component may contain multiple lines
639 * using \n as a newline separator.
641 * @return the comment of the component.
643 public final String getComment() {
649 * Set the comment of the component.
651 * @param comment the comment of the component.
653 public final void setComment(String comment) {
654 if (this.comment.equals(comment))
660 this.comment = comment;
661 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
667 * Returns the unique ID of the component.
669 * @return the ID of the component.
671 public final String getID() {
676 * Generate a new ID for this component.
678 private final void newID() {
680 this.id = UniqueID.uuid();
687 * Get the characteristic length of the component, for example the length of a body tube
688 * of the length of the root chord of a fin. This is used in positioning the component
689 * relative to its parent.
691 * If the length of a component is settable, the class must define the setter method
694 public final double getLength() {
700 * Get the positioning of the component relative to its parent component.
701 * This is one of the enums of {@link Position}. A setter method is not provided,
702 * but can be provided by a subclass.
704 public final Position getRelativePosition() {
706 return relativePosition;
711 * Set the positioning of the component relative to its parent component.
712 * The actual position of the component is maintained to the best ability.
714 * The default implementation is of protected visibility, since many components
715 * do not support setting the relative position. A component that does support
716 * it should override this with a public method that simply calls this
717 * supermethod AND fire a suitable ComponentChangeEvent.
719 * @param position the relative positioning.
721 protected void setRelativePosition(RocketComponent.Position position) {
722 if (this.relativePosition == position)
726 // Update position so as not to move the component
727 if (this.parent != null) {
728 double thisPos = this.toRelative(Coordinate.NUL, this.parent)[0].x;
732 this.position = this.toAbsolute(Coordinate.NUL)[0].x;
736 this.position = thisPos;
740 this.position = thisPos - (this.parent.length - this.length) / 2;
744 this.position = thisPos - (this.parent.length - this.length);
748 throw new BugException("Unknown position type: " + position);
752 this.relativePosition = position;
753 fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE);
760 * Get the position value of the component. The exact meaning of the value is
761 * dependent on the current relative positioning.
763 * @return the positional value.
765 public final double getPositionValue() {
772 * Set the position value of the component. The exact meaning of the value
773 * depends on the current relative positioning.
775 * The default implementation is of protected visibility, since many components
776 * do not support setting the relative position. A component that does support
777 * it should override this with a public method that simply calls this
778 * supermethod AND fire a suitable ComponentChangeEvent.
780 * @param value the position value of the component.
782 public void setPositionValue(double value) {
783 if (MathUtil.equals(this.position, value))
786 this.position = value;
791 /////////// Coordinate changes ///////////
794 * Returns coordinate c in absolute coordinates. Equivalent to toComponent(c,null).
796 public Coordinate[] toAbsolute(Coordinate c) {
798 return toRelative(c, null);
803 * Return coordinate <code>c</code> described in the coordinate system of
804 * <code>dest</code>. If <code>dest</code> is <code>null</code> returns
805 * absolute coordinates.
807 * This method returns an array of coordinates, each of which represents a
808 * position of the coordinate in clustered cases. The array is guaranteed
809 * to contain at least one element.
811 * The current implementation does not support rotating components.
813 * @param c Coordinate in the component's coordinate system.
814 * @param dest Destination component coordinate system.
815 * @return an array of coordinates describing <code>c</code> in coordinates
816 * relative to <code>dest</code>.
818 public final Coordinate[] toRelative(Coordinate c, RocketComponent dest) {
820 mutex.lock("toRelative");
822 double absoluteX = Double.NaN;
823 RocketComponent search = dest;
824 Coordinate[] array = new Coordinate[1];
827 RocketComponent component = this;
828 while ((component != search) && (component.parent != null)) {
830 array = component.shiftCoordinates(array);
832 switch (component.relativePosition) {
834 for (int i = 0; i < array.length; i++) {
835 array[i] = array[i].add(component.position, 0, 0);
840 for (int i = 0; i < array.length; i++) {
841 array[i] = array[i].add(component.position +
842 (component.parent.length - component.length) / 2, 0, 0);
847 for (int i = 0; i < array.length; i++) {
848 array[i] = array[i].add(component.position +
849 (component.parent.length - component.length), 0, 0);
854 // Add length of all previous brother-components with POSITION_RELATIVE_AFTER
855 int index = component.parent.children.indexOf(component);
857 for (index--; index >= 0; index--) {
858 RocketComponent comp = component.parent.children.get(index);
859 double componentLength = comp.getTotalLength();
860 for (int i = 0; i < array.length; i++) {
861 array[i] = array[i].add(componentLength, 0, 0);
864 for (int i = 0; i < array.length; i++) {
865 array[i] = array[i].add(component.position + component.parent.length, 0, 0);
870 search = null; // Requires back-search if dest!=null
871 if (Double.isNaN(absoluteX)) {
872 absoluteX = component.position;
877 throw new BugException("Unknown relative positioning type of component" +
878 component + ": " + component.relativePosition);
881 component = component.parent; // parent != null
884 if (!Double.isNaN(absoluteX)) {
885 for (int i = 0; i < array.length; i++) {
886 array[i] = array[i].setX(absoluteX + c.x);
890 // Check whether destination has been found or whether to backtrack
891 // TODO: LOW: Backtracking into clustered components uses only one component
892 if ((dest != null) && (component != dest)) {
893 Coordinate[] origin = dest.toAbsolute(Coordinate.NUL);
894 for (int i = 0; i < array.length; i++) {
895 array[i] = array[i].sub(origin[0]);
901 mutex.unlock("toRelative");
907 * Recursively sum the lengths of all subcomponents that have position
910 * @return Sum of the lengths.
912 private final double getTotalLength() {
914 this.checkComponentStructure();
915 mutex.lock("getTotalLength");
918 if (relativePosition == Position.AFTER)
920 for (int i = 0; i < children.size(); i++)
921 l += children.get(i).getTotalLength();
924 mutex.unlock("getTotalLength");
930 /////////// Total mass and CG calculation ////////////
933 * Return the (possibly overridden) mass of component.
935 * @return The mass of the component or the given override mass.
937 public final double getMass() {
941 return getComponentMass();
945 * Return the (possibly overridden) center of gravity and mass.
947 * Returns the CG with the weight of the coordinate set to the weight of the component.
948 * Both CG and mass may be separately overridden.
950 * @return The CG of the component or the given override CG.
952 public final Coordinate getCG() {
955 return getOverrideCG().setWeight(getMass());
958 return getComponentCG().setWeight(getMass());
960 return getComponentCG();
965 * Return the longitudinal (around the y- or z-axis) moment of inertia of this component.
966 * The moment of inertia is scaled in reference to the (possibly overridden) mass
967 * and is relative to the non-overridden CG.
969 * @return the longitudinal moment of inertia of this component.
971 public final double getLongitudinalInertia() {
973 return getLongitudinalUnitInertia() * getMass();
977 * Return the rotational (around the y- or z-axis) moment of inertia of this component.
978 * The moment of inertia is scaled in reference to the (possibly overridden) mass
979 * and is relative to the non-overridden CG.
981 * @return the rotational moment of inertia of this component.
983 public final double getRotationalInertia() {
985 return getRotationalUnitInertia() * getMass();
990 /////////// Children handling ///////////
994 * Adds a child to the rocket component tree. The component is added to the end
995 * of the component's child list. This is a helper method that calls
996 * {@link #addChild(RocketComponent,int)}.
998 * @param component The component to add.
999 * @throws IllegalArgumentException if the component is already part of some
1001 * @see #addChild(RocketComponent,int)
1003 public final void addChild(RocketComponent component) {
1005 addChild(component, children.size());
1010 * Adds a child to the rocket component tree. The component is added to
1011 * the given position of the component's child list.
1013 * This method may be overridden to enforce more strict component addition rules.
1014 * The tests should be performed first and then this method called.
1016 * @param component The component to add.
1017 * @param index Position to add component to.
1018 * @throws IllegalArgumentException If the component is already part of
1019 * some component tree.
1021 public void addChild(RocketComponent component, int index) {
1023 if (component.parent != null) {
1024 throw new IllegalArgumentException("component " + component.getComponentName() +
1025 " is already in a tree");
1027 if (!isCompatible(component)) {
1028 throw new IllegalStateException("Component " + component.getComponentName() +
1029 " not currently compatible with component " + getComponentName());
1032 children.add(index, component);
1033 component.parent = this;
1035 this.checkComponentStructure();
1036 component.checkComponentStructure();
1038 fireAddRemoveEvent(component);
1043 * Removes a child from the rocket component tree.
1045 * @param n remove the n'th child.
1046 * @throws IndexOutOfBoundsException if n is out of bounds
1048 public final void removeChild(int n) {
1050 RocketComponent component = children.remove(n);
1051 component.parent = null;
1053 this.checkComponentStructure();
1054 component.checkComponentStructure();
1056 fireAddRemoveEvent(component);
1060 * Removes a child from the rocket component tree. Does nothing if the component
1061 * is not present as a child.
1063 * @param component the component to remove
1064 * @return whether the component was a child
1066 public final boolean removeChild(RocketComponent component) {
1069 component.checkComponentStructure();
1071 if (children.remove(component)) {
1072 component.parent = null;
1074 this.checkComponentStructure();
1075 component.checkComponentStructure();
1077 fireAddRemoveEvent(component);
1087 * Move a child to another position.
1089 * @param component the component to move
1090 * @param index the component's new position
1091 * @throws IllegalArgumentException If an illegal placement was attempted.
1093 public final void moveChild(RocketComponent component, int index) {
1095 if (children.remove(component)) {
1096 children.add(index, component);
1098 this.checkComponentStructure();
1099 component.checkComponentStructure();
1101 fireAddRemoveEvent(component);
1107 * Fires an AERODYNAMIC_CHANGE, MASS_CHANGE or OTHER_CHANGE event depending on the
1108 * type of component removed.
1110 private void fireAddRemoveEvent(RocketComponent component) {
1111 Iterator<RocketComponent> iter = component.iterator(true);
1112 int type = ComponentChangeEvent.TREE_CHANGE;
1113 while (iter.hasNext()) {
1114 RocketComponent c = iter.next();
1115 if (c.isAerodynamic())
1116 type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
1118 type |= ComponentChangeEvent.MASS_CHANGE;
1121 fireComponentChangeEvent(type);
1125 public final int getChildCount() {
1127 this.checkComponentStructure();
1128 return children.size();
1131 public final RocketComponent getChild(int n) {
1133 this.checkComponentStructure();
1134 return children.get(n);
1137 public final List<RocketComponent> getChildren() {
1139 this.checkComponentStructure();
1140 return children.clone();
1145 * Returns the position of the child in this components child list, or -1 if the
1146 * component is not a child of this component.
1148 * @param child The child to search for.
1149 * @return Position in the list or -1 if not found.
1151 public final int getChildPosition(RocketComponent child) {
1153 this.checkComponentStructure();
1154 return children.indexOf(child);
1158 * Get the parent component of this component. Returns <code>null</code> if the component
1161 * @return The parent of this component or <code>null</code>.
1163 public final RocketComponent getParent() {
1169 * Get the root component of the component tree.
1171 * @return The root component of the component tree.
1173 public final RocketComponent getRoot() {
1175 RocketComponent gp = this;
1176 while (gp.parent != null)
1182 * Returns the root Rocket component of this component tree. Throws an
1183 * IllegalStateException if the root component is not a Rocket.
1185 * @return The root Rocket component of the component tree.
1186 * @throws IllegalStateException If the root component is not a Rocket.
1188 public final Rocket getRocket() {
1190 RocketComponent r = getRoot();
1191 if (r instanceof Rocket)
1193 throw new IllegalStateException("getRocket() called with root component "
1194 + r.getComponentName());
1199 * Return the Stage component that this component belongs to. Throws an
1200 * IllegalStateException if a Stage is not in the parentage of this component.
1202 * @return The Stage component this component belongs to.
1203 * @throws IllegalStateException if a Stage component is not in the parentage.
1205 public final Stage getStage() {
1207 RocketComponent c = this;
1209 if (c instanceof Stage)
1213 throw new IllegalStateException("getStage() called without Stage as a parent.");
1217 * Return the stage number of the stage this component belongs to. The stages
1218 * are numbered from zero upwards.
1220 * @return the stage number this component belongs to.
1222 public final int getStageNumber() {
1224 if (parent == null) {
1225 throw new IllegalArgumentException("getStageNumber() called for root component");
1228 RocketComponent stage = this;
1229 while (!(stage instanceof Stage)) {
1230 stage = stage.parent;
1231 if (stage == null || stage.parent == null) {
1232 throw new IllegalStateException("getStageNumber() could not find parent " +
1236 return stage.parent.getChildPosition(stage);
1241 * Find a component with the given ID. The component tree is searched from this component
1242 * down (including this component) for the ID and the corresponding component is returned,
1243 * or null if not found.
1245 * @param idToFind ID to search for.
1246 * @return The component with the ID, or null if not found.
1248 public final RocketComponent findComponent(String idToFind) {
1250 Iterator<RocketComponent> iter = this.iterator(true);
1251 while (iter.hasNext()) {
1252 RocketComponent c = iter.next();
1253 if (c.getID().equals(idToFind))
1260 // TODO: Move these methods elsewhere (used only in SymmetricComponent)
1261 public final RocketComponent getPreviousComponent() {
1263 this.checkComponentStructure();
1266 int pos = parent.getChildPosition(this);
1268 StringBuffer sb = new StringBuffer();
1269 sb.append("Inconsistent internal state: ");
1270 sb.append("this=").append(this).append('[')
1271 .append(System.identityHashCode(this)).append(']');
1272 sb.append(" parent.children=[");
1273 for (int i = 0; i < parent.children.size(); i++) {
1274 RocketComponent c = parent.children.get(i);
1275 sb.append(c).append('[').append(System.identityHashCode(c)).append(']');
1276 if (i < parent.children.size() - 1)
1280 throw new IllegalStateException(sb.toString());
1285 RocketComponent c = parent.getChild(pos - 1);
1286 while (c.getChildCount() > 0)
1287 c = c.getChild(c.getChildCount() - 1);
1291 // TODO: Move these methods elsewhere (used only in SymmetricComponent)
1292 public final RocketComponent getNextComponent() {
1294 if (getChildCount() > 0)
1297 RocketComponent current = this;
1298 RocketComponent nextParent = this.parent;
1300 while (nextParent != null) {
1301 int pos = nextParent.getChildPosition(current);
1302 if (pos < nextParent.getChildCount() - 1)
1303 return nextParent.getChild(pos + 1);
1305 current = nextParent;
1306 nextParent = current.parent;
1312 /////////// Event handling //////////
1314 // Listener lists are provided by the root Rocket component,
1315 // a single listener list for the whole rocket.
1319 * Adds a ComponentChangeListener to the rocket tree. The listener is added to the root
1320 * component, which must be of type Rocket (which overrides this method). Events of all
1321 * subcomponents are sent to all listeners.
1323 * @throws IllegalStateException - if the root component is not a Rocket
1325 public void addComponentChangeListener(ComponentChangeListener l) {
1327 getRocket().addComponentChangeListener(l);
1331 * Removes a ComponentChangeListener from the rocket tree. The listener is removed from
1332 * the root component, which must be of type Rocket (which overrides this method).
1333 * Does nothing if the root component is not a Rocket. (The asymmetry is so
1334 * that listeners can always be removed just in case.)
1336 * @param l Listener to remove
1338 public void removeComponentChangeListener(ComponentChangeListener l) {
1339 if (parent != null) {
1340 getRoot().removeComponentChangeListener(l);
1346 * Adds a <code>ChangeListener</code> to the rocket tree. This is identical to
1347 * <code>addComponentChangeListener()</code> except that it uses a
1348 * <code>ChangeListener</code>. The same events are dispatched to the
1349 * <code>ChangeListener</code>, as <code>ComponentChangeEvent</code> is a subclass
1350 * of <code>ChangeEvent</code>.
1352 * @throws IllegalStateException - if the root component is not a <code>Rocket</code>
1355 public void addChangeListener(ChangeListener l) {
1357 getRocket().addChangeListener(l);
1361 * Removes a ChangeListener from the rocket tree. This is identical to
1362 * removeComponentChangeListener() except it uses a ChangeListener.
1363 * Does nothing if the root component is not a Rocket. (The asymmetry is so
1364 * that listeners can always be removed just in case.)
1366 * @param l Listener to remove
1369 public void removeChangeListener(ChangeListener l) {
1370 if (this.parent != null) {
1371 getRoot().removeChangeListener(l);
1377 * Fires a ComponentChangeEvent on the rocket structure. The call is passed to the
1378 * root component, which must be of type Rocket (which overrides this method).
1379 * Events of all subcomponents are sent to all listeners.
1381 * If the component tree root is not a Rocket, the event is ignored. This is the
1382 * case when constructing components not in any Rocket tree. In this case it
1383 * would be impossible for the component to have listeners in any case.
1385 * @param e Event to send
1387 protected void fireComponentChangeEvent(ComponentChangeEvent e) {
1389 if (parent == null) {
1390 /* Ignore if root invalid. */
1391 log.debug("Attempted firing event " + e + " with root " + this.getComponentName() + ", ignoring event");
1394 getRoot().fireComponentChangeEvent(e);
1399 * Fires a ComponentChangeEvent of the given type. The source of the event is set to
1402 * @param type Type of event
1403 * @see #fireComponentChangeEvent(ComponentChangeEvent)
1405 protected void fireComponentChangeEvent(int type) {
1406 fireComponentChangeEvent(new ComponentChangeEvent(this, type));
1411 * Checks whether this component has been invalidated and should no longer be used.
1412 * This is a safety check that in-place replaced components are no longer used.
1413 * All non-trivial methods (with the exception of methods simply getting a property)
1414 * should call this method before changing or computing anything.
1416 * @throws BugException if this component has been invalidated by {@link #copyFrom(RocketComponent)}.
1418 protected void checkState() {
1419 invalidator.check(true);
1425 * Check that the local component structure is correct. This can be called after changing
1426 * the component structure in order to verify the integrity.
1428 * TODO: Remove this after the "inconsistent internal state" bug has been corrected
1430 public void checkComponentStructure() {
1431 if (this.parent != null) {
1432 // Test that this component is found in parent's children with == operator
1433 if (!containsExact(this.parent.children, this)) {
1434 throw new BugException("Inconsistent component structure detected, parent does not contain this " +
1435 "component as a child, parent=" + parent.toDebugString() + " this=" + this.toDebugString());
1438 for (RocketComponent child : this.children) {
1439 if (child.parent != this) {
1440 throw new BugException("Inconsistent component structure detected, child does not have this component " +
1441 "as the parent, this=" + this.toDebugString() + " child=" + child.toDebugString() +
1442 " child.parent=" + (child.parent == null ? "null" : child.parent.toDebugString()));
1447 // Check whether the list contains exactly the searched-for component (with == operator)
1448 private boolean containsExact(List<RocketComponent> haystack, RocketComponent needle) {
1449 for (RocketComponent c : haystack) {
1458 /////////// Iterators //////////
1461 * Returns an iterator that iterates over all children and sub-children.
1463 * The iterator iterates through all children below this object, including itself if
1464 * <code>returnSelf</code> is true. The order of the iteration is not specified
1465 * (it may be specified in the future).
1467 * If an iterator iterating over only the direct children of the component is required,
1468 * use <code>component.getChildren().iterator()</code>.
1470 * TODO: HIGH: Remove this after merges have been done
1472 * @param returnSelf boolean value specifying whether the component itself should be
1474 * @return An iterator for the children and sub-children.
1475 * @deprecated Use {@link #iterator(boolean)} instead
1478 public final Iterator<RocketComponent> deepIterator(boolean returnSelf) {
1479 return iterator(returnSelf);
1484 * Returns an iterator that iterates over all children and sub-children, including itself.
1486 * This method is equivalent to <code>deepIterator(true)</code>.
1488 * TODO: HIGH: Remove this after merges have been done
1490 * @return An iterator for this component, its children and sub-children.
1491 * @deprecated Use {@link #iterator()} instead
1494 public final Iterator<RocketComponent> deepIterator() {
1501 * Returns an iterator that iterates over all children and sub-children.
1503 * The iterator iterates through all children below this object, including itself if
1504 * <code>returnSelf</code> is true. The order of the iteration is not specified
1505 * (it may be specified in the future).
1507 * If an iterator iterating over only the direct children of the component is required,
1508 * use <code>component.getChildren().iterator()</code>.
1510 * @param returnSelf boolean value specifying whether the component itself should be
1512 * @return An iterator for the children and sub-children.
1514 public final Iterator<RocketComponent> iterator(boolean returnSelf) {
1516 return new RocketComponentIterator(this, returnSelf);
1521 * Returns an iterator that iterates over this components, its children and sub-children.
1523 * This method is equivalent to <code>iterator(true)</code>.
1525 * @return An iterator for this component, its children and sub-children.
1528 public final Iterator<RocketComponent> iterator() {
1529 return iterator(true);
1537 * Compare component equality based on the ID of this component. Only the
1538 * ID and class type is used for a basis of comparison.
1541 public boolean equals(Object obj) {
1546 if (this.getClass() != obj.getClass())
1548 RocketComponent other = (RocketComponent) obj;
1549 return this.id.equals(other.id);
1555 public int hashCode() {
1556 return id.hashCode();
1561 //////////// Helper methods for subclasses
1567 * Helper method to add rotationally symmetric bounds at the specified coordinates.
1568 * The X-axis value is <code>x</code> and the radius at the specified position is
1571 protected static final void addBound(Collection<Coordinate> bounds, double x, double r) {
1572 bounds.add(new Coordinate(x, -r, -r));
1573 bounds.add(new Coordinate(x, r, -r));
1574 bounds.add(new Coordinate(x, r, r));
1575 bounds.add(new Coordinate(x, -r, r));
1579 protected static final Coordinate ringCG(double outerRadius, double innerRadius,
1580 double x1, double x2, double density) {
1581 return new Coordinate((x1 + x2) / 2, 0, 0,
1582 ringMass(outerRadius, innerRadius, x2 - x1, density));
1585 protected static final double ringMass(double outerRadius, double innerRadius,
1586 double length, double density) {
1587 return Math.PI * (MathUtil.pow2(outerRadius) - MathUtil.pow2(innerRadius)) *
1591 protected static final double ringLongitudinalUnitInertia(double outerRadius,
1592 double innerRadius, double length) {
1593 // 1/12 * (3 * (r1^2 + r2^2) + h^2)
1594 return (3 * (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) + MathUtil.pow2(length)) / 12;
1597 protected static final double ringRotationalUnitInertia(double outerRadius,
1598 double innerRadius) {
1599 // 1/2 * (r1^2 + r2^2)
1600 return (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) / 2;
1609 * Loads the RocketComponent fields from the given component. This method is meant
1610 * for in-place replacement of a component. It is used with the undo/redo
1611 * mechanism and when converting a finset into a freeform fin set.
1612 * This component must not have a parent, otherwise this method will fail.
1614 * The child components in the source tree are copied into the current tree, however,
1615 * the original components should not be used since they represent old copies of the
1616 * components. It is recommended to invalidate them by calling {@link #invalidate()}.
1618 * This method returns a list of components that should be invalidated after references
1619 * to them have been removed (for example by firing appropriate events). The list contains
1620 * all children and sub-children of the current component and the entire component
1621 * tree of <code>src</code>.
1623 * @return a list of components that should not be used after this call.
1625 protected List<RocketComponent> copyFrom(RocketComponent src) {
1627 List<RocketComponent> toInvalidate = new ArrayList<RocketComponent>();
1629 if (this.parent != null) {
1630 throw new UnsupportedOperationException("copyFrom called for non-root component, parent=" +
1631 this.parent.toDebugString() + ", this=" + this.toDebugString());
1634 // Add current structure to be invalidated
1635 Iterator<RocketComponent> iterator = this.iterator(false);
1636 while (iterator.hasNext()) {
1637 toInvalidate.add(iterator.next());
1640 // Remove previous components
1641 for (RocketComponent child : this.children) {
1642 child.parent = null;
1644 this.children.clear();
1646 // Copy new children to this component
1647 for (RocketComponent c : src.children) {
1648 RocketComponent copy = c.copyWithOriginalID();
1649 this.children.add(copy);
1653 this.checkComponentStructure();
1654 src.checkComponentStructure();
1656 // Set all parameters
1657 this.length = src.length;
1658 this.relativePosition = src.relativePosition;
1659 this.position = src.position;
1660 this.color = src.color;
1661 this.lineStyle = src.lineStyle;
1662 this.overrideMass = src.overrideMass;
1663 this.massOverriden = src.massOverriden;
1664 this.overrideCGX = src.overrideCGX;
1665 this.cgOverriden = src.cgOverriden;
1666 this.overrideSubcomponents = src.overrideSubcomponents;
1667 this.name = src.name;
1668 this.comment = src.comment;
1671 // Add source components to invalidation tree
1672 for (RocketComponent c : src) {
1673 toInvalidate.add(c);
1676 return toInvalidate;
1679 protected void invalidate() {
1680 invalidator.invalidate();
1684 ////////// Iterator implementation ///////////
1687 * Private inner class to implement the Iterator.
1689 * This iterator is fail-fast if the root of the structure is a Rocket.
1691 private static class RocketComponentIterator implements Iterator<RocketComponent> {
1692 // Stack holds iterators which still have some components left.
1693 private final Deque<Iterator<RocketComponent>> iteratorStack = new ArrayDeque<Iterator<RocketComponent>>();
1695 private final Rocket root;
1696 private final int treeModID;
1698 private final RocketComponent original;
1699 private boolean returnSelf = false;
1701 // Construct iterator with component's child's iterator, if it has elements
1702 public RocketComponentIterator(RocketComponent c, boolean returnSelf) {
1704 RocketComponent gp = c.getRoot();
1705 if (gp instanceof Rocket) {
1707 treeModID = root.getTreeModID();
1713 Iterator<RocketComponent> i = c.children.iterator();
1715 iteratorStack.push(i);
1718 this.returnSelf = returnSelf;
1722 public boolean hasNext() {
1726 return !iteratorStack.isEmpty(); // Elements remain if stack is not empty
1730 public RocketComponent next() {
1731 Iterator<RocketComponent> i;
1735 // Return original component first
1741 // Peek first iterator from stack, throw exception if empty
1742 i = iteratorStack.peek();
1744 throw new NoSuchElementException("No further elements in RocketComponent iterator");
1747 // Retrieve next component of the iterator, remove iterator from stack if empty
1748 RocketComponent c = i.next();
1750 iteratorStack.pop();
1752 // Add iterator of component children to stack if it has children
1753 i = c.children.iterator();
1755 iteratorStack.push(i);
1760 private void checkID() {
1762 if (root.getTreeModID() != treeModID) {
1763 throw new IllegalStateException("Rocket modified while being iterated");
1769 public void remove() {
1770 throw new UnsupportedOperationException("remove() not supported by " +
1771 "RocketComponent iterator");