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) {
209 return isCompatible(c.getClass());
215 * Return a collection of bounding coordinates. The coordinates must be such that
216 * the component is fully enclosed in their convex hull.
218 * @return a collection of coordinates that bound the component.
220 public abstract Collection<Coordinate> getComponentBounds();
223 * Return true if the component may have an aerodynamic effect on the rocket.
225 public abstract boolean isAerodynamic();
228 * Return true if the component may have an effect on the rocket's mass.
230 public abstract boolean isMassive();
236 //////////// Methods that may be overridden ////////////
240 * Shift the coordinates in the array corresponding to radial movement. A component
241 * that has a radial position must shift the coordinates in this array suitably.
242 * If the component is clustered, then a new array must be returned with a
243 * coordinate for each cluster.
245 * The default implementation simply returns the array, and thus produces no shift.
247 * @param c an array of coordinates to shift.
248 * @return an array of shifted coordinates. The method may modify the contents
249 * of the passed array and return the array itself.
251 public Coordinate[] shiftCoordinates(Coordinate[] c) {
258 * Called when any component in the tree fires a ComponentChangeEvent. This is by
259 * default a no-op, but subclasses may override this method to e.g. invalidate
260 * cached data. The overriding method *must* call
261 * <code>super.componentChanged(e)</code> at some point.
263 * @param e The event fired
265 protected void componentChanged(ComponentChangeEvent e) {
274 * Return a descriptive name of the component.
276 * The description may include extra information about the type of component,
277 * e.g. "Conical nose cone".
279 * @return A string describing the component.
282 public final String toString() {
284 return getComponentName();
290 public final void printStructure() {
291 System.out.println("Rocket structure from '" + this.toString() + "':");
295 private void printStructure(int level) {
298 for (int i = 0; i < level; i++) {
301 s += this.toString() + " (" + this.getComponentName() + ")";
302 System.out.println(s);
304 for (RocketComponent c : children) {
305 c.printStructure(level + 1);
311 * Make a deep copy of the rocket component tree structure from this component
312 * downwards for copying purposes. Each component in the copy will be assigned
313 * a new component ID, making it a safe copy. This method does not fire any events.
315 * @return A deep copy of the structure.
317 public final RocketComponent copy() {
318 RocketComponent clone = copyWithOriginalID();
320 Iterator<RocketComponent> iterator = clone.deepIterator(true);
321 while (iterator.hasNext()) {
322 iterator.next().newID();
330 * Make a deep copy of the rocket component tree structure from this component
331 * downwards while maintaining the component ID's. The purpose of this method is
332 * to allow copies to be created with the original ID's for the purpose of the
333 * undo/redo mechanism. This method should not be used for other purposes,
334 * such as copy/paste. This method does not fire any events.
336 * This method must be overridden by any component that refers to mutable objects,
337 * or if some fields should not be copied. This should be performed by
338 * <code>RocketComponent c = super.copyWithOriginalID();</code> and then cloning/modifying
339 * the appropriate fields.
341 * This is not performed as serializing/deserializing for performance reasons.
343 * @return A deep copy of the structure.
345 protected RocketComponent copyWithOriginalID() {
347 RocketComponent clone;
349 clone = (RocketComponent) this.clone();
350 } catch (CloneNotSupportedException e) {
351 throw new BugException("CloneNotSupportedException encountered, " +
355 // Reset all parent/child information
357 clone.children = new ArrayList<RocketComponent>();
359 // Add copied children to the structure without firing events.
360 for (RocketComponent child : this.children) {
361 RocketComponent childCopy = child.copyWithOriginalID();
362 // Don't use add method since it fires events
363 clone.children.add(childCopy);
364 childCopy.parent = clone;
371 ////////////// Methods that may not be overridden ////////////
375 ////////// Common parameter setting/getting //////////
378 * Return the color of the object to use in 2D figures, or <code>null</code>
379 * to use the default color.
381 public final Color getColor() {
386 * Set the color of the object to use in 2D figures.
388 public final void setColor(Color c) {
389 if ((color == null && c == null) ||
390 (color != null && color.equals(c)))
395 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
399 public final LineStyle getLineStyle() {
403 public final void setLineStyle(LineStyle style) {
404 if (this.lineStyle == style)
407 this.lineStyle = style;
408 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
415 * Get the current override mass. The mass is not necessarily in use
418 * @return the override mass
420 public final double getOverrideMass() {
425 * Set the current override mass. The mass is not set to use by this
428 * @param m the override mass
430 public final void setOverrideMass(double m) {
431 if (MathUtil.equals(m, overrideMass))
434 overrideMass = Math.max(m, 0);
436 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
440 * Return whether mass override is active for this component. This does NOT
441 * take into account whether a parent component is overriding the mass.
443 * @return whether the mass is overridden
445 public final boolean isMassOverridden() {
446 return massOverriden;
450 * Set whether the mass is currently overridden.
452 * @param o whether the mass is overridden
454 public final void setMassOverridden(boolean o) {
455 if (massOverriden == o) {
460 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
468 * Return the current override CG. The CG is not necessarily overridden.
470 * @return the override CG
472 public final Coordinate getOverrideCG() {
473 return getComponentCG().setX(overrideCGX);
477 * Return the x-coordinate of the current override CG.
479 * @return the x-coordinate of the override CG.
481 public final double getOverrideCGX() {
486 * Set the current override CG to (x,0,0).
488 * @param x the x-coordinate of the override CG to set.
490 public final void setOverrideCGX(double x) {
491 if (MathUtil.equals(overrideCGX, x))
494 this.overrideCGX = x;
495 if (isCGOverridden())
496 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
498 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
502 * Return whether the CG is currently overridden.
504 * @return whether the CG is overridden
506 public final boolean isCGOverridden() {
511 * Set whether the CG is currently overridden.
513 * @param o whether the CG is overridden
515 public final void setCGOverridden(boolean o) {
516 if (cgOverriden == o) {
521 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
527 * Return whether the mass and/or CG override overrides all subcomponent values
528 * as well. The default implementation is a normal getter/setter implementation,
529 * however, subclasses are allowed to override this behavior if some subclass
530 * always or never overrides subcomponents. In this case the subclass should
531 * also override {@link #isOverrideSubcomponentsEnabled()} to return
532 * <code>false</code>.
534 * @return whether the current mass and/or CG override overrides subcomponents as well.
536 public boolean getOverrideSubcomponents() {
537 return overrideSubcomponents;
542 * Set whether the mass and/or CG override overrides all subcomponent values
543 * as well. See {@link #getOverrideSubcomponents()} for details.
545 * @param override whether the mass and/or CG override overrides all subcomponent.
547 public void setOverrideSubcomponents(boolean override) {
548 if (overrideSubcomponents == override) {
552 overrideSubcomponents = override;
553 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
557 * Return whether the option to override all subcomponents is enabled or not.
558 * The default implementation returns <code>false</code> if neither mass nor
559 * CG is overridden, <code>true</code> otherwise.
561 * This method may be overridden if the setting of overriding subcomponents
564 * @return whether the option to override subcomponents is currently enabled.
566 public boolean isOverrideSubcomponentsEnabled() {
567 return isCGOverridden() || isMassOverridden();
574 * Get the user-defined name of the component.
576 public final String getName() {
581 * Set the user-defined name of the component. If name==null, sets the name to
582 * the default name, currently the component name.
584 public final void setName(String name) {
585 if (this.name.equals(name)) {
589 if (name == null || name.matches("^\\s*$"))
590 this.name = getComponentName();
593 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
598 * Return the comment of the component. The component may contain multiple lines
599 * using \n as a newline separator.
601 * @return the comment of the component.
603 public final String getComment() {
608 * Set the comment of the component.
610 * @param comment the comment of the component.
612 public final void setComment(String comment) {
613 if (this.comment.equals(comment))
619 this.comment = comment;
620 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
626 * Returns the unique ID of the component.
628 * @return the ID of the component.
630 public final String getID() {
635 * Generate a new ID for this component.
637 private final void newID() {
638 this.id = UniqueID.uuid();
645 * Get the characteristic length of the component, for example the length of a body tube
646 * of the length of the root chord of a fin. This is used in positioning the component
647 * relative to its parent.
649 * If the length of a component is settable, the class must define the setter method
652 public final double getLength() {
657 * Get the positioning of the component relative to its parent component.
658 * This is one of the enums of {@link Position}. A setter method is not provided,
659 * but can be provided by a subclass.
661 public final Position getRelativePosition() {
662 return relativePosition;
667 * Set the positioning of the component relative to its parent component.
668 * The actual position of the component is maintained to the best ability.
670 * The default implementation is of protected visibility, since many components
671 * do not support setting the relative position. A component that does support
672 * it should override this with a public method that simply calls this
673 * supermethod AND fire a suitable ComponentChangeEvent.
675 * @param position the relative positioning.
677 protected void setRelativePosition(RocketComponent.Position position) {
678 if (this.relativePosition == position)
682 // Update position so as not to move the component
683 if (this.parent != null) {
684 double thisPos = this.toRelative(Coordinate.NUL, this.parent)[0].x;
688 this.position = this.toAbsolute(Coordinate.NUL)[0].x;
692 this.position = thisPos;
696 this.position = thisPos - (this.parent.length - this.length) / 2;
700 this.position = thisPos - (this.parent.length - this.length);
704 throw new BugException("Unknown position type: " + position);
708 this.relativePosition = position;
709 fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE);
716 * Get the position value of the component. The exact meaning of the value is
717 * dependent on the current relative positioning.
719 * @return the positional value.
721 public final double getPositionValue() {
727 * Set the position value of the component. The exact meaning of the value
728 * depends on the current relative positioning.
730 * The default implementation is of protected visibility, since many components
731 * do not support setting the relative position. A component that does support
732 * it should override this with a public method that simply calls this
733 * supermethod AND fire a suitable ComponentChangeEvent.
735 * @param value the position value of the component.
737 public void setPositionValue(double value) {
738 if (MathUtil.equals(this.position, value))
741 this.position = value;
746 /////////// Coordinate changes ///////////
749 * Returns coordinate c in absolute coordinates. Equivalent to toComponent(c,null).
751 public Coordinate[] toAbsolute(Coordinate c) {
753 return toRelative(c, null);
758 * Return coordinate <code>c</code> described in the coordinate system of
759 * <code>dest</code>. If <code>dest</code> is <code>null</code> returns
760 * absolute coordinates.
762 * This method returns an array of coordinates, each of which represents a
763 * position of the coordinate in clustered cases. The array is guaranteed
764 * to contain at least one element.
766 * The current implementation does not support rotating components.
768 * @param c Coordinate in the component's coordinate system.
769 * @param dest Destination component coordinate system.
770 * @return an array of coordinates describing <code>c</code> in coordinates
771 * relative to <code>dest</code>.
773 public final Coordinate[] toRelative(Coordinate c, RocketComponent dest) {
775 double absoluteX = Double.NaN;
776 RocketComponent search = dest;
777 Coordinate[] array = new Coordinate[1];
780 RocketComponent component = this;
781 while ((component != search) && (component.parent != null)) {
783 array = component.shiftCoordinates(array);
785 switch (component.relativePosition) {
787 for (int i = 0; i < array.length; i++) {
788 array[i] = array[i].add(component.position, 0, 0);
793 for (int i = 0; i < array.length; i++) {
794 array[i] = array[i].add(component.position +
795 (component.parent.length - component.length) / 2, 0, 0);
800 for (int i = 0; i < array.length; i++) {
801 array[i] = array[i].add(component.position +
802 (component.parent.length - component.length), 0, 0);
807 // Add length of all previous brother-components with POSITION_RELATIVE_AFTER
808 int index = component.parent.children.indexOf(component);
810 for (index--; index >= 0; index--) {
811 RocketComponent comp = component.parent.children.get(index);
812 double length = comp.getTotalLength();
813 for (int i = 0; i < array.length; i++) {
814 array[i] = array[i].add(length, 0, 0);
817 for (int i = 0; i < array.length; i++) {
818 array[i] = array[i].add(component.position + component.parent.length, 0, 0);
823 search = null; // Requires back-search if dest!=null
824 if (Double.isNaN(absoluteX)) {
825 absoluteX = component.position;
830 throw new BugException("Unknown relative positioning type of component" +
831 component + ": " + component.relativePosition);
834 component = component.parent; // parent != null
837 if (!Double.isNaN(absoluteX)) {
838 for (int i = 0; i < array.length; i++) {
839 array[i] = array[i].setX(absoluteX + c.x);
843 // Check whether destination has been found or whether to backtrack
844 // TODO: LOW: Backtracking into clustered components uses only one component
845 if ((dest != null) && (component != dest)) {
846 Coordinate[] origin = dest.toAbsolute(Coordinate.NUL);
847 for (int i = 0; i < array.length; i++) {
848 array[i] = array[i].sub(origin[0]);
857 * Recursively sum the lengths of all subcomponents that have position
860 * @return Sum of the lengths.
862 private final double getTotalLength() {
865 if (relativePosition == Position.AFTER)
867 for (int i = 0; i < children.size(); i++)
868 l += children.get(i).getTotalLength();
874 /////////// Total mass and CG calculation ////////////
877 * Return the (possibly overridden) mass of component.
879 * @return The mass of the component or the given override mass.
881 public final double getMass() {
884 return getComponentMass();
888 * Return the (possibly overridden) center of gravity and mass.
890 * Returns the CG with the weight of the coordinate set to the weight of the component.
891 * Both CG and mass may be separately overridden.
893 * @return The CG of the component or the given override CG.
895 public final Coordinate getCG() {
898 return getOverrideCG().setWeight(getMass());
901 return getComponentCG().setWeight(getMass());
903 return getComponentCG();
908 * Return the longitudal (around the y- or z-axis) moment of inertia of this component.
909 * The moment of inertia is scaled in reference to the (possibly overridden) mass
910 * and is relative to the non-overridden CG.
912 * @return the longitudal moment of inertia of this component.
914 public final double getLongitudalInertia() {
916 return getLongitudalUnitInertia() * getMass();
920 * Return the rotational (around the y- or z-axis) moment of inertia of this component.
921 * The moment of inertia is scaled in reference to the (possibly overridden) mass
922 * and is relative to the non-overridden CG.
924 * @return the rotational moment of inertia of this component.
926 public final double getRotationalInertia() {
928 return getRotationalUnitInertia() * getMass();
933 /////////// Children handling ///////////
937 * Adds a child to the rocket component tree. The component is added to the end
938 * of the component's child list. This is a helper method that calls
939 * {@link #addChild(RocketComponent,int)}.
941 * @param component The component to add.
942 * @throws IllegalArgumentException if the component is already part of some
944 * @see #addChild(RocketComponent,int)
946 public final void addChild(RocketComponent component) {
948 addChild(component, children.size());
953 * Adds a child to the rocket component tree. The component is added to
954 * the given position of the component's child list.
956 * This method may be overridden to enforce more strict component addition rules.
957 * The tests should be performed first and then this method called.
959 * @param component The component to add.
960 * @param position Position to add component to.
961 * @throws IllegalArgumentException If the component is already part of
962 * some component tree.
964 public void addChild(RocketComponent component, int position) {
966 if (component.parent != null) {
967 throw new IllegalArgumentException("component " + component.getComponentName() +
968 " is already in a tree");
970 if (!isCompatible(component)) {
971 throw new IllegalStateException("Component " + component.getComponentName() +
972 " not currently compatible with component " + getComponentName());
975 children.add(position, component);
976 component.parent = this;
978 fireAddRemoveEvent(component);
983 * Removes a child from the rocket component tree.
985 * @param n remove the n'th child.
986 * @throws IndexOutOfBoundsException if n is out of bounds
988 public final void removeChild(int n) {
990 RocketComponent component = children.remove(n);
991 component.parent = null;
992 fireAddRemoveEvent(component);
996 * Removes a child from the rocket component tree. Does nothing if the component
997 * is not present as a child.
999 * @param component the component to remove
1000 * @return whether the component was a child
1002 public final boolean removeChild(RocketComponent component) {
1004 if (children.remove(component)) {
1005 component.parent = null;
1006 fireAddRemoveEvent(component);
1016 * Move a child to another position.
1018 * @param component the component to move
1019 * @param position the component's new position
1020 * @throws IllegalArgumentException If an illegal placement was attempted.
1022 public final void moveChild(RocketComponent component, int position) {
1024 if (children.remove(component)) {
1025 children.add(position, component);
1026 fireAddRemoveEvent(component);
1032 * Fires an AERODYNAMIC_CHANGE, MASS_CHANGE or OTHER_CHANGE event depending on the
1033 * type of component removed.
1035 private void fireAddRemoveEvent(RocketComponent component) {
1036 Iterator<RocketComponent> iter = component.deepIterator(true);
1037 int type = ComponentChangeEvent.TREE_CHANGE;
1038 while (iter.hasNext()) {
1039 RocketComponent c = iter.next();
1040 if (c.isAerodynamic())
1041 type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
1043 type |= ComponentChangeEvent.MASS_CHANGE;
1046 fireComponentChangeEvent(type);
1050 public final int getChildCount() {
1052 return children.size();
1055 public final RocketComponent getChild(int n) {
1057 return children.get(n);
1060 public final RocketComponent[] getChildren() {
1062 return children.toArray(new RocketComponent[0]);
1067 * Returns the position of the child in this components child list, or -1 if the
1068 * component is not a child of this component.
1070 * @param child The child to search for.
1071 * @return Position in the list or -1 if not found.
1073 public final int getChildPosition(RocketComponent child) {
1075 return children.indexOf(child);
1079 * Get the parent component of this component. Returns <code>null</code> if the component
1082 * @return The parent of this component or <code>null</code>.
1084 public final RocketComponent getParent() {
1090 * Get the root component of the component tree.
1092 * @return The root component of the component tree.
1094 public final RocketComponent getRoot() {
1096 RocketComponent gp = this;
1097 while (gp.parent != null)
1103 * Returns the root Rocket component of this component tree. Throws an
1104 * IllegalStateException if the root component is not a Rocket.
1106 * @return The root Rocket component of the component tree.
1107 * @throws IllegalStateException If the root component is not a Rocket.
1109 public final Rocket getRocket() {
1111 RocketComponent r = getRoot();
1112 if (r instanceof Rocket)
1114 throw new IllegalStateException("getRocket() called with root component "
1115 + r.getComponentName());
1120 * Return the Stage component that this component belongs to. Throws an
1121 * IllegalStateException if a Stage is not in the parentage of this component.
1123 * @return The Stage component this component belongs to.
1124 * @throws IllegalStateException if a Stage component is not in the parentage.
1126 public final Stage getStage() {
1128 RocketComponent c = this;
1130 if (c instanceof Stage)
1134 throw new IllegalStateException("getStage() called without Stage as a parent.");
1138 * Return the stage number of the stage this component belongs to. The stages
1139 * are numbered from zero upwards.
1141 * @return the stage number this component belongs to.
1143 public final int getStageNumber() {
1145 if (parent == null) {
1146 throw new IllegalArgumentException("getStageNumber() called for root component");
1149 RocketComponent stage = this;
1150 while (!(stage instanceof Stage)) {
1151 stage = stage.parent;
1152 if (stage == null || stage.parent == null) {
1153 throw new IllegalStateException("getStageNumber() could not find parent " +
1157 return stage.parent.getChildPosition(stage);
1162 * Find a component with the given ID. The component tree is searched from this component
1163 * down (including this component) for the ID and the corresponding component is returned,
1164 * or null if not found.
1166 * @param idToFind ID to search for.
1167 * @return The component with the ID, or null if not found.
1169 public final RocketComponent findComponent(String idToFind) {
1171 Iterator<RocketComponent> iter = this.deepIterator(true);
1172 while (iter.hasNext()) {
1173 RocketComponent c = iter.next();
1174 if (c.getID().equals(idToFind))
1181 public final RocketComponent getPreviousComponent() {
1185 int pos = parent.getChildPosition(this);
1187 StringBuffer sb = new StringBuffer();
1188 sb.append("Inconsistent internal state: ");
1189 sb.append("this=").append(this).append('[')
1190 .append(System.identityHashCode(this)).append(']');
1191 sb.append(" parent.children=[");
1192 for (int i = 0; i < parent.children.size(); i++) {
1193 RocketComponent c = parent.children.get(i);
1194 sb.append(c).append('[').append(System.identityHashCode(c)).append(']');
1195 if (i < parent.children.size() - 1)
1199 throw new IllegalStateException(sb.toString());
1204 RocketComponent c = parent.getChild(pos - 1);
1205 while (c.getChildCount() > 0)
1206 c = c.getChild(c.getChildCount() - 1);
1210 public final RocketComponent getNextComponent() {
1212 if (getChildCount() > 0)
1215 RocketComponent current = this;
1216 RocketComponent parent = this.parent;
1218 while (parent != null) {
1219 int pos = parent.getChildPosition(current);
1220 if (pos < parent.getChildCount() - 1)
1221 return parent.getChild(pos + 1);
1224 parent = current.parent;
1230 /////////// Event handling //////////
1232 // Listener lists are provided by the root Rocket component,
1233 // a single listener list for the whole rocket.
1237 * Adds a ComponentChangeListener to the rocket tree. The listener is added to the root
1238 * component, which must be of type Rocket (which overrides this method). Events of all
1239 * subcomponents are sent to all listeners.
1241 * @throws IllegalStateException - if the root component is not a Rocket
1243 public void addComponentChangeListener(ComponentChangeListener l) {
1245 getRocket().addComponentChangeListener(l);
1249 * Removes a ComponentChangeListener from the rocket tree. The listener is removed from
1250 * the root component, which must be of type Rocket (which overrides this method).
1251 * Does nothing if the root component is not a Rocket. (The asymmetry is so
1252 * that listeners can always be removed just in case.)
1254 * @param l Listener to remove
1256 public void removeComponentChangeListener(ComponentChangeListener l) {
1257 if (parent != null) {
1258 getRoot().removeComponentChangeListener(l);
1264 * Adds a <code>ChangeListener</code> to the rocket tree. This is identical to
1265 * <code>addComponentChangeListener()</code> except that it uses a
1266 * <code>ChangeListener</code>. The same events are dispatched to the
1267 * <code>ChangeListener</code>, as <code>ComponentChangeEvent</code> is a subclass
1268 * of <code>ChangeEvent</code>.
1270 * @throws IllegalStateException - if the root component is not a <code>Rocket</code>
1272 public void addChangeListener(ChangeListener l) {
1274 getRocket().addChangeListener(l);
1278 * Removes a ChangeListener from the rocket tree. This is identical to
1279 * removeComponentChangeListener() except it uses a ChangeListener.
1280 * Does nothing if the root component is not a Rocket. (The asymmetry is so
1281 * that listeners can always be removed just in case.)
1283 * @param l Listener to remove
1285 public void removeChangeListener(ChangeListener l) {
1286 if (this.parent != null) {
1287 getRoot().removeChangeListener(l);
1293 * Fires a ComponentChangeEvent on the rocket structure. The call is passed to the
1294 * root component, which must be of type Rocket (which overrides this method).
1295 * Events of all subcomponents are sent to all listeners.
1297 * If the component tree root is not a Rocket, the event is ignored. This is the
1298 * case when constructing components not in any Rocket tree. In this case it
1299 * would be impossible for the component to have listeners in any case.
1301 * @param e Event to send
1303 protected void fireComponentChangeEvent(ComponentChangeEvent e) {
1305 if (parent == null) {
1306 /* Ignore if root invalid. */
1309 getRoot().fireComponentChangeEvent(e);
1314 * Fires a ComponentChangeEvent of the given type. The source of the event is set to
1317 * @param type Type of event
1318 * @see #fireComponentChangeEvent(ComponentChangeEvent)
1320 protected void fireComponentChangeEvent(int type) {
1321 fireComponentChangeEvent(new ComponentChangeEvent(this, type));
1326 * Checks whether this component has been invalidated and should no longer be used.
1327 * This is a safety check that in-place replaced components are no longer used.
1328 * All non-trivial methods (with the exception of methods simply getting a property)
1329 * should call this method before changing or computing anything.
1331 * @throws BugException if this component has been invalidated by {@link #copyFrom(RocketComponent)}.
1333 protected void checkState() {
1334 if (invalidated != null) {
1335 throw new BugException("This component has been invalidated. Cause is the point of invalidation.",
1341 /////////// Iterator implementation //////////
1344 * Private inner class to implement the Iterator.
1346 * This iterator is fail-fast if the root of the structure is a Rocket.
1348 private class RocketComponentIterator implements Iterator<RocketComponent> {
1349 // Stack holds iterators which still have some components left.
1350 private final Stack<Iterator<RocketComponent>> iteratorstack =
1351 new Stack<Iterator<RocketComponent>>();
1353 private final Rocket root;
1354 private final int treeModID;
1356 private final RocketComponent original;
1357 private boolean returnSelf = false;
1359 // Construct iterator with component's child's iterator, if it has elements
1360 public RocketComponentIterator(RocketComponent c, boolean returnSelf) {
1362 RocketComponent gp = c.getRoot();
1363 if (gp instanceof Rocket) {
1365 treeModID = root.getTreeModID();
1371 Iterator<RocketComponent> i = c.children.iterator();
1373 iteratorstack.push(i);
1376 this.returnSelf = returnSelf;
1379 public boolean hasNext() {
1384 return !iteratorstack.empty(); // Elements remain if stack is not empty
1387 public RocketComponent next() {
1388 Iterator<RocketComponent> i;
1393 // Return original component first
1399 // Peek first iterator from stack, throw exception if empty
1401 i = iteratorstack.peek();
1402 } catch (EmptyStackException e) {
1403 throw new NoSuchElementException("No further elements in " +
1404 "RocketComponent iterator");
1407 // Retrieve next component of the iterator, remove iterator from stack if empty
1408 RocketComponent c = i.next();
1410 iteratorstack.pop();
1412 // Add iterator of component children to stack if it has children
1413 i = c.children.iterator();
1415 iteratorstack.push(i);
1420 private void checkID() {
1422 if (root.getTreeModID() != treeModID) {
1423 throw new IllegalStateException("Rocket modified while being iterated");
1428 public void remove() {
1429 throw new UnsupportedOperationException("remove() not supported by " +
1430 "RocketComponent iterator");
1435 * Returns an iterator that iterates over all children and sub-children.
1437 * The iterator iterates through all children below this object, including itself if
1438 * returnSelf is true. The order of the iteration is not specified
1439 * (it may be specified in the future).
1441 * If an iterator iterating over only the direct children of the component is required,
1442 * use component.getChildren().iterator()
1444 * @param returnSelf boolean value specifying whether the component itself should be
1446 * @return An iterator for the children and sub-children.
1448 public final Iterator<RocketComponent> deepIterator(boolean returnSelf) {
1450 return new RocketComponentIterator(this, returnSelf);
1454 * Returns an iterator that iterates over all children and sub-children.
1456 * The iterator does NOT return the component itself. It is thus equivalent to
1457 * deepIterator(false).
1460 * @return An iterator for the children and sub-children.
1462 public final Iterator<RocketComponent> deepIterator() {
1464 return new RocketComponentIterator(this, false);
1469 * Return an iterator that iterates of the children of the component. The iterator
1470 * does NOT recurse to sub-children nor return itself.
1472 * @return An iterator for the children.
1474 public final Iterator<RocketComponent> iterator() {
1476 return Collections.unmodifiableList(children).iterator();
1483 * Compare component equality based on the ID of this component. Only the
1484 * ID and class type is used for a basis of comparison.
1487 public boolean equals(Object obj) {
1492 if (this.getClass() != obj.getClass())
1494 RocketComponent other = (RocketComponent) obj;
1495 return this.id.equals(other.id);
1501 public int hashCode() {
1502 return id.hashCode();
1507 //////////// Helper methods for subclasses
1513 * Helper method to add rotationally symmetric bounds at the specified coordinates.
1514 * The X-axis value is <code>x</code> and the radius at the specified position is
1517 protected static final void addBound(Collection<Coordinate> bounds, double x, double r) {
1518 bounds.add(new Coordinate(x, -r, -r));
1519 bounds.add(new Coordinate(x, r, -r));
1520 bounds.add(new Coordinate(x, r, r));
1521 bounds.add(new Coordinate(x, -r, r));
1525 protected static final Coordinate ringCG(double outerRadius, double innerRadius,
1526 double x1, double x2, double density) {
1527 return new Coordinate((x1 + x2) / 2, 0, 0,
1528 ringMass(outerRadius, innerRadius, x2 - x1, density));
1531 protected static final double ringMass(double outerRadius, double innerRadius,
1532 double length, double density) {
1533 return Math.PI * (MathUtil.pow2(outerRadius) - MathUtil.pow2(innerRadius)) *
1537 protected static final double ringLongitudalUnitInertia(double outerRadius,
1538 double innerRadius, double length) {
1539 // 1/12 * (3 * (r1^2 + r2^2) + h^2)
1540 return (3 * (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) + MathUtil.pow2(length)) / 12;
1543 protected static final double ringRotationalUnitInertia(double outerRadius,
1544 double innerRadius) {
1545 // 1/2 * (r1^2 + r2^2)
1546 return (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) / 2;
1555 * Loads the RocketComponent fields from the given component. This method is meant
1556 * for in-place replacement of a component. It is used with the undo/redo
1557 * mechanism and when converting a finset into a freeform fin set.
1558 * This component must not have a parent, otherwise this method will fail.
1560 * The fields are copied by reference, and the supplied component must not be used
1561 * after the call, as it is in an undefined state. This is enforced by invalidating
1562 * the source component.
1564 * TODO: MEDIUM: Make general to copy all private/protected fields...
1566 protected void copyFrom(RocketComponent src) {
1569 if (this.parent != null) {
1570 throw new UnsupportedOperationException("copyFrom called for non-root component "
1574 // Set parents and children
1575 this.children = src.children;
1576 src.children = new ArrayList<RocketComponent>();
1578 for (RocketComponent c : this.children) {
1582 // Set all parameters
1583 this.length = src.length;
1584 this.relativePosition = src.relativePosition;
1585 this.position = src.position;
1586 this.color = src.color;
1587 this.lineStyle = src.lineStyle;
1588 this.overrideMass = src.overrideMass;
1589 this.massOverriden = src.massOverriden;
1590 this.overrideCGX = src.overrideCGX;
1591 this.cgOverriden = src.cgOverriden;
1592 this.overrideSubcomponents = src.overrideSubcomponents;
1593 this.name = src.name;
1594 this.comment = src.comment;
1597 src.invalidated = new TraceException();