1 package net.sf.openrocket.rocketcomponent;
3 import java.util.ArrayDeque;
4 import java.util.Collection;
5 import java.util.Deque;
6 import java.util.EventListener;
7 import java.util.Iterator;
9 import java.util.NoSuchElementException;
11 import net.sf.openrocket.l10n.Translator;
12 import net.sf.openrocket.logging.LogHelper;
13 import net.sf.openrocket.preset.ComponentPreset;
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.Color;
19 import net.sf.openrocket.util.Coordinate;
20 import net.sf.openrocket.util.Invalidator;
21 import net.sf.openrocket.util.LineStyle;
22 import net.sf.openrocket.util.MathUtil;
23 import net.sf.openrocket.util.SafetyMutex;
24 import net.sf.openrocket.util.UniqueID;
27 public abstract class RocketComponent implements ChangeSource, Cloneable, Iterable<RocketComponent> {
28 private static final LogHelper log = Application.getLogger();
29 private static final Translator trans = Application.getTranslator();
32 * Text is suitable to the form
33 * Position relative to: <title>
35 public enum Position {
36 /** Position relative to the top of the parent component. */
37 //// Top of the parent component
38 TOP(trans.get("RocketComponent.Position.TOP")),
39 /** Position relative to the middle of the parent component. */
40 //// Middle of the parent component
41 MIDDLE(trans.get("RocketComponent.Position.MIDDLE")),
42 /** Position relative to the bottom of the parent component. */
43 //// Bottom of the parent component
44 BOTTOM(trans.get("RocketComponent.Position.BOTTOM")),
45 /** Position after the parent component (for body components). */
46 //// After the parent component
47 AFTER(trans.get("RocketComponent.Position.AFTER")),
48 /** Specify an absolute X-coordinate position. */
49 //// Tip of the nose cone
50 ABSOLUTE(trans.get("RocketComponent.Position.ABSOLUTE"));
54 Position(String title) {
59 public String toString() {
65 * A safety mutex that can be used to prevent concurrent access to this component.
67 protected SafetyMutex mutex = SafetyMutex.newInstance();
69 //////// Parent/child trees
71 * Parent component of the current component, or null if none exists.
73 private RocketComponent parent = null;
76 * List of child components of this component.
78 private ArrayList<RocketComponent> children = new ArrayList<RocketComponent>();
81 //////// Parameters common to all components:
84 * Characteristic length of the component. This is used in calculating the coordinate
85 * transformations and positions of other components in reference to this component.
86 * This may and should be used as the "true" length of the component, where applicable.
87 * By default it is zero, i.e. no translation.
89 protected double length = 0;
92 * Positioning of this component relative to the parent component.
94 protected Position relativePosition;
97 * Offset of the position of this component relative to the normal position given by
98 * relativePosition. By default zero, i.e. no position change.
100 protected double position = 0;
103 // Color of the component, null means to use the default color
104 private Color color = null;
105 private LineStyle lineStyle = null;
109 private double overrideMass = 0;
110 private boolean massOverriden = false;
111 private double overrideCGX = 0;
112 private boolean cgOverriden = false;
114 private boolean overrideSubcomponents = false;
117 // User-given name of the component
118 private String name = null;
120 // User-specified comment
121 private String comment = "";
123 // Unique ID of the component
124 private String id = null;
126 // Preset component this component is based upon
127 private ComponentPreset presetComponent = null;
131 * Used to invalidate the component after calling {@link #copyFrom(RocketComponent)}.
133 private Invalidator invalidator = new Invalidator(this);
136 //// NOTE !!! All fields must be copied in the method copyFrom()! ////
141 * Default constructor. Sets the name of the component to the component's static name
142 * and the relative position of the component.
144 public RocketComponent(Position relativePosition) {
145 // These must not fire any events, due to Rocket undo system initialization
146 this.name = getComponentName();
147 this.relativePosition = relativePosition;
151 //////////// Methods that must be implemented ////////////
155 * Static component name. The name may not vary of the parameters, it must be static.
157 public abstract String getComponentName(); // Static component type name
160 * Return the component mass (regardless of mass overriding).
162 public abstract double getComponentMass(); // Mass of non-overridden component
165 * Return the component CG and mass (regardless of CG or mass overriding).
167 public abstract Coordinate getComponentCG(); // CG of non-overridden component
171 * Return the longitudinal (around the y- or z-axis) unitary moment of inertia.
172 * The unitary moment of inertia is the moment of inertia with the assumption that
173 * the mass of the component is one kilogram. The inertia is measured in
174 * respect to the non-overridden CG.
176 * @return the longitudinal unitary moment of inertia of this component.
178 public abstract double getLongitudinalUnitInertia();
182 * Return the rotational (around the x-axis) unitary moment of inertia.
183 * The unitary moment of inertia is the moment of inertia with the assumption that
184 * the mass of the component is one kilogram. The inertia is measured in
185 * respect to the non-overridden CG.
187 * @return the rotational unitary moment of inertia of this component.
189 public abstract double getRotationalUnitInertia();
193 * Test whether this component allows any children components. This method must
194 * return true if and only if {@link #isCompatible(Class)} returns true for any
195 * rocket component class.
197 * @return <code>true</code> if children can be attached to this component, <code>false</code> otherwise.
199 public abstract boolean allowsChildren();
202 * Test whether the given component type can be added to this component. This type safety
203 * is enforced by the <code>addChild()</code> methods. The return value of this method
204 * may change to reflect the current state of this component (e.g. two components of some
205 * type cannot be placed as children).
207 * @param type The RocketComponent class type to add.
208 * @return Whether such a component can be added.
210 public abstract boolean isCompatible(Class<? extends RocketComponent> type);
213 /* Non-abstract helper method */
215 * Test whether the given component can be added to this component. This is equivalent
216 * to calling <code>isCompatible(c.getClass())</code>.
218 * @param c Component to test.
219 * @return Whether the component can be added.
220 * @see #isCompatible(Class)
222 public final boolean isCompatible(RocketComponent c) {
224 return isCompatible(c.getClass());
230 * Return a collection of bounding coordinates. The coordinates must be such that
231 * the component is fully enclosed in their convex hull.
233 * @return a collection of coordinates that bound the component.
235 public abstract Collection<Coordinate> getComponentBounds();
238 * Return true if the component may have an aerodynamic effect on the rocket.
240 public abstract boolean isAerodynamic();
243 * Return true if the component may have an effect on the rocket's mass.
245 public abstract boolean isMassive();
251 //////////// Methods that may be overridden ////////////
255 * Shift the coordinates in the array corresponding to radial movement. A component
256 * that has a radial position must shift the coordinates in this array suitably.
257 * If the component is clustered, then a new array must be returned with a
258 * coordinate for each cluster.
260 * The default implementation simply returns the array, and thus produces no shift.
262 * @param c an array of coordinates to shift.
263 * @return an array of shifted coordinates. The method may modify the contents
264 * of the passed array and return the array itself.
266 public Coordinate[] shiftCoordinates(Coordinate[] c) {
273 * Called when any component in the tree fires a ComponentChangeEvent. This is by
274 * default a no-op, but subclasses may override this method to e.g. invalidate
275 * cached data. The overriding method *must* call
276 * <code>super.componentChanged(e)</code> at some point.
278 * @param e The event fired
280 protected void componentChanged(ComponentChangeEvent e) {
289 * Return the user-provided name of the component, or the component base
290 * name if the user-provided name is empty. This can be used in the UI.
292 * @return A string describing the component.
295 public final String toString() {
297 if (name.length() == 0)
298 return getComponentName();
305 * Create a string describing the basic component structure from this component downwards.
306 * @return a string containing the rocket structure
308 public final String toDebugString() {
309 mutex.lock("toDebugString");
311 StringBuilder sb = new StringBuilder();
313 return sb.toString();
315 mutex.unlock("toDebugString");
319 private void toDebugString(StringBuilder sb) {
320 sb.append(this.getClass().getSimpleName()).append('@').append(System.identityHashCode(this));
321 sb.append("[\"").append(this.getName()).append('"');
322 for (RocketComponent c : this.children) {
331 * Make a deep copy of the rocket component tree structure from this component
332 * downwards for copying purposes. Each component in the copy will be assigned
333 * a new component ID, making it a safe copy. This method does not fire any events.
335 * @return A deep copy of the structure.
337 public final RocketComponent copy() {
338 RocketComponent clone = copyWithOriginalID();
340 Iterator<RocketComponent> iterator = clone.iterator(true);
341 while (iterator.hasNext()) {
342 iterator.next().newID();
350 * Make a deep copy of the rocket component tree structure from this component
351 * downwards while maintaining the component ID's. The purpose of this method is
352 * to allow copies to be created with the original ID's for the purpose of the
353 * undo/redo mechanism. This method should not be used for other purposes,
354 * such as copy/paste. This method does not fire any events.
356 * This method must be overridden by any component that refers to mutable objects,
357 * or if some fields should not be copied. This should be performed by
358 * <code>RocketComponent c = super.copyWithOriginalID();</code> and then cloning/modifying
359 * the appropriate fields.
361 * This is not performed as serializing/deserializing for performance reasons.
363 * @return A deep copy of the structure.
365 protected RocketComponent copyWithOriginalID() {
366 mutex.lock("copyWithOriginalID");
369 RocketComponent clone;
371 clone = (RocketComponent) this.clone();
372 } catch (CloneNotSupportedException e) {
373 throw new BugException("CloneNotSupportedException encountered, report a bug!", e);
377 clone.mutex = SafetyMutex.newInstance();
379 // Reset all parent/child information
381 clone.children = new ArrayList<RocketComponent>();
383 // Add copied children to the structure without firing events.
384 for (RocketComponent child : this.children) {
385 RocketComponent childCopy = child.copyWithOriginalID();
386 // Don't use add method since it fires events
387 clone.children.add(childCopy);
388 childCopy.parent = clone;
391 this.checkComponentStructure();
392 clone.checkComponentStructure();
396 mutex.unlock("copyWithOriginalID");
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 * Return the preset component that this component is based upon.
669 * @return the preset component, or <code>null</code> if this is not based on a preset.
671 public final ComponentPreset getPresetComponent() {
672 return presetComponent;
676 * Return the most compatible preset type for this component.
677 * This method should be overridden by components which have presets
679 * @return the most compatible ComponentPreset.Type or <code>null</code> if no presets are compatible.
681 public ComponentPreset.Type getPresetType() {
686 * Set the preset component this component is based upon and load all of the
689 * @param preset the preset component to load, or <code>null</code> to clear the preset.
691 public final void loadPreset(ComponentPreset preset) {
692 if (presetComponent == preset) {
696 if (preset == null) {
701 // TODO - do we need to this compatibility check?
703 if (preset.getComponentClass() != this.getClass()) {
704 throw new IllegalArgumentException("Attempting to load preset of type " + preset.getComponentClass()
705 + " into component of type " + this.getClass());
709 RocketComponent root = getRoot();
711 if (root instanceof Rocket) {
712 rocket = (Rocket) root;
718 if (rocket != null) {
722 loadFromPreset(preset);
724 this.presetComponent = preset;
725 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
728 if (rocket != null) {
736 * Load component properties from the specified preset. The preset is guaranteed
737 * to be of the correct type.
739 * This method should fire the appropriate events related to the changes. The rocket
740 * is frozen by the caller, so the events will be automatically combined.
742 * This method must FIRST perform the preset loading and THEN call super.loadFromPreset().
743 * This is because mass setting requires the dimensions to be set beforehand.
745 * @param preset the preset to load from
747 protected void loadFromPreset(ComponentPreset preset) {
748 if ( preset.has(ComponentPreset.LENGTH) ) {
749 this.length = preset.get(ComponentPreset.LENGTH);
755 * Clear the current component preset. This does not affect the component properties
758 public final void clearPreset() {
759 if (presetComponent == null)
761 presetComponent = null;
762 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
768 * Returns the unique ID of the component.
770 * @return the ID of the component.
772 public final String getID() {
777 * Generate a new ID for this component.
779 private final void newID() {
781 this.id = UniqueID.uuid();
788 * Get the characteristic length of the component, for example the length of a body tube
789 * of the length of the root chord of a fin. This is used in positioning the component
790 * relative to its parent.
792 * If the length of a component is settable, the class must define the setter method
795 public final double getLength() {
801 * Get the positioning of the component relative to its parent component.
802 * This is one of the enums of {@link Position}. A setter method is not provided,
803 * but can be provided by a subclass.
805 public final Position getRelativePosition() {
807 return relativePosition;
812 * Set the positioning of the component relative to its parent component.
813 * The actual position of the component is maintained to the best ability.
815 * The default implementation is of protected visibility, since many components
816 * do not support setting the relative position. A component that does support
817 * it should override this with a public method that simply calls this
818 * supermethod AND fire a suitable ComponentChangeEvent.
820 * @param position the relative positioning.
822 protected void setRelativePosition(RocketComponent.Position position) {
823 if (this.relativePosition == position)
827 // Update position so as not to move the component
828 if (this.parent != null) {
829 double thisPos = this.toRelative(Coordinate.NUL, this.parent)[0].x;
833 this.position = this.toAbsolute(Coordinate.NUL)[0].x;
837 this.position = thisPos;
841 this.position = thisPos - (this.parent.length - this.length) / 2;
845 this.position = thisPos - (this.parent.length - this.length);
849 throw new BugException("Unknown position type: " + position);
853 this.relativePosition = position;
854 fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE);
859 * Determine position relative to given position argument. Note: This is a side-effect free method. No state
862 * @param thePosition the relative position to be used as the basis for the computation
863 * @param relativeTo the position is computed relative the the given component
865 * @return double position of the component relative to the parent, with respect to <code>position</code>
867 public double asPositionValue(Position thePosition, RocketComponent relativeTo) {
868 double result = this.position;
869 if (relativeTo != null) {
870 double thisPos = this.toRelative(Coordinate.NUL, relativeTo)[0].x;
872 switch (thePosition) {
874 result = this.toAbsolute(Coordinate.NUL)[0].x;
880 result = thisPos - (relativeTo.length - this.length) / 2;
883 result = thisPos - (relativeTo.length - this.length);
886 throw new BugException("Unknown position type: " + thePosition);
893 * Get the position value of the component. The exact meaning of the value is
894 * dependent on the current relative positioning.
896 * @return the positional value.
898 public final double getPositionValue() {
905 * Set the position value of the component. The exact meaning of the value
906 * depends on the current relative positioning.
908 * The default implementation is of protected visibility, since many components
909 * do not support setting the relative position. A component that does support
910 * it should override this with a public method that simply calls this
911 * supermethod AND fire a suitable ComponentChangeEvent.
913 * @param value the position value of the component.
915 public void setPositionValue(double value) {
916 if (MathUtil.equals(this.position, value))
919 this.position = value;
924 /////////// Coordinate changes ///////////
927 * Returns coordinate c in absolute coordinates. Equivalent to toComponent(c,null).
929 public Coordinate[] toAbsolute(Coordinate c) {
931 return toRelative(c, null);
936 * Return coordinate <code>c</code> described in the coordinate system of
937 * <code>dest</code>. If <code>dest</code> is <code>null</code> returns
938 * absolute coordinates.
940 * This method returns an array of coordinates, each of which represents a
941 * position of the coordinate in clustered cases. The array is guaranteed
942 * to contain at least one element.
944 * The current implementation does not support rotating components.
946 * @param c Coordinate in the component's coordinate system.
947 * @param dest Destination component coordinate system.
948 * @return an array of coordinates describing <code>c</code> in coordinates
949 * relative to <code>dest</code>.
951 public final Coordinate[] toRelative(Coordinate c, RocketComponent dest) {
953 mutex.lock("toRelative");
955 double absoluteX = Double.NaN;
956 RocketComponent search = dest;
957 Coordinate[] array = new Coordinate[1];
960 RocketComponent component = this;
961 while ((component != search) && (component.parent != null)) {
963 array = component.shiftCoordinates(array);
965 switch (component.relativePosition) {
967 for (int i = 0; i < array.length; i++) {
968 array[i] = array[i].add(component.position, 0, 0);
973 for (int i = 0; i < array.length; i++) {
974 array[i] = array[i].add(component.position +
975 (component.parent.length - component.length) / 2, 0, 0);
980 for (int i = 0; i < array.length; i++) {
981 array[i] = array[i].add(component.position +
982 (component.parent.length - component.length), 0, 0);
987 // Add length of all previous brother-components with POSITION_RELATIVE_AFTER
988 int index = component.parent.children.indexOf(component);
990 for (index--; index >= 0; index--) {
991 RocketComponent comp = component.parent.children.get(index);
992 double componentLength = comp.getTotalLength();
993 for (int i = 0; i < array.length; i++) {
994 array[i] = array[i].add(componentLength, 0, 0);
997 for (int i = 0; i < array.length; i++) {
998 array[i] = array[i].add(component.position + component.parent.length, 0, 0);
1003 search = null; // Requires back-search if dest!=null
1004 if (Double.isNaN(absoluteX)) {
1005 absoluteX = component.position;
1010 throw new BugException("Unknown relative positioning type of component" +
1011 component + ": " + component.relativePosition);
1014 component = component.parent; // parent != null
1017 if (!Double.isNaN(absoluteX)) {
1018 for (int i = 0; i < array.length; i++) {
1019 array[i] = array[i].setX(absoluteX + c.x);
1023 // Check whether destination has been found or whether to backtrack
1024 // TODO: LOW: Backtracking into clustered components uses only one component
1025 if ((dest != null) && (component != dest)) {
1026 Coordinate[] origin = dest.toAbsolute(Coordinate.NUL);
1027 for (int i = 0; i < array.length; i++) {
1028 array[i] = array[i].sub(origin[0]);
1034 mutex.unlock("toRelative");
1040 * Recursively sum the lengths of all subcomponents that have position
1043 * @return Sum of the lengths.
1045 private final double getTotalLength() {
1047 this.checkComponentStructure();
1048 mutex.lock("getTotalLength");
1051 if (relativePosition == Position.AFTER)
1053 for (int i = 0; i < children.size(); i++)
1054 l += children.get(i).getTotalLength();
1057 mutex.unlock("getTotalLength");
1063 /////////// Total mass and CG calculation ////////////
1066 * Return the (possibly overridden) mass of component.
1068 * @return The mass of the component or the given override mass.
1070 public final double getMass() {
1073 return overrideMass;
1074 return getComponentMass();
1078 * Return the (possibly overridden) center of gravity and mass.
1080 * Returns the CG with the weight of the coordinate set to the weight of the component.
1081 * Both CG and mass may be separately overridden.
1083 * @return The CG of the component or the given override CG.
1085 public final Coordinate getCG() {
1088 return getOverrideCG().setWeight(getMass());
1091 return getComponentCG().setWeight(getMass());
1093 return getComponentCG();
1098 * Return the longitudinal (around the y- or z-axis) moment of inertia of this component.
1099 * The moment of inertia is scaled in reference to the (possibly overridden) mass
1100 * and is relative to the non-overridden CG.
1102 * @return the longitudinal moment of inertia of this component.
1104 public final double getLongitudinalInertia() {
1106 return getLongitudinalUnitInertia() * getMass();
1110 * Return the rotational (around the y- or z-axis) moment of inertia of this component.
1111 * The moment of inertia is scaled in reference to the (possibly overridden) mass
1112 * and is relative to the non-overridden CG.
1114 * @return the rotational moment of inertia of this component.
1116 public final double getRotationalInertia() {
1118 return getRotationalUnitInertia() * getMass();
1123 /////////// Children handling ///////////
1127 * Adds a child to the rocket component tree. The component is added to the end
1128 * of the component's child list. This is a helper method that calls
1129 * {@link #addChild(RocketComponent,int)}.
1131 * @param component The component to add.
1132 * @throws IllegalArgumentException if the component is already part of some
1134 * @see #addChild(RocketComponent,int)
1136 public final void addChild(RocketComponent component) {
1138 addChild(component, children.size());
1143 * Adds a child to the rocket component tree. The component is added to
1144 * the given position of the component's child list.
1146 * This method may be overridden to enforce more strict component addition rules.
1147 * The tests should be performed first and then this method called.
1149 * @param component The component to add.
1150 * @param index Position to add component to.
1151 * @throws IllegalArgumentException If the component is already part of
1152 * some component tree.
1154 public void addChild(RocketComponent component, int index) {
1157 if (component.parent != null) {
1158 throw new IllegalArgumentException("component " + component.getComponentName() +
1159 " is already in a tree");
1162 // Ensure that the no loops are created in component tree [A -> X -> Y -> B, B.addChild(A)]
1163 if (this.getRoot().equals(component)) {
1164 throw new IllegalStateException("Component " + component.getComponentName() +
1165 " is a parent of " + this.getComponentName() + ", attempting to create cycle in tree.");
1168 if (!isCompatible(component)) {
1169 throw new IllegalStateException("Component " + component.getComponentName() +
1170 " not currently compatible with component " + getComponentName());
1173 children.add(index, component);
1174 component.parent = this;
1176 this.checkComponentStructure();
1177 component.checkComponentStructure();
1179 fireAddRemoveEvent(component);
1183 * Removes a child from the rocket component tree.
1185 * @param n remove the n'th child.
1186 * @throws IndexOutOfBoundsException if n is out of bounds
1188 public final void removeChild(int n) {
1190 RocketComponent component = children.remove(n);
1191 component.parent = null;
1193 this.checkComponentStructure();
1194 component.checkComponentStructure();
1196 fireAddRemoveEvent(component);
1200 * Removes a child from the rocket component tree. Does nothing if the component
1201 * is not present as a child.
1203 * @param component the component to remove
1204 * @return whether the component was a child
1206 public final boolean removeChild(RocketComponent component) {
1209 component.checkComponentStructure();
1211 if (children.remove(component)) {
1212 component.parent = null;
1214 this.checkComponentStructure();
1215 component.checkComponentStructure();
1217 fireAddRemoveEvent(component);
1227 * Move a child to another position.
1229 * @param component the component to move
1230 * @param index the component's new position
1231 * @throws IllegalArgumentException If an illegal placement was attempted.
1233 public final void moveChild(RocketComponent component, int index) {
1235 if (children.remove(component)) {
1236 children.add(index, component);
1238 this.checkComponentStructure();
1239 component.checkComponentStructure();
1241 fireAddRemoveEvent(component);
1247 * Fires an AERODYNAMIC_CHANGE, MASS_CHANGE or OTHER_CHANGE event depending on the
1248 * type of component removed.
1250 private void fireAddRemoveEvent(RocketComponent component) {
1251 Iterator<RocketComponent> iter = component.iterator(true);
1252 int type = ComponentChangeEvent.TREE_CHANGE;
1253 while (iter.hasNext()) {
1254 RocketComponent c = iter.next();
1255 if (c.isAerodynamic())
1256 type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
1258 type |= ComponentChangeEvent.MASS_CHANGE;
1261 fireComponentChangeEvent(type);
1265 public final int getChildCount() {
1267 this.checkComponentStructure();
1268 return children.size();
1271 public final RocketComponent getChild(int n) {
1273 this.checkComponentStructure();
1274 return children.get(n);
1277 public final List<RocketComponent> getChildren() {
1279 this.checkComponentStructure();
1280 return children.clone();
1285 * Returns the position of the child in this components child list, or -1 if the
1286 * component is not a child of this component.
1288 * @param child The child to search for.
1289 * @return Position in the list or -1 if not found.
1291 public final int getChildPosition(RocketComponent child) {
1293 this.checkComponentStructure();
1294 return children.indexOf(child);
1298 * Get the parent component of this component. Returns <code>null</code> if the component
1301 * @return The parent of this component or <code>null</code>.
1303 public final RocketComponent getParent() {
1309 * Get the root component of the component tree.
1311 * @return The root component of the component tree.
1313 public final RocketComponent getRoot() {
1315 RocketComponent gp = this;
1316 while (gp.parent != null)
1322 * Returns the root Rocket component of this component tree. Throws an
1323 * IllegalStateException if the root component is not a Rocket.
1325 * @return The root Rocket component of the component tree.
1326 * @throws IllegalStateException If the root component is not a Rocket.
1328 public final Rocket getRocket() {
1330 RocketComponent r = getRoot();
1331 if (r instanceof Rocket)
1333 throw new IllegalStateException("getRocket() called with root component "
1334 + r.getComponentName());
1339 * Return the Stage component that this component belongs to. Throws an
1340 * IllegalStateException if a Stage is not in the parentage of this component.
1342 * @return The Stage component this component belongs to.
1343 * @throws IllegalStateException if a Stage component is not in the parentage.
1345 public final Stage getStage() {
1347 RocketComponent c = this;
1349 if (c instanceof Stage)
1353 throw new IllegalStateException("getStage() called without Stage as a parent.");
1357 * Return the stage number of the stage this component belongs to. The stages
1358 * are numbered from zero upwards.
1360 * @return the stage number this component belongs to.
1362 public final int getStageNumber() {
1364 if (parent == null) {
1365 throw new IllegalArgumentException("getStageNumber() called for root component");
1368 RocketComponent stage = this;
1369 while (!(stage instanceof Stage)) {
1370 stage = stage.parent;
1371 if (stage == null || stage.parent == null) {
1372 throw new IllegalStateException("getStageNumber() could not find parent " +
1376 return stage.parent.getChildPosition(stage);
1381 * Find a component with the given ID. The component tree is searched from this component
1382 * down (including this component) for the ID and the corresponding component is returned,
1383 * or null if not found.
1385 * @param idToFind ID to search for.
1386 * @return The component with the ID, or null if not found.
1388 public final RocketComponent findComponent(String idToFind) {
1390 Iterator<RocketComponent> iter = this.iterator(true);
1391 while (iter.hasNext()) {
1392 RocketComponent c = iter.next();
1393 if (c.getID().equals(idToFind))
1400 // TODO: Move these methods elsewhere (used only in SymmetricComponent)
1401 public final RocketComponent getPreviousComponent() {
1403 this.checkComponentStructure();
1406 int pos = parent.getChildPosition(this);
1408 StringBuffer sb = new StringBuffer();
1409 sb.append("Inconsistent internal state: ");
1410 sb.append("this=").append(this).append('[')
1411 .append(System.identityHashCode(this)).append(']');
1412 sb.append(" parent.children=[");
1413 for (int i = 0; i < parent.children.size(); i++) {
1414 RocketComponent c = parent.children.get(i);
1415 sb.append(c).append('[').append(System.identityHashCode(c)).append(']');
1416 if (i < parent.children.size() - 1)
1420 throw new IllegalStateException(sb.toString());
1425 RocketComponent c = parent.getChild(pos - 1);
1426 while (c.getChildCount() > 0)
1427 c = c.getChild(c.getChildCount() - 1);
1431 // TODO: Move these methods elsewhere (used only in SymmetricComponent)
1432 public final RocketComponent getNextComponent() {
1434 if (getChildCount() > 0)
1437 RocketComponent current = this;
1438 RocketComponent nextParent = this.parent;
1440 while (nextParent != null) {
1441 int pos = nextParent.getChildPosition(current);
1442 if (pos < nextParent.getChildCount() - 1)
1443 return nextParent.getChild(pos + 1);
1445 current = nextParent;
1446 nextParent = current.parent;
1452 /////////// Event handling //////////
1454 // Listener lists are provided by the root Rocket component,
1455 // a single listener list for the whole rocket.
1459 * Adds a ComponentChangeListener to the rocket tree. The listener is added to the root
1460 * component, which must be of type Rocket (which overrides this method). Events of all
1461 * subcomponents are sent to all listeners.
1463 * @throws IllegalStateException - if the root component is not a Rocket
1465 public void addComponentChangeListener(ComponentChangeListener l) {
1467 getRocket().addComponentChangeListener(l);
1471 * Removes a ComponentChangeListener from the rocket tree. The listener is removed from
1472 * the root component, which must be of type Rocket (which overrides this method).
1473 * Does nothing if the root component is not a Rocket. (The asymmetry is so
1474 * that listeners can always be removed just in case.)
1476 * @param l Listener to remove
1478 public void removeComponentChangeListener(ComponentChangeListener l) {
1479 if (parent != null) {
1480 getRoot().removeComponentChangeListener(l);
1486 * Adds a <code>ChangeListener</code> to the rocket tree. This is identical to
1487 * <code>addComponentChangeListener()</code> except that it uses a
1488 * <code>ChangeListener</code>. The same events are dispatched to the
1489 * <code>ChangeListener</code>, as <code>ComponentChangeEvent</code> is a subclass
1490 * of <code>ChangeEvent</code>.
1492 * @throws IllegalStateException - if the root component is not a <code>Rocket</code>
1495 public void addChangeListener(EventListener l) {
1497 getRocket().addChangeListener(l);
1501 * Removes a ChangeListener from the rocket tree. This is identical to
1502 * removeComponentChangeListener() except it uses a ChangeListener.
1503 * Does nothing if the root component is not a Rocket. (The asymmetry is so
1504 * that listeners can always be removed just in case.)
1506 * @param l Listener to remove
1509 public void removeChangeListener(EventListener l) {
1510 if (this.parent != null) {
1511 getRoot().removeChangeListener(l);
1517 * Fires a ComponentChangeEvent on the rocket structure. The call is passed to the
1518 * root component, which must be of type Rocket (which overrides this method).
1519 * Events of all subcomponents are sent to all listeners.
1521 * If the component tree root is not a Rocket, the event is ignored. This is the
1522 * case when constructing components not in any Rocket tree. In this case it
1523 * would be impossible for the component to have listeners in any case.
1525 * @param e Event to send
1527 protected void fireComponentChangeEvent(ComponentChangeEvent e) {
1529 if (parent == null) {
1530 /* Ignore if root invalid. */
1531 log.debug("Attempted firing event " + e + " with root " + this.getComponentName() + ", ignoring event");
1534 getRoot().fireComponentChangeEvent(e);
1539 * Fires a ComponentChangeEvent of the given type. The source of the event is set to
1542 * @param type Type of event
1543 * @see #fireComponentChangeEvent(ComponentChangeEvent)
1545 protected void fireComponentChangeEvent(int type) {
1546 fireComponentChangeEvent(new ComponentChangeEvent(this, type));
1551 * Checks whether this component has been invalidated and should no longer be used.
1552 * This is a safety check that in-place replaced components are no longer used.
1553 * All non-trivial methods (with the exception of methods simply getting a property)
1554 * should call this method before changing or computing anything.
1556 * @throws BugException if this component has been invalidated by {@link #copyFrom(RocketComponent)}.
1558 protected void checkState() {
1559 invalidator.check(true);
1565 * Check that the local component structure is correct. This can be called after changing
1566 * the component structure in order to verify the integrity.
1568 * TODO: Remove this after the "inconsistent internal state" bug has been corrected
1570 public void checkComponentStructure() {
1571 if (this.parent != null) {
1572 // Test that this component is found in parent's children with == operator
1573 if (!containsExact(this.parent.children, this)) {
1574 throw new BugException("Inconsistent component structure detected, parent does not contain this " +
1575 "component as a child, parent=" + parent.toDebugString() + " this=" + this.toDebugString());
1578 for (RocketComponent child : this.children) {
1579 if (child.parent != this) {
1580 throw new BugException("Inconsistent component structure detected, child does not have this component " +
1581 "as the parent, this=" + this.toDebugString() + " child=" + child.toDebugString() +
1582 " child.parent=" + (child.parent == null ? "null" : child.parent.toDebugString()));
1587 // Check whether the list contains exactly the searched-for component (with == operator)
1588 private boolean containsExact(List<RocketComponent> haystack, RocketComponent needle) {
1589 for (RocketComponent c : haystack) {
1598 /////////// Iterators //////////
1601 * Returns an iterator that iterates over all children and sub-children.
1603 * The iterator iterates through all children below this object, including itself if
1604 * <code>returnSelf</code> is true. The order of the iteration is not specified
1605 * (it may be specified in the future).
1607 * If an iterator iterating over only the direct children of the component is required,
1608 * use <code>component.getChildren().iterator()</code>.
1610 * TODO: HIGH: Remove this after merges have been done
1612 * @param returnSelf boolean value specifying whether the component itself should be
1614 * @return An iterator for the children and sub-children.
1615 * @deprecated Use {@link #iterator(boolean)} instead
1618 public final Iterator<RocketComponent> deepIterator(boolean returnSelf) {
1619 return iterator(returnSelf);
1624 * Returns an iterator that iterates over all children and sub-children, including itself.
1626 * This method is equivalent to <code>deepIterator(true)</code>.
1628 * TODO: HIGH: Remove this after merges have been done
1630 * @return An iterator for this component, its children and sub-children.
1631 * @deprecated Use {@link #iterator()} instead
1634 public final Iterator<RocketComponent> deepIterator() {
1641 * Returns an iterator that iterates over all children and sub-children.
1643 * The iterator iterates through all children below this object, including itself if
1644 * <code>returnSelf</code> is true. The order of the iteration is not specified
1645 * (it may be specified in the future).
1647 * If an iterator iterating over only the direct children of the component is required,
1648 * use <code>component.getChildren().iterator()</code>.
1650 * @param returnSelf boolean value specifying whether the component itself should be
1652 * @return An iterator for the children and sub-children.
1654 public final Iterator<RocketComponent> iterator(boolean returnSelf) {
1656 return new RocketComponentIterator(this, returnSelf);
1661 * Returns an iterator that iterates over this component, its children and sub-children.
1663 * This method is equivalent to <code>iterator(true)</code>.
1665 * @return An iterator for this component, its children and sub-children.
1668 public final Iterator<RocketComponent> iterator() {
1669 return iterator(true);
1677 * Compare component equality based on the ID of this component. Only the
1678 * ID and class type is used for a basis of comparison.
1681 public boolean equals(Object obj) {
1686 if (this.getClass() != obj.getClass())
1688 RocketComponent other = (RocketComponent) obj;
1689 return this.id.equals(other.id);
1695 public int hashCode() {
1696 return id.hashCode();
1701 //////////// Helper methods for subclasses
1707 * Helper method to add rotationally symmetric bounds at the specified coordinates.
1708 * The X-axis value is <code>x</code> and the radius at the specified position is
1711 protected static final void addBound(Collection<Coordinate> bounds, double x, double r) {
1712 bounds.add(new Coordinate(x, -r, -r));
1713 bounds.add(new Coordinate(x, r, -r));
1714 bounds.add(new Coordinate(x, r, r));
1715 bounds.add(new Coordinate(x, -r, r));
1719 protected static final Coordinate ringCG(double outerRadius, double innerRadius,
1720 double x1, double x2, double density) {
1721 return new Coordinate((x1 + x2) / 2, 0, 0,
1722 ringMass(outerRadius, innerRadius, x2 - x1, density));
1725 protected static final double ringVolume( double outerRadius, double innerRadius, double length ) {
1726 return ringMass( outerRadius, innerRadius, length, 1.0 );
1729 protected static final double ringMass(double outerRadius, double innerRadius,
1730 double length, double density) {
1731 return Math.PI * (MathUtil.pow2(outerRadius) - MathUtil.pow2(innerRadius)) *
1735 protected static final double ringLongitudinalUnitInertia(double outerRadius,
1736 double innerRadius, double length) {
1737 // 1/12 * (3 * (r1^2 + r2^2) + h^2)
1738 return (3 * (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) + MathUtil.pow2(length)) / 12;
1741 protected static final double ringRotationalUnitInertia(double outerRadius,
1742 double innerRadius) {
1743 // 1/2 * (r1^2 + r2^2)
1744 return (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) / 2;
1753 * Loads the RocketComponent fields from the given component. This method is meant
1754 * for in-place replacement of a component. It is used with the undo/redo
1755 * mechanism and when converting a finset into a freeform fin set.
1756 * This component must not have a parent, otherwise this method will fail.
1758 * The child components in the source tree are copied into the current tree, however,
1759 * the original components should not be used since they represent old copies of the
1760 * components. It is recommended to invalidate them by calling {@link #invalidate()}.
1762 * This method returns a list of components that should be invalidated after references
1763 * to them have been removed (for example by firing appropriate events). The list contains
1764 * all children and sub-children of the current component and the entire component
1765 * tree of <code>src</code>.
1767 * @return a list of components that should not be used after this call.
1769 protected List<RocketComponent> copyFrom(RocketComponent src) {
1771 List<RocketComponent> toInvalidate = new ArrayList<RocketComponent>();
1773 if (this.parent != null) {
1774 throw new UnsupportedOperationException("copyFrom called for non-root component, parent=" +
1775 this.parent.toDebugString() + ", this=" + this.toDebugString());
1778 // Add current structure to be invalidated
1779 Iterator<RocketComponent> iterator = this.iterator(false);
1780 while (iterator.hasNext()) {
1781 toInvalidate.add(iterator.next());
1784 // Remove previous components
1785 for (RocketComponent child : this.children) {
1786 child.parent = null;
1788 this.children.clear();
1790 // Copy new children to this component
1791 for (RocketComponent c : src.children) {
1792 RocketComponent copy = c.copyWithOriginalID();
1793 this.children.add(copy);
1797 this.checkComponentStructure();
1798 src.checkComponentStructure();
1800 // Set all parameters
1801 this.length = src.length;
1802 this.relativePosition = src.relativePosition;
1803 this.position = src.position;
1804 this.color = src.color;
1805 this.lineStyle = src.lineStyle;
1806 this.overrideMass = src.overrideMass;
1807 this.massOverriden = src.massOverriden;
1808 this.overrideCGX = src.overrideCGX;
1809 this.cgOverriden = src.cgOverriden;
1810 this.overrideSubcomponents = src.overrideSubcomponents;
1811 this.name = src.name;
1812 this.comment = src.comment;
1815 // Add source components to invalidation tree
1816 for (RocketComponent c : src) {
1817 toInvalidate.add(c);
1820 return toInvalidate;
1823 protected void invalidate() {
1824 invalidator.invalidate();
1828 ////////// Iterator implementation ///////////
1831 * Private inner class to implement the Iterator.
1833 * This iterator is fail-fast if the root of the structure is a Rocket.
1835 private static class RocketComponentIterator implements Iterator<RocketComponent> {
1836 // Stack holds iterators which still have some components left.
1837 private final Deque<Iterator<RocketComponent>> iteratorStack = new ArrayDeque<Iterator<RocketComponent>>();
1839 private final Rocket root;
1840 private final int treeModID;
1842 private final RocketComponent original;
1843 private boolean returnSelf = false;
1845 // Construct iterator with component's child's iterator, if it has elements
1846 public RocketComponentIterator(RocketComponent c, boolean returnSelf) {
1848 RocketComponent gp = c.getRoot();
1849 if (gp instanceof Rocket) {
1851 treeModID = root.getTreeModID();
1857 Iterator<RocketComponent> i = c.children.iterator();
1859 iteratorStack.push(i);
1862 this.returnSelf = returnSelf;
1866 public boolean hasNext() {
1870 return !iteratorStack.isEmpty(); // Elements remain if stack is not empty
1874 public RocketComponent next() {
1875 Iterator<RocketComponent> i;
1879 // Return original component first
1885 // Peek first iterator from stack, throw exception if empty
1886 i = iteratorStack.peek();
1888 throw new NoSuchElementException("No further elements in RocketComponent iterator");
1891 // Retrieve next component of the iterator, remove iterator from stack if empty
1892 RocketComponent c = i.next();
1894 iteratorStack.pop();
1896 // Add iterator of component children to stack if it has children
1897 i = c.children.iterator();
1899 iteratorStack.push(i);
1904 private void checkID() {
1906 if (root.getTreeModID() != treeModID) {
1907 throw new IllegalStateException("Rocket modified while being iterated");
1913 public void remove() {
1914 throw new UnsupportedOperationException("remove() not supported by " +
1915 "RocketComponent iterator");