1 package net.sf.openrocket.rocketcomponent;
4 import java.util.ArrayList;
5 import java.util.Collection;
6 import java.util.Collections;
7 import java.util.EmptyStackException;
8 import java.util.Iterator;
10 import java.util.NoSuchElementException;
11 import java.util.Stack;
13 import javax.swing.event.ChangeListener;
15 import net.sf.openrocket.logging.TraceException;
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.LineStyle;
20 import net.sf.openrocket.util.MathUtil;
21 import net.sf.openrocket.util.UniqueID;
24 public abstract class RocketComponent implements ChangeSource, Cloneable,
25 Iterable<RocketComponent> {
28 * Text is suitable to the form
29 * Position relative to: <title>
31 public enum Position {
32 /** Position relative to the top of the parent component. */
33 TOP("Top of the parent component"),
34 /** Position relative to the middle of the parent component. */
35 MIDDLE("Middle of the parent component"),
36 /** Position relative to the bottom of the parent component. */
37 BOTTOM("Bottom of the parent component"),
38 /** Position after the parent component (for body components). */
39 AFTER("After the parent component"),
40 /** Specify an absolute X-coordinate position. */
41 ABSOLUTE("Tip of the nose cone");
45 Position(String title) {
50 public String toString() {
55 //////// Parent/child trees
57 * Parent component of the current component, or null if none exists.
59 private RocketComponent parent = null;
62 * List of child components of this component.
64 private List<RocketComponent> children = new ArrayList<RocketComponent>();
67 //////// Parameters common to all components:
70 * Characteristic length of the component. This is used in calculating the coordinate
71 * transformations and positions of other components in reference to this component.
72 * This may and should be used as the "true" length of the component, where applicable.
73 * By default it is zero, i.e. no translation.
75 protected double length = 0;
78 * Positioning of this component relative to the parent component.
80 protected Position relativePosition;
83 * Offset of the position of this component relative to the normal position given by
84 * relativePosition. By default zero, i.e. no position change.
86 protected double position = 0;
89 // Color of the component, null means to use the default color
90 private Color color = null;
91 private LineStyle lineStyle = null;
95 private double overrideMass = 0;
96 private boolean massOverriden = false;
97 private double overrideCGX = 0;
98 private boolean cgOverriden = false;
100 private boolean overrideSubcomponents = false;
103 // User-given name of the component
104 private String name = null;
106 // User-specified comment
107 private String comment = "";
109 // Unique ID of the component
110 private String id = null;
113 * When invalidated is non-null this component cannot be used anymore.
114 * This is a safety mechanism to prevent accidental use after calling {@link #copyFrom(RocketComponent)}.
116 private TraceException invalidated = null;
118 //// NOTE !!! All fields must be copied in the method copyFrom()! ////
123 * Default constructor. Sets the name of the component to the component's static name
124 * and the relative position of the component.
126 public RocketComponent(Position relativePosition) {
127 // These must not fire any events, due to Rocket undo system initialization
128 this.name = getComponentName();
129 this.relativePosition = relativePosition;
137 //////////// Methods that must be implemented ////////////
141 * Static component name. The name may not vary of the parameters, it must be static.
143 public abstract String getComponentName(); // Static component type name
146 * Return the component mass (regardless of mass overriding).
148 public abstract double getComponentMass(); // Mass of non-overridden component
151 * Return the component CG and mass (regardless of CG or mass overriding).
153 public abstract Coordinate getComponentCG(); // CG of non-overridden component
157 * Return the longitudal (around the y- or z-axis) unitary moment of inertia.
158 * The unitary moment of inertia is the moment of inertia with the assumption that
159 * the mass of the component is one kilogram. The inertia is measured in
160 * respect to the non-overridden CG.
162 * @return the longitudal unitary moment of inertia of this component.
164 public abstract double getLongitudalUnitInertia();
168 * Return the rotational (around the x-axis) unitary moment of inertia.
169 * The unitary moment of inertia is the moment of inertia with the assumption that
170 * the mass of the component is one kilogram. The inertia is measured in
171 * respect to the non-overridden CG.
173 * @return the rotational unitary moment of inertia of this component.
175 public abstract double getRotationalUnitInertia();
179 * Test whether this component allows any children components. This method must
180 * return true if and only if {@link #isCompatible(Class)} returns true for any
181 * rocket component class.
183 * @return <code>true</code> if children can be attached to this component, <code>false</code> otherwise.
185 public abstract boolean allowsChildren();
188 * Test whether the given component type can be added to this component. This type safety
189 * is enforced by the <code>addChild()</code> methods. The return value of this method
190 * may change to reflect the current state of this component (e.g. two components of some
191 * type cannot be placed as children).
193 * @param type The RocketComponent class type to add.
194 * @return Whether such a component can be added.
196 public abstract boolean isCompatible(Class<? extends RocketComponent> type);
199 /* Non-abstract helper method */
201 * Test whether the given component can be added to this component. This is equivalent
202 * to calling <code>isCompatible(c.getClass())</code>.
204 * @param c Component to test.
205 * @return Whether the component can be added.
206 * @see #isCompatible(Class)
208 public final boolean isCompatible(RocketComponent c) {
210 return isCompatible(c.getClass());
216 * Return a collection of bounding coordinates. The coordinates must be such that
217 * the component is fully enclosed in their convex hull.
219 * @return a collection of coordinates that bound the component.
221 public abstract Collection<Coordinate> getComponentBounds();
224 * Return true if the component may have an aerodynamic effect on the rocket.
226 public abstract boolean isAerodynamic();
229 * Return true if the component may have an effect on the rocket's mass.
231 public abstract boolean isMassive();
237 //////////// Methods that may be overridden ////////////
241 * Shift the coordinates in the array corresponding to radial movement. A component
242 * that has a radial position must shift the coordinates in this array suitably.
243 * If the component is clustered, then a new array must be returned with a
244 * coordinate for each cluster.
246 * The default implementation simply returns the array, and thus produces no shift.
248 * @param c an array of coordinates to shift.
249 * @return an array of shifted coordinates. The method may modify the contents
250 * of the passed array and return the array itself.
252 public Coordinate[] shiftCoordinates(Coordinate[] c) {
259 * Called when any component in the tree fires a ComponentChangeEvent. This is by
260 * default a no-op, but subclasses may override this method to e.g. invalidate
261 * cached data. The overriding method *must* call
262 * <code>super.componentChanged(e)</code> at some point.
264 * @param e The event fired
266 protected void componentChanged(ComponentChangeEvent e) {
275 * Return a descriptive name of the component.
277 * The description may include extra information about the type of component,
278 * e.g. "Conical nose cone".
280 * @return A string describing the component.
283 public final String toString() {
285 return getComponentName();
291 public final void printStructure() {
292 System.out.println("Rocket structure from '" + this.toString() + "':");
296 private void printStructure(int level) {
299 for (int i = 0; i < level; i++) {
302 s += this.toString() + " (" + this.getComponentName() + ")";
303 System.out.println(s);
305 for (RocketComponent c : children) {
306 c.printStructure(level + 1);
312 * Make a deep copy of the rocket component tree structure from this component
313 * downwards for copying purposes. Each component in the copy will be assigned
314 * a new component ID, making it a safe copy. This method does not fire any events.
316 * @return A deep copy of the structure.
318 public final RocketComponent copy() {
319 RocketComponent clone = copyWithOriginalID();
321 Iterator<RocketComponent> iterator = clone.deepIterator(true);
322 while (iterator.hasNext()) {
323 iterator.next().newID();
331 * Make a deep copy of the rocket component tree structure from this component
332 * downwards while maintaining the component ID's. The purpose of this method is
333 * to allow copies to be created with the original ID's for the purpose of the
334 * undo/redo mechanism. This method should not be used for other purposes,
335 * such as copy/paste. This method does not fire any events.
337 * This method must be overridden by any component that refers to mutable objects,
338 * or if some fields should not be copied. This should be performed by
339 * <code>RocketComponent c = super.copyWithOriginalID();</code> and then cloning/modifying
340 * the appropriate fields.
342 * This is not performed as serializing/deserializing for performance reasons.
344 * @return A deep copy of the structure.
346 protected RocketComponent copyWithOriginalID() {
348 RocketComponent clone;
350 clone = (RocketComponent) this.clone();
351 } catch (CloneNotSupportedException e) {
352 throw new BugException("CloneNotSupportedException encountered, " +
356 // Reset all parent/child information
358 clone.children = new ArrayList<RocketComponent>();
360 // Add copied children to the structure without firing events.
361 for (RocketComponent child : this.children) {
362 RocketComponent childCopy = child.copyWithOriginalID();
363 // Don't use add method since it fires events
364 clone.children.add(childCopy);
365 childCopy.parent = clone;
372 ////////////// Methods that may not be overridden ////////////
376 ////////// Common parameter setting/getting //////////
379 * Return the color of the object to use in 2D figures, or <code>null</code>
380 * to use the default color.
382 public final Color getColor() {
388 * Set the color of the object to use in 2D figures.
390 public final void setColor(Color c) {
392 if ((color == null && c == null) ||
393 (color != null && color.equals(c)))
397 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
401 public final LineStyle getLineStyle() {
406 public final void setLineStyle(LineStyle style) {
408 if (this.lineStyle == style)
410 this.lineStyle = style;
411 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
418 * Get the current override mass. The mass is not necessarily in use
421 * @return the override mass
423 public final double getOverrideMass() {
429 * Set the current override mass. The mass is not set to use by this
432 * @param m the override mass
434 public final void setOverrideMass(double m) {
436 overrideMass = Math.max(m, 0);
438 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
442 * Return whether mass override is active for this component. This does NOT
443 * take into account whether a parent component is overriding the mass.
445 * @return whether the mass is overridden
447 public final boolean isMassOverridden() {
449 return massOverriden;
453 * Set whether the mass is currently overridden.
455 * @param o whether the mass is overridden
457 public final void setMassOverridden(boolean o) {
459 if (massOverriden != o) {
461 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
470 * Return the current override CG. The CG is not necessarily overridden.
472 * @return the override CG
474 public final Coordinate getOverrideCG() {
476 return getComponentCG().setX(overrideCGX);
480 * Return the x-coordinate of the current override CG.
482 * @return the x-coordinate of the override CG.
484 public final double getOverrideCGX() {
490 * Set the current override CG to (x,0,0).
492 * @param x the x-coordinate of the override CG to set.
494 public final void setOverrideCGX(double x) {
496 if (MathUtil.equals(overrideCGX, x))
498 this.overrideCGX = x;
499 if (isCGOverridden())
500 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
502 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
506 * Return whether the CG is currently overridden.
508 * @return whether the CG is overridden
510 public final boolean isCGOverridden() {
516 * Set whether the CG is currently overridden.
518 * @param o whether the CG is overridden
520 public final void setCGOverridden(boolean o) {
522 if (cgOverriden != o) {
524 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
531 * Return whether the mass and/or CG override overrides all subcomponent values
532 * as well. The default implementation is a normal getter/setter implementation,
533 * however, subclasses are allowed to override this behavior if some subclass
534 * always or never overrides subcomponents. In this case the subclass should
535 * also override {@link #isOverrideSubcomponentsEnabled()} to return
536 * <code>false</code>.
538 * @return whether the current mass and/or CG override overrides subcomponents as well.
540 public boolean getOverrideSubcomponents() {
542 return overrideSubcomponents;
547 * Set whether the mass and/or CG override overrides all subcomponent values
548 * as well. See {@link #getOverrideSubcomponents()} for details.
550 * @param override whether the mass and/or CG override overrides all subcomponent.
552 public void setOverrideSubcomponents(boolean override) {
554 if (overrideSubcomponents != override) {
555 overrideSubcomponents = override;
556 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
561 * Return whether the option to override all subcomponents is enabled or not.
562 * The default implementation returns <code>false</code> if neither mass nor
563 * CG is overridden, <code>true</code> otherwise.
565 * This method may be overridden if the setting of overriding subcomponents
568 * @return whether the option to override subcomponents is currently enabled.
570 public boolean isOverrideSubcomponentsEnabled() {
572 return isCGOverridden() || isMassOverridden();
579 * Get the user-defined name of the component.
581 public final String getName() {
586 * Set the user-defined name of the component. If name==null, sets the name to
587 * the default name, currently the component name.
589 public final void setName(String name) {
591 if (name == null || name.matches("^\\s*$"))
592 this.name = getComponentName();
595 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
600 * Return the comment of the component. The component may contain multiple lines
601 * using \n as a newline separator.
603 * @return the comment of the component.
605 public final String getComment() {
611 * Set the comment of the component.
613 * @param comment the comment of the component.
615 public final void setComment(String comment) {
617 if (this.comment.equals(comment))
622 this.comment = comment;
623 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
629 * Returns the unique ID of the component.
631 * @return the ID of the component.
633 public final String getID() {
638 * Generate a new ID for this component.
640 private final void newID() {
641 this.id = UniqueID.uuid();
648 * Get the characteristic length of the component, for example the length of a body tube
649 * of the length of the root chord of a fin. This is used in positioning the component
650 * relative to its parent.
652 * If the length of a component is settable, the class must define the setter method
655 public final double getLength() {
661 * Get the positioning of the component relative to its parent component.
662 * This is one of the enums of {@link Position}. A setter method is not provided,
663 * but can be provided by a subclass.
665 public final Position getRelativePosition() {
667 return relativePosition;
672 * Set the positioning of the component relative to its parent component.
673 * The actual position of the component is maintained to the best ability.
675 * The default implementation is of protected visibility, since many components
676 * do not support setting the relative position. A component that does support
677 * it should override this with a public method that simply calls this
678 * supermethod AND fire a suitable ComponentChangeEvent.
680 * @param position the relative positioning.
682 protected void setRelativePosition(RocketComponent.Position position) {
684 if (this.relativePosition == position)
687 // Update position so as not to move the component
688 if (this.parent != null) {
689 double thisPos = this.toRelative(Coordinate.NUL, this.parent)[0].x;
693 this.position = this.toAbsolute(Coordinate.NUL)[0].x;
697 this.position = thisPos;
701 this.position = thisPos - (this.parent.length - this.length) / 2;
705 this.position = thisPos - (this.parent.length - this.length);
709 throw new BugException("Unknown position type: " + position);
713 this.relativePosition = position;
714 fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE);
721 * Get the position value of the component. The exact meaning of the value is
722 * dependent on the current relative positioning.
724 * @return the positional value.
726 public final double getPositionValue() {
733 * Set the position value of the component. The exact meaning of the value
734 * depends on the current relative positioning.
736 * The default implementation is of protected visibility, since many components
737 * do not support setting the relative position. A component that does support
738 * it should override this with a public method that simply calls this
739 * supermethod AND fire a suitable ComponentChangeEvent.
741 * @param value the position value of the component.
743 public void setPositionValue(double value) {
745 if (MathUtil.equals(this.position, value))
747 this.position = value;
752 /////////// Coordinate changes ///////////
755 * Returns coordinate c in absolute coordinates. Equivalent to toComponent(c,null).
757 public Coordinate[] toAbsolute(Coordinate c) {
759 return toRelative(c, null);
764 * Return coordinate <code>c</code> described in the coordinate system of
765 * <code>dest</code>. If <code>dest</code> is <code>null</code> returns
766 * absolute coordinates.
768 * This method returns an array of coordinates, each of which represents a
769 * position of the coordinate in clustered cases. The array is guaranteed
770 * to contain at least one element.
772 * The current implementation does not support rotating components.
774 * @param c Coordinate in the component's coordinate system.
775 * @param dest Destination component coordinate system.
776 * @return an array of coordinates describing <code>c</code> in coordinates
777 * relative to <code>dest</code>.
779 public final Coordinate[] toRelative(Coordinate c, RocketComponent dest) {
781 double absoluteX = Double.NaN;
782 RocketComponent search = dest;
783 Coordinate[] array = new Coordinate[1];
786 RocketComponent component = this;
787 while ((component != search) && (component.parent != null)) {
789 array = component.shiftCoordinates(array);
791 switch (component.relativePosition) {
793 for (int i = 0; i < array.length; i++) {
794 array[i] = array[i].add(component.position, 0, 0);
799 for (int i = 0; i < array.length; i++) {
800 array[i] = array[i].add(component.position +
801 (component.parent.length - component.length) / 2, 0, 0);
806 for (int i = 0; i < array.length; i++) {
807 array[i] = array[i].add(component.position +
808 (component.parent.length - component.length), 0, 0);
813 // Add length of all previous brother-components with POSITION_RELATIVE_AFTER
814 int index = component.parent.children.indexOf(component);
816 for (index--; index >= 0; index--) {
817 RocketComponent comp = component.parent.children.get(index);
818 double length = comp.getTotalLength();
819 for (int i = 0; i < array.length; i++) {
820 array[i] = array[i].add(length, 0, 0);
823 for (int i = 0; i < array.length; i++) {
824 array[i] = array[i].add(component.position + component.parent.length, 0, 0);
829 search = null; // Requires back-search if dest!=null
830 if (Double.isNaN(absoluteX)) {
831 absoluteX = component.position;
836 throw new BugException("Unknown relative positioning type of component" +
837 component + ": " + component.relativePosition);
840 component = component.parent; // parent != null
843 if (!Double.isNaN(absoluteX)) {
844 for (int i = 0; i < array.length; i++) {
845 array[i] = array[i].setX(absoluteX + c.x);
849 // Check whether destination has been found or whether to backtrack
850 // TODO: LOW: Backtracking into clustered components uses only one component
851 if ((dest != null) && (component != dest)) {
852 Coordinate[] origin = dest.toAbsolute(Coordinate.NUL);
853 for (int i = 0; i < array.length; i++) {
854 array[i] = array[i].sub(origin[0]);
863 * Recursively sum the lengths of all subcomponents that have position
866 * @return Sum of the lengths.
868 private final double getTotalLength() {
871 if (relativePosition == Position.AFTER)
873 for (int i = 0; i < children.size(); i++)
874 l += children.get(i).getTotalLength();
880 /////////// Total mass and CG calculation ////////////
883 * Return the (possibly overridden) mass of component.
885 * @return The mass of the component or the given override mass.
887 public final double getMass() {
891 return getComponentMass();
895 * Return the (possibly overridden) center of gravity and mass.
897 * Returns the CG with the weight of the coordinate set to the weight of the component.
898 * Both CG and mass may be separately overridden.
900 * @return The CG of the component or the given override CG.
902 public final Coordinate getCG() {
905 return getOverrideCG().setWeight(getMass());
908 return getComponentCG().setWeight(getMass());
910 return getComponentCG();
915 * Return the longitudal (around the y- or z-axis) moment of inertia of this component.
916 * The moment of inertia is scaled in reference to the (possibly overridden) mass
917 * and is relative to the non-overridden CG.
919 * @return the longitudal moment of inertia of this component.
921 public final double getLongitudalInertia() {
923 return getLongitudalUnitInertia() * getMass();
927 * Return the rotational (around the y- or z-axis) moment of inertia of this component.
928 * The moment of inertia is scaled in reference to the (possibly overridden) mass
929 * and is relative to the non-overridden CG.
931 * @return the rotational moment of inertia of this component.
933 public final double getRotationalInertia() {
935 return getRotationalUnitInertia() * getMass();
940 /////////// Children handling ///////////
944 * Adds a child to the rocket component tree. The component is added to the end
945 * of the component's child list. This is a helper method that calls
946 * {@link #addChild(RocketComponent,int)}.
948 * @param component The component to add.
949 * @throws IllegalArgumentException if the component is already part of some
951 * @see #addChild(RocketComponent,int)
953 public final void addChild(RocketComponent component) {
955 addChild(component, children.size());
960 * Adds a child to the rocket component tree. The component is added to
961 * the given position of the component's child list.
963 * This method may be overridden to enforce more strict component addition rules.
964 * The tests should be performed first and then this method called.
966 * @param component The component to add.
967 * @param position Position to add component to.
968 * @throws IllegalArgumentException If the component is already part of
969 * some component tree.
971 public void addChild(RocketComponent component, int position) {
973 if (component.parent != null) {
974 throw new IllegalArgumentException("component " + component.getComponentName() +
975 " is already in a tree");
977 if (!isCompatible(component)) {
978 throw new IllegalStateException("Component " + component.getComponentName() +
979 " not currently compatible with component " + getComponentName());
982 children.add(position, component);
983 component.parent = this;
985 fireAddRemoveEvent(component);
990 * Removes a child from the rocket component tree.
992 * @param n remove the n'th child.
993 * @throws IndexOutOfBoundsException if n is out of bounds
995 public final void removeChild(int n) {
997 RocketComponent component = children.remove(n);
998 component.parent = null;
999 fireAddRemoveEvent(component);
1003 * Removes a child from the rocket component tree. Does nothing if the component
1004 * is not present as a child.
1006 * @param component the component to remove
1007 * @return whether the component was a child
1009 public final boolean removeChild(RocketComponent component) {
1011 if (children.remove(component)) {
1012 component.parent = null;
1013 fireAddRemoveEvent(component);
1023 * Move a child to another position.
1025 * @param component the component to move
1026 * @param position the component's new position
1027 * @throws IllegalArgumentException If an illegal placement was attempted.
1029 public final void moveChild(RocketComponent component, int position) {
1031 if (children.remove(component)) {
1032 children.add(position, component);
1033 fireAddRemoveEvent(component);
1039 * Fires an AERODYNAMIC_CHANGE, MASS_CHANGE or OTHER_CHANGE event depending on the
1040 * type of component removed.
1042 private void fireAddRemoveEvent(RocketComponent component) {
1043 Iterator<RocketComponent> iter = component.deepIterator(true);
1044 int type = ComponentChangeEvent.TREE_CHANGE;
1045 while (iter.hasNext()) {
1046 RocketComponent c = iter.next();
1047 if (c.isAerodynamic())
1048 type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
1050 type |= ComponentChangeEvent.MASS_CHANGE;
1053 fireComponentChangeEvent(type);
1057 public final int getChildCount() {
1059 return children.size();
1062 public final RocketComponent getChild(int n) {
1064 return children.get(n);
1067 public final RocketComponent[] getChildren() {
1069 return children.toArray(new RocketComponent[0]);
1074 * Returns the position of the child in this components child list, or -1 if the
1075 * component is not a child of this component.
1077 * @param child The child to search for.
1078 * @return Position in the list or -1 if not found.
1080 public final int getChildPosition(RocketComponent child) {
1082 return children.indexOf(child);
1086 * Get the parent component of this component. Returns <code>null</code> if the component
1089 * @return The parent of this component or <code>null</code>.
1091 public final RocketComponent getParent() {
1097 * Get the root component of the component tree.
1099 * @return The root component of the component tree.
1101 public final RocketComponent getRoot() {
1103 RocketComponent gp = this;
1104 while (gp.parent != null)
1110 * Returns the root Rocket component of this component tree. Throws an
1111 * IllegalStateException if the root component is not a Rocket.
1113 * @return The root Rocket component of the component tree.
1114 * @throws IllegalStateException If the root component is not a Rocket.
1116 public final Rocket getRocket() {
1118 RocketComponent r = getRoot();
1119 if (r instanceof Rocket)
1121 throw new IllegalStateException("getRocket() called with root component "
1122 + r.getComponentName());
1127 * Return the Stage component that this component belongs to. Throws an
1128 * IllegalStateException if a Stage is not in the parentage of this component.
1130 * @return The Stage component this component belongs to.
1131 * @throws IllegalStateException if a Stage component is not in the parentage.
1133 public final Stage getStage() {
1135 RocketComponent c = this;
1137 if (c instanceof Stage)
1141 throw new IllegalStateException("getStage() called without Stage as a parent.");
1145 * Return the stage number of the stage this component belongs to. The stages
1146 * are numbered from zero upwards.
1148 * @return the stage number this component belongs to.
1150 public final int getStageNumber() {
1152 if (parent == null) {
1153 throw new IllegalArgumentException("getStageNumber() called for root component");
1156 RocketComponent stage = this;
1157 while (!(stage instanceof Stage)) {
1158 stage = stage.parent;
1159 if (stage == null || stage.parent == null) {
1160 throw new IllegalStateException("getStageNumber() could not find parent " +
1164 return stage.parent.getChildPosition(stage);
1169 * Find a component with the given ID. The component tree is searched from this component
1170 * down (including this component) for the ID and the corresponding component is returned,
1171 * or null if not found.
1173 * @param idToFind ID to search for.
1174 * @return The component with the ID, or null if not found.
1176 public final RocketComponent findComponent(String idToFind) {
1178 Iterator<RocketComponent> iter = this.deepIterator(true);
1179 while (iter.hasNext()) {
1180 RocketComponent c = iter.next();
1181 if (c.getID().equals(idToFind))
1188 public final RocketComponent getPreviousComponent() {
1192 int pos = parent.getChildPosition(this);
1194 StringBuffer sb = new StringBuffer();
1195 sb.append("Inconsistent internal state: ");
1196 sb.append("this=").append(this).append('[')
1197 .append(System.identityHashCode(this)).append(']');
1198 sb.append(" parent.children=[");
1199 for (int i = 0; i < parent.children.size(); i++) {
1200 RocketComponent c = parent.children.get(i);
1201 sb.append(c).append('[').append(System.identityHashCode(c)).append(']');
1202 if (i < parent.children.size() - 1)
1206 throw new IllegalStateException(sb.toString());
1211 RocketComponent c = parent.getChild(pos - 1);
1212 while (c.getChildCount() > 0)
1213 c = c.getChild(c.getChildCount() - 1);
1217 public final RocketComponent getNextComponent() {
1219 if (getChildCount() > 0)
1222 RocketComponent current = this;
1223 RocketComponent parent = this.parent;
1225 while (parent != null) {
1226 int pos = parent.getChildPosition(current);
1227 if (pos < parent.getChildCount() - 1)
1228 return parent.getChild(pos + 1);
1231 parent = current.parent;
1237 /////////// Event handling //////////
1239 // Listener lists are provided by the root Rocket component,
1240 // a single listener list for the whole rocket.
1244 * Adds a ComponentChangeListener to the rocket tree. The listener is added to the root
1245 * component, which must be of type Rocket (which overrides this method). Events of all
1246 * subcomponents are sent to all listeners.
1248 * @throws IllegalStateException - if the root component is not a Rocket
1250 public void addComponentChangeListener(ComponentChangeListener l) {
1252 getRocket().addComponentChangeListener(l);
1256 * Removes a ComponentChangeListener from the rocket tree. The listener is removed from
1257 * the root component, which must be of type Rocket (which overrides this method).
1258 * Does nothing if the root component is not a Rocket. (The asymmetry is so
1259 * that listeners can always be removed just in case.)
1261 * @param l Listener to remove
1263 public void removeComponentChangeListener(ComponentChangeListener l) {
1264 if (parent != null) {
1265 getRoot().removeComponentChangeListener(l);
1271 * Adds a <code>ChangeListener</code> to the rocket tree. This is identical to
1272 * <code>addComponentChangeListener()</code> except that it uses a
1273 * <code>ChangeListener</code>. The same events are dispatched to the
1274 * <code>ChangeListener</code>, as <code>ComponentChangeEvent</code> is a subclass
1275 * of <code>ChangeEvent</code>.
1277 * @throws IllegalStateException - if the root component is not a <code>Rocket</code>
1279 public void addChangeListener(ChangeListener l) {
1281 getRocket().addChangeListener(l);
1285 * Removes a ChangeListener from the rocket tree. This is identical to
1286 * removeComponentChangeListener() except it uses a ChangeListener.
1287 * Does nothing if the root component is not a Rocket. (The asymmetry is so
1288 * that listeners can always be removed just in case.)
1290 * @param l Listener to remove
1292 public void removeChangeListener(ChangeListener l) {
1293 if (this.parent != null) {
1294 getRoot().removeChangeListener(l);
1300 * Fires a ComponentChangeEvent on the rocket structure. The call is passed to the
1301 * root component, which must be of type Rocket (which overrides this method).
1302 * Events of all subcomponents are sent to all listeners.
1304 * If the component tree root is not a Rocket, the event is ignored. This is the
1305 * case when constructing components not in any Rocket tree. In this case it
1306 * would be impossible for the component to have listeners in any case.
1308 * @param e Event to send
1310 protected void fireComponentChangeEvent(ComponentChangeEvent e) {
1312 if (parent == null) {
1313 /* Ignore if root invalid. */
1316 getRoot().fireComponentChangeEvent(e);
1321 * Fires a ComponentChangeEvent of the given type. The source of the event is set to
1324 * @param type Type of event
1325 * @see #fireComponentChangeEvent(ComponentChangeEvent)
1327 protected void fireComponentChangeEvent(int type) {
1328 fireComponentChangeEvent(new ComponentChangeEvent(this, type));
1333 * Checks whether this component has been invalidated and should no longer be used.
1334 * This is a safety check that in-place replaced components are no longer used.
1335 * All non-trivial methods should call this method as the first thing, unless the
1336 * method may be used in debugging cases.
1338 * @throws BugException if this component has been invalidated by {@link #copyFrom(RocketComponent)}.
1340 protected void checkState() {
1341 if (invalidated != null) {
1342 throw new BugException("This component has been invalidated. Cause is the point of invalidation.",
1348 /////////// Iterator implementation //////////
1351 * Private inner class to implement the Iterator.
1353 * This iterator is fail-fast if the root of the structure is a Rocket.
1355 private class RocketComponentIterator implements Iterator<RocketComponent> {
1356 // Stack holds iterators which still have some components left.
1357 private final Stack<Iterator<RocketComponent>> iteratorstack =
1358 new Stack<Iterator<RocketComponent>>();
1360 private final Rocket root;
1361 private final int treeModID;
1363 private final RocketComponent original;
1364 private boolean returnSelf = false;
1366 // Construct iterator with component's child's iterator, if it has elements
1367 public RocketComponentIterator(RocketComponent c, boolean returnSelf) {
1369 RocketComponent gp = c.getRoot();
1370 if (gp instanceof Rocket) {
1372 treeModID = root.getTreeModID();
1378 Iterator<RocketComponent> i = c.children.iterator();
1380 iteratorstack.push(i);
1383 this.returnSelf = returnSelf;
1386 public boolean hasNext() {
1391 return !iteratorstack.empty(); // Elements remain if stack is not empty
1394 public RocketComponent next() {
1395 Iterator<RocketComponent> i;
1400 // Return original component first
1406 // Peek first iterator from stack, throw exception if empty
1408 i = iteratorstack.peek();
1409 } catch (EmptyStackException e) {
1410 throw new NoSuchElementException("No further elements in " +
1411 "RocketComponent iterator");
1414 // Retrieve next component of the iterator, remove iterator from stack if empty
1415 RocketComponent c = i.next();
1417 iteratorstack.pop();
1419 // Add iterator of component children to stack if it has children
1420 i = c.children.iterator();
1422 iteratorstack.push(i);
1427 private void checkID() {
1429 if (root.getTreeModID() != treeModID) {
1430 throw new IllegalStateException("Rocket modified while being iterated");
1435 public void remove() {
1436 throw new UnsupportedOperationException("remove() not supported by " +
1437 "RocketComponent iterator");
1442 * Returns an iterator that iterates over all children and sub-children.
1444 * The iterator iterates through all children below this object, including itself if
1445 * returnSelf is true. The order of the iteration is not specified
1446 * (it may be specified in the future).
1448 * If an iterator iterating over only the direct children of the component is required,
1449 * use component.getChildren().iterator()
1451 * @param returnSelf boolean value specifying whether the component itself should be
1453 * @return An iterator for the children and sub-children.
1455 public final Iterator<RocketComponent> deepIterator(boolean returnSelf) {
1457 return new RocketComponentIterator(this, returnSelf);
1461 * Returns an iterator that iterates over all children and sub-children.
1463 * The iterator does NOT return the component itself. It is thus equivalent to
1464 * deepIterator(false).
1467 * @return An iterator for the children and sub-children.
1469 public final Iterator<RocketComponent> deepIterator() {
1471 return new RocketComponentIterator(this, false);
1476 * Return an iterator that iterates of the children of the component. The iterator
1477 * does NOT recurse to sub-children nor return itself.
1479 * @return An iterator for the children.
1481 public final Iterator<RocketComponent> iterator() {
1483 return Collections.unmodifiableList(children).iterator();
1490 * Compare component equality based on the ID of this component. Only the
1491 * ID and class type is used for a basis of comparison.
1494 public boolean equals(Object obj) {
1499 if (this.getClass() != obj.getClass())
1501 RocketComponent other = (RocketComponent) obj;
1502 return this.id.equals(other.id);
1508 public int hashCode() {
1509 return id.hashCode();
1514 //////////// Helper methods for subclasses
1520 * Helper method to add rotationally symmetric bounds at the specified coordinates.
1521 * The X-axis value is <code>x</code> and the radius at the specified position is
1524 protected static final void addBound(Collection<Coordinate> bounds, double x, double r) {
1525 bounds.add(new Coordinate(x, -r, -r));
1526 bounds.add(new Coordinate(x, r, -r));
1527 bounds.add(new Coordinate(x, r, r));
1528 bounds.add(new Coordinate(x, -r, r));
1532 protected static final Coordinate ringCG(double outerRadius, double innerRadius,
1533 double x1, double x2, double density) {
1534 return new Coordinate((x1 + x2) / 2, 0, 0,
1535 ringMass(outerRadius, innerRadius, x2 - x1, density));
1538 protected static final double ringMass(double outerRadius, double innerRadius,
1539 double length, double density) {
1540 return Math.PI * (MathUtil.pow2(outerRadius) - MathUtil.pow2(innerRadius)) *
1544 protected static final double ringLongitudalUnitInertia(double outerRadius,
1545 double innerRadius, double length) {
1546 // 1/12 * (3 * (r1^2 + r2^2) + h^2)
1547 return (3 * (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) + MathUtil.pow2(length)) / 12;
1550 protected static final double ringRotationalUnitInertia(double outerRadius,
1551 double innerRadius) {
1552 // 1/2 * (r1^2 + r2^2)
1553 return (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) / 2;
1562 * Loads the RocketComponent fields from the given component. This method is meant
1563 * for in-place replacement of a component. It is used with the undo/redo
1564 * mechanism and when converting a finset into a freeform fin set.
1565 * This component must not have a parent, otherwise this method will fail.
1567 * The fields are copied by reference, and the supplied component must not be used
1568 * after the call, as it is in an undefined state. This is enforced by invalidating
1569 * the source component.
1571 * TODO: MEDIUM: Make general to copy all private/protected fields...
1573 protected void copyFrom(RocketComponent src) {
1576 if (this.parent != null) {
1577 throw new UnsupportedOperationException("copyFrom called for non-root component "
1581 // Set parents and children
1582 this.children = src.children;
1583 src.children = new ArrayList<RocketComponent>();
1585 for (RocketComponent c : this.children) {
1589 // Set all parameters
1590 this.length = src.length;
1591 this.relativePosition = src.relativePosition;
1592 this.position = src.position;
1593 this.color = src.color;
1594 this.lineStyle = src.lineStyle;
1595 this.overrideMass = src.overrideMass;
1596 this.massOverriden = src.massOverriden;
1597 this.overrideCGX = src.overrideCGX;
1598 this.cgOverriden = src.cgOverriden;
1599 this.overrideSubcomponents = src.overrideSubcomponents;
1600 this.name = src.name;
1601 this.comment = src.comment;
1604 src.invalidated = new TraceException();