Reimplement ComponentPreset to be a bag of typed parameters. This provides greater...
[debian/openrocket] / core / src / net / sf / openrocket / rocketcomponent / RocketComponent.java
1 package net.sf.openrocket.rocketcomponent;
2
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;
8 import java.util.List;
9 import java.util.NoSuchElementException;
10
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;
25
26
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();
30         
31         /*
32          * Text is suitable to the form
33          *    Position relative to:  <title>
34          */
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"));
51                 
52                 private String title;
53                 
54                 Position(String title) {
55                         this.title = title;
56                 }
57                 
58                 @Override
59                 public String toString() {
60                         return title;
61                 }
62         }
63         
64         /**
65          * A safety mutex that can be used to prevent concurrent access to this component.
66          */
67         protected SafetyMutex mutex = SafetyMutex.newInstance();
68         
69         ////////  Parent/child trees
70         /**
71          * Parent component of the current component, or null if none exists.
72          */
73         private RocketComponent parent = null;
74         
75         /**
76          * List of child components of this component.
77          */
78         private ArrayList<RocketComponent> children = new ArrayList<RocketComponent>();
79         
80         
81         ////////  Parameters common to all components:
82         
83         /**
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.
88          */
89         protected double length = 0;
90         
91         /**
92          * Positioning of this component relative to the parent component.
93          */
94         protected Position relativePosition;
95         
96         /**
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.
99          */
100         protected double position = 0;
101         
102         
103         // Color of the component, null means to use the default color
104         private Color color = null;
105         private LineStyle lineStyle = null;
106         
107         
108         // Override mass/CG
109         private double overrideMass = 0;
110         private boolean massOverriden = false;
111         private double overrideCGX = 0;
112         private boolean cgOverriden = false;
113         
114         private boolean overrideSubcomponents = false;
115         
116         
117         // User-given name of the component
118         private String name = null;
119         
120         // User-specified comment
121         private String comment = "";
122         
123         // Unique ID of the component
124         private String id = null;
125         
126         // Preset component this component is based upon
127         private ComponentPreset presetComponent = null;
128         
129         
130         /**
131          * Used to invalidate the component after calling {@link #copyFrom(RocketComponent)}.
132          */
133         private Invalidator invalidator = new Invalidator(this);
134         
135         
136         ////  NOTE !!!  All fields must be copied in the method copyFrom()!  ////
137         
138         
139         
140         /**
141          * Default constructor.  Sets the name of the component to the component's static name
142          * and the relative position of the component.
143          */
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;
148                 newID();
149         }
150         
151         ////////////  Methods that must be implemented  ////////////
152         
153         
154         /**
155          * Static component name.  The name may not vary of the parameters, it must be static.
156          */
157         public abstract String getComponentName(); // Static component type name
158         
159         /**
160          * Return the component mass (regardless of mass overriding).
161          */
162         public abstract double getComponentMass(); // Mass of non-overridden component
163         
164         /**
165          * Return the component CG and mass (regardless of CG or mass overriding).
166          */
167         public abstract Coordinate getComponentCG(); // CG of non-overridden component
168         
169         
170         /**
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.
175          *
176          * @return   the longitudinal unitary moment of inertia of this component.
177          */
178         public abstract double getLongitudinalUnitInertia();
179         
180         
181         /**
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.
186          *
187          * @return   the rotational unitary moment of inertia of this component.
188          */
189         public abstract double getRotationalUnitInertia();
190         
191         
192         /**
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.
196          *
197          * @return      <code>true</code> if children can be attached to this component, <code>false</code> otherwise.
198          */
199         public abstract boolean allowsChildren();
200         
201         /**
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).
206          *
207          * @param type  The RocketComponent class type to add.
208          * @return      Whether such a component can be added.
209          */
210         public abstract boolean isCompatible(Class<? extends RocketComponent> type);
211         
212         
213         /* Non-abstract helper method */
214         /**
215          * Test whether the given component can be added to this component.  This is equivalent
216          * to calling <code>isCompatible(c.getClass())</code>.
217          *
218          * @param c  Component to test.
219          * @return   Whether the component can be added.
220          * @see #isCompatible(Class)
221          */
222         public final boolean isCompatible(RocketComponent c) {
223                 mutex.verify();
224                 return isCompatible(c.getClass());
225         }
226         
227         
228         
229         /**
230          * Return a collection of bounding coordinates.  The coordinates must be such that
231          * the component is fully enclosed in their convex hull.
232          *
233          * @return      a collection of coordinates that bound the component.
234          */
235         public abstract Collection<Coordinate> getComponentBounds();
236         
237         /**
238          * Return true if the component may have an aerodynamic effect on the rocket.
239          */
240         public abstract boolean isAerodynamic();
241         
242         /**
243          * Return true if the component may have an effect on the rocket's mass.
244          */
245         public abstract boolean isMassive();
246         
247         
248         
249         
250         
251         ////////////  Methods that may be overridden  ////////////
252         
253         
254         /**
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.
259          * <p>
260          * The default implementation simply returns the array, and thus produces no shift.
261          *
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.
265          */
266         public Coordinate[] shiftCoordinates(Coordinate[] c) {
267                 checkState();
268                 return c;
269         }
270         
271         
272         /**
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.
277          *
278          * @param e  The event fired
279          */
280         protected void componentChanged(ComponentChangeEvent e) {
281                 // No-op
282                 checkState();
283         }
284         
285         
286         
287         
288         /**
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.
291          *
292          * @return A string describing the component.
293          */
294         @Override
295         public final String toString() {
296                 mutex.verify();
297                 if (name.length() == 0)
298                         return getComponentName();
299                 else
300                         return name;
301         }
302         
303         
304         /**
305          * Create a string describing the basic component structure from this component downwards.
306          * @return      a string containing the rocket structure
307          */
308         public final String toDebugString() {
309                 mutex.lock("toDebugString");
310                 try {
311                         StringBuilder sb = new StringBuilder();
312                         toDebugString(sb);
313                         return sb.toString();
314                 } finally {
315                         mutex.unlock("toDebugString");
316                 }
317         }
318         
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) {
323                         sb.append("; ");
324                         c.toDebugString(sb);
325                 }
326                 sb.append(']');
327         }
328         
329         
330         /**
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.
334          *
335          * @return A deep copy of the structure.
336          */
337         public final RocketComponent copy() {
338                 RocketComponent clone = copyWithOriginalID();
339                 
340                 Iterator<RocketComponent> iterator = clone.iterator(true);
341                 while (iterator.hasNext()) {
342                         iterator.next().newID();
343                 }
344                 return clone;
345         }
346         
347         
348         
349         /**
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.
355          * <p>
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.
360          * <p>
361          * This is not performed as serializing/deserializing for performance reasons.
362          *
363          * @return A deep copy of the structure.
364          */
365         protected RocketComponent copyWithOriginalID() {
366                 mutex.lock("copyWithOriginalID");
367                 try {
368                         checkState();
369                         RocketComponent clone;
370                         try {
371                                 clone = (RocketComponent) this.clone();
372                         } catch (CloneNotSupportedException e) {
373                                 throw new BugException("CloneNotSupportedException encountered, report a bug!", e);
374                         }
375                         
376                         // Reset the mutex
377                         clone.mutex = SafetyMutex.newInstance();
378                         
379                         // Reset all parent/child information
380                         clone.parent = null;
381                         clone.children = new ArrayList<RocketComponent>();
382                         
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;
389                         }
390                         
391                         this.checkComponentStructure();
392                         clone.checkComponentStructure();
393                         
394                         return clone;
395                 } finally {
396                         mutex.unlock("copyWithOriginalID");
397                 }
398         }
399         
400         
401         //////////////  Methods that may not be overridden  ////////////
402         
403         
404         
405         ////////// Common parameter setting/getting //////////
406         
407         /**
408          * Return the color of the object to use in 2D figures, or <code>null</code>
409          * to use the default color.
410          */
411         public final Color getColor() {
412                 mutex.verify();
413                 return color;
414         }
415         
416         /**
417          * Set the color of the object to use in 2D figures.
418          */
419         public final void setColor(Color c) {
420                 if ((color == null && c == null) ||
421                                 (color != null && color.equals(c)))
422                         return;
423                 
424                 checkState();
425                 this.color = c;
426                 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
427         }
428         
429         
430         public final LineStyle getLineStyle() {
431                 mutex.verify();
432                 return lineStyle;
433         }
434         
435         public final void setLineStyle(LineStyle style) {
436                 if (this.lineStyle == style)
437                         return;
438                 checkState();
439                 this.lineStyle = style;
440                 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
441         }
442         
443         
444         
445         
446         /**
447          * Get the current override mass.  The mass is not necessarily in use
448          * at the moment.
449          *
450          * @return  the override mass
451          */
452         public final double getOverrideMass() {
453                 mutex.verify();
454                 return overrideMass;
455         }
456         
457         /**
458          * Set the current override mass.  The mass is not set to use by this
459          * method.
460          *
461          * @param m  the override mass
462          */
463         public final void setOverrideMass(double m) {
464                 if (MathUtil.equals(m, overrideMass))
465                         return;
466                 checkState();
467                 overrideMass = Math.max(m, 0);
468                 if (massOverriden)
469                         fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
470         }
471         
472         /**
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.
475          *
476          * @return  whether the mass is overridden
477          */
478         public final boolean isMassOverridden() {
479                 mutex.verify();
480                 return massOverriden;
481         }
482         
483         /**
484          * Set whether the mass is currently overridden.
485          *
486          * @param o  whether the mass is overridden
487          */
488         public final void setMassOverridden(boolean o) {
489                 if (massOverriden == o) {
490                         return;
491                 }
492                 checkState();
493                 massOverriden = o;
494                 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
495         }
496         
497         
498         
499         
500         
501         /**
502          * Return the current override CG.  The CG is not necessarily overridden.
503          *
504          * @return  the override CG
505          */
506         public final Coordinate getOverrideCG() {
507                 mutex.verify();
508                 return getComponentCG().setX(overrideCGX);
509         }
510         
511         /**
512          * Return the x-coordinate of the current override CG.
513          *
514          * @return      the x-coordinate of the override CG.
515          */
516         public final double getOverrideCGX() {
517                 mutex.verify();
518                 return overrideCGX;
519         }
520         
521         /**
522          * Set the current override CG to (x,0,0).
523          *
524          * @param x  the x-coordinate of the override CG to set.
525          */
526         public final void setOverrideCGX(double x) {
527                 if (MathUtil.equals(overrideCGX, x))
528                         return;
529                 checkState();
530                 this.overrideCGX = x;
531                 if (isCGOverridden())
532                         fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
533                 else
534                         fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
535         }
536         
537         /**
538          * Return whether the CG is currently overridden.
539          *
540          * @return  whether the CG is overridden
541          */
542         public final boolean isCGOverridden() {
543                 mutex.verify();
544                 return cgOverriden;
545         }
546         
547         /**
548          * Set whether the CG is currently overridden.
549          *
550          * @param o  whether the CG is overridden
551          */
552         public final void setCGOverridden(boolean o) {
553                 if (cgOverriden == o) {
554                         return;
555                 }
556                 checkState();
557                 cgOverriden = o;
558                 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
559         }
560         
561         
562         
563         /**
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>.
570          *
571          * @return      whether the current mass and/or CG override overrides subcomponents as well.
572          */
573         public boolean getOverrideSubcomponents() {
574                 mutex.verify();
575                 return overrideSubcomponents;
576         }
577         
578         
579         /**
580          * Set whether the mass and/or CG override overrides all subcomponent values
581          * as well.  See {@link #getOverrideSubcomponents()} for details.
582          *
583          * @param override      whether the mass and/or CG override overrides all subcomponent.
584          */
585         public void setOverrideSubcomponents(boolean override) {
586                 if (overrideSubcomponents == override) {
587                         return;
588                 }
589                 checkState();
590                 overrideSubcomponents = override;
591                 fireComponentChangeEvent(ComponentChangeEvent.MASS_CHANGE);
592         }
593         
594         /**
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.
598          * <p>
599          * This method may be overridden if the setting of overriding subcomponents
600          * cannot be set.
601          *
602          * @return      whether the option to override subcomponents is currently enabled.
603          */
604         public boolean isOverrideSubcomponentsEnabled() {
605                 mutex.verify();
606                 return isCGOverridden() || isMassOverridden();
607         }
608         
609         
610         
611         
612         /**
613          * Get the user-defined name of the component.
614          */
615         public final String getName() {
616                 mutex.verify();
617                 return name;
618         }
619         
620         /**
621          * Set the user-defined name of the component.  If name==null, sets the name to
622          * the default name, currently the component name.
623          */
624         public final void setName(String name) {
625                 if (this.name.equals(name)) {
626                         return;
627                 }
628                 checkState();
629                 if (name == null || name.matches("^\\s*$"))
630                         this.name = getComponentName();
631                 else
632                         this.name = name;
633                 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
634         }
635         
636         
637         /**
638          * Return the comment of the component.  The component may contain multiple lines
639          * using \n as a newline separator.
640          *
641          * @return  the comment of the component.
642          */
643         public final String getComment() {
644                 mutex.verify();
645                 return comment;
646         }
647         
648         /**
649          * Set the comment of the component.
650          *
651          * @param comment  the comment of the component.
652          */
653         public final void setComment(String comment) {
654                 if (this.comment.equals(comment))
655                         return;
656                 checkState();
657                 if (comment == null)
658                         this.comment = "";
659                 else
660                         this.comment = comment;
661                 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
662         }
663         
664         
665         
666         /**
667          * Return the preset component that this component is based upon.
668          * 
669          * @return      the preset component, or <code>null</code> if this is not based on a preset.
670          */
671         public final ComponentPreset getPresetComponent() {
672                 return presetComponent;
673         }
674         
675         /**
676          * Set the preset component this component is based upon and load all of the 
677          * preset values.
678          * 
679          * @param preset        the preset component to load, or <code>null</code> to clear the preset.
680          */
681         public final void loadPreset(ComponentPreset preset) {
682                 if (presetComponent == preset) {
683                         return;
684                 }
685                 
686                 if (preset == null) {
687                         clearPreset();
688                         return;
689                 }
690                 
691                 // TODO - do we need to this compatibility check?
692                 /*
693                 if (preset.getComponentClass() != this.getClass()) {
694                         throw new IllegalArgumentException("Attempting to load preset of type " + preset.getComponentClass()
695                                         + " into component of type " + this.getClass());
696                 }
697                 */
698                 
699                 RocketComponent root = getRoot();
700                 final Rocket rocket;
701                 if (root instanceof Rocket) {
702                         rocket = (Rocket) root;
703                 } else {
704                         rocket = null;
705                 }
706                 
707                 try {
708                         if (rocket != null) {
709                                 rocket.freeze();
710                         }
711                         
712                         loadFromPreset(preset);
713                         
714                         this.presetComponent = preset;
715                         fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
716                         
717                 } finally {
718                         if (rocket != null) {
719                                 rocket.thaw();
720                         }
721                 }
722         }
723         
724         
725         /**
726          * Load component properties from the specified preset.  The preset is guaranteed
727          * to be of the correct type.
728          * <p>
729          * This method should fire the appropriate events related to the changes.  The rocket
730          * is frozen by the caller, so the events will be automatically combined.
731          * <p>
732          * This method must FIRST perform the preset loading and THEN call super.loadFromPreset().
733          * This is because mass setting requires the dimensions to be set beforehand.
734          * 
735          * @param preset        the preset to load from
736          */
737         protected void loadFromPreset(ComponentPreset preset) {
738                 // No-op
739         }
740         
741         
742         /**
743          * Clear the current component preset.  This does not affect the component properties
744          * otherwise.
745          */
746         public final void clearPreset() {
747                 if (presetComponent == null)
748                         return;
749                 presetComponent = null;
750                 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
751         }
752         
753         
754         
755         /**
756          * Returns the unique ID of the component.
757          *
758          * @return      the ID of the component.
759          */
760         public final String getID() {
761                 return id;
762         }
763         
764         /**
765          * Generate a new ID for this component.
766          */
767         private final void newID() {
768                 mutex.verify();
769                 this.id = UniqueID.uuid();
770         }
771         
772         
773         
774         
775         /**
776          * Get the characteristic length of the component, for example the length of a body tube
777          * of the length of the root chord of a fin.  This is used in positioning the component
778          * relative to its parent.
779          *
780          * If the length of a component is settable, the class must define the setter method
781          * itself.
782          */
783         public final double getLength() {
784                 mutex.verify();
785                 return length;
786         }
787         
788         /**
789          * Get the positioning of the component relative to its parent component.
790          * This is one of the enums of {@link Position}.  A setter method is not provided,
791          * but can be provided by a subclass.
792          */
793         public final Position getRelativePosition() {
794                 mutex.verify();
795                 return relativePosition;
796         }
797         
798         
799         /**
800          * Set the positioning of the component relative to its parent component.
801          * The actual position of the component is maintained to the best ability.
802          * <p>
803          * The default implementation is of protected visibility, since many components
804          * do not support setting the relative position.  A component that does support
805          * it should override this with a public method that simply calls this
806          * supermethod AND fire a suitable ComponentChangeEvent.
807          *
808          * @param position      the relative positioning.
809          */
810         protected void setRelativePosition(RocketComponent.Position position) {
811                 if (this.relativePosition == position)
812                         return;
813                 checkState();
814                 
815                 // Update position so as not to move the component
816                 if (this.parent != null) {
817                         double thisPos = this.toRelative(Coordinate.NUL, this.parent)[0].x;
818                         
819                         switch (position) {
820                         case ABSOLUTE:
821                                 this.position = this.toAbsolute(Coordinate.NUL)[0].x;
822                                 break;
823                         
824                         case TOP:
825                                 this.position = thisPos;
826                                 break;
827                         
828                         case MIDDLE:
829                                 this.position = thisPos - (this.parent.length - this.length) / 2;
830                                 break;
831                         
832                         case BOTTOM:
833                                 this.position = thisPos - (this.parent.length - this.length);
834                                 break;
835                         
836                         default:
837                                 throw new BugException("Unknown position type: " + position);
838                         }
839                 }
840                 
841                 this.relativePosition = position;
842                 fireComponentChangeEvent(ComponentChangeEvent.BOTH_CHANGE);
843         }
844         
845         
846         /**
847          * Determine position relative to given position argument.  Note: This is a side-effect free method.  No state
848          * is modified.
849          *
850          * @param thePosition the relative position to be used as the basis for the computation
851          * @param relativeTo  the position is computed relative the the given component
852          *
853          * @return double position of the component relative to the parent, with respect to <code>position</code>
854          */
855         public double asPositionValue(Position thePosition, RocketComponent relativeTo) {
856                 double result = this.position;
857                 if (relativeTo != null) {
858                         double thisPos = this.toRelative(Coordinate.NUL, relativeTo)[0].x;
859                         
860                         switch (thePosition) {
861                         case ABSOLUTE:
862                                 result = this.toAbsolute(Coordinate.NUL)[0].x;
863                                 break;
864                         case TOP:
865                                 result = thisPos;
866                                 break;
867                         case MIDDLE:
868                                 result = thisPos - (relativeTo.length - this.length) / 2;
869                                 break;
870                         case BOTTOM:
871                                 result = thisPos - (relativeTo.length - this.length);
872                                 break;
873                         default:
874                                 throw new BugException("Unknown position type: " + thePosition);
875                         }
876                 }
877                 return result;
878         }
879         
880         /**
881          * Get the position value of the component.  The exact meaning of the value is
882          * dependent on the current relative positioning.
883          *
884          * @return  the positional value.
885          */
886         public final double getPositionValue() {
887                 mutex.verify();
888                 return position;
889         }
890         
891         
892         /**
893          * Set the position value of the component.  The exact meaning of the value
894          * depends on the current relative positioning.
895          * <p>
896          * The default implementation is of protected visibility, since many components
897          * do not support setting the relative position.  A component that does support
898          * it should override this with a public method that simply calls this
899          * supermethod AND fire a suitable ComponentChangeEvent.
900          *
901          * @param value         the position value of the component.
902          */
903         public void setPositionValue(double value) {
904                 if (MathUtil.equals(this.position, value))
905                         return;
906                 checkState();
907                 this.position = value;
908         }
909         
910         
911         
912         ///////////  Coordinate changes  ///////////
913         
914         /**
915          * Returns coordinate c in absolute coordinates.  Equivalent to toComponent(c,null).
916          */
917         public Coordinate[] toAbsolute(Coordinate c) {
918                 checkState();
919                 return toRelative(c, null);
920         }
921         
922         
923         /**
924          * Return coordinate <code>c</code> described in the coordinate system of
925          * <code>dest</code>.  If <code>dest</code> is <code>null</code> returns
926          * absolute coordinates.
927          * <p>
928          * This method returns an array of coordinates, each of which represents a
929          * position of the coordinate in clustered cases.  The array is guaranteed
930          * to contain at least one element.
931          * <p>
932          * The current implementation does not support rotating components.
933          *
934          * @param c    Coordinate in the component's coordinate system.
935          * @param dest Destination component coordinate system.
936          * @return     an array of coordinates describing <code>c</code> in coordinates
937          *                         relative to <code>dest</code>.
938          */
939         public final Coordinate[] toRelative(Coordinate c, RocketComponent dest) {
940                 checkState();
941                 mutex.lock("toRelative");
942                 try {
943                         double absoluteX = Double.NaN;
944                         RocketComponent search = dest;
945                         Coordinate[] array = new Coordinate[1];
946                         array[0] = c;
947                         
948                         RocketComponent component = this;
949                         while ((component != search) && (component.parent != null)) {
950                                 
951                                 array = component.shiftCoordinates(array);
952                                 
953                                 switch (component.relativePosition) {
954                                 case TOP:
955                                         for (int i = 0; i < array.length; i++) {
956                                                 array[i] = array[i].add(component.position, 0, 0);
957                                         }
958                                         break;
959                                 
960                                 case MIDDLE:
961                                         for (int i = 0; i < array.length; i++) {
962                                                 array[i] = array[i].add(component.position +
963                                                                 (component.parent.length - component.length) / 2, 0, 0);
964                                         }
965                                         break;
966                                 
967                                 case BOTTOM:
968                                         for (int i = 0; i < array.length; i++) {
969                                                 array[i] = array[i].add(component.position +
970                                                                 (component.parent.length - component.length), 0, 0);
971                                         }
972                                         break;
973                                 
974                                 case AFTER:
975                                         // Add length of all previous brother-components with POSITION_RELATIVE_AFTER
976                                         int index = component.parent.children.indexOf(component);
977                                         assert (index >= 0);
978                                         for (index--; index >= 0; index--) {
979                                                 RocketComponent comp = component.parent.children.get(index);
980                                                 double componentLength = comp.getTotalLength();
981                                                 for (int i = 0; i < array.length; i++) {
982                                                         array[i] = array[i].add(componentLength, 0, 0);
983                                                 }
984                                         }
985                                         for (int i = 0; i < array.length; i++) {
986                                                 array[i] = array[i].add(component.position + component.parent.length, 0, 0);
987                                         }
988                                         break;
989                                 
990                                 case ABSOLUTE:
991                                         search = null; // Requires back-search if dest!=null
992                                         if (Double.isNaN(absoluteX)) {
993                                                 absoluteX = component.position;
994                                         }
995                                         break;
996                                 
997                                 default:
998                                         throw new BugException("Unknown relative positioning type of component" +
999                                                         component + ": " + component.relativePosition);
1000                                 }
1001                                 
1002                                 component = component.parent; // parent != null
1003                         }
1004                         
1005                         if (!Double.isNaN(absoluteX)) {
1006                                 for (int i = 0; i < array.length; i++) {
1007                                         array[i] = array[i].setX(absoluteX + c.x);
1008                                 }
1009                         }
1010                         
1011                         // Check whether destination has been found or whether to backtrack
1012                         // TODO: LOW: Backtracking into clustered components uses only one component
1013                         if ((dest != null) && (component != dest)) {
1014                                 Coordinate[] origin = dest.toAbsolute(Coordinate.NUL);
1015                                 for (int i = 0; i < array.length; i++) {
1016                                         array[i] = array[i].sub(origin[0]);
1017                                 }
1018                         }
1019                         
1020                         return array;
1021                 } finally {
1022                         mutex.unlock("toRelative");
1023                 }
1024         }
1025         
1026         
1027         /**
1028          * Recursively sum the lengths of all subcomponents that have position
1029          * Position.AFTER.
1030          *
1031          * @return  Sum of the lengths.
1032          */
1033         private final double getTotalLength() {
1034                 checkState();
1035                 this.checkComponentStructure();
1036                 mutex.lock("getTotalLength");
1037                 try {
1038                         double l = 0;
1039                         if (relativePosition == Position.AFTER)
1040                                 l = length;
1041                         for (int i = 0; i < children.size(); i++)
1042                                 l += children.get(i).getTotalLength();
1043                         return l;
1044                 } finally {
1045                         mutex.unlock("getTotalLength");
1046                 }
1047         }
1048         
1049         
1050         
1051         /////////// Total mass and CG calculation ////////////
1052         
1053         /**
1054          * Return the (possibly overridden) mass of component.
1055          *
1056          * @return The mass of the component or the given override mass.
1057          */
1058         public final double getMass() {
1059                 mutex.verify();
1060                 if (massOverriden)
1061                         return overrideMass;
1062                 return getComponentMass();
1063         }
1064         
1065         /**
1066          * Return the (possibly overridden) center of gravity and mass.
1067          *
1068          * Returns the CG with the weight of the coordinate set to the weight of the component.
1069          * Both CG and mass may be separately overridden.
1070          *
1071          * @return The CG of the component or the given override CG.
1072          */
1073         public final Coordinate getCG() {
1074                 checkState();
1075                 if (cgOverriden)
1076                         return getOverrideCG().setWeight(getMass());
1077                 
1078                 if (massOverriden)
1079                         return getComponentCG().setWeight(getMass());
1080                 
1081                 return getComponentCG();
1082         }
1083         
1084         
1085         /**
1086          * Return the longitudinal (around the y- or z-axis) moment of inertia of this component.
1087          * The moment of inertia is scaled in reference to the (possibly overridden) mass
1088          * and is relative to the non-overridden CG.
1089          *
1090          * @return    the longitudinal moment of inertia of this component.
1091          */
1092         public final double getLongitudinalInertia() {
1093                 checkState();
1094                 return getLongitudinalUnitInertia() * getMass();
1095         }
1096         
1097         /**
1098          * Return the rotational (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.
1101          *
1102          * @return    the rotational moment of inertia of this component.
1103          */
1104         public final double getRotationalInertia() {
1105                 checkState();
1106                 return getRotationalUnitInertia() * getMass();
1107         }
1108         
1109         
1110         
1111         ///////////  Children handling  ///////////
1112         
1113         
1114         /**
1115          * Adds a child to the rocket component tree.  The component is added to the end
1116          * of the component's child list.  This is a helper method that calls
1117          * {@link #addChild(RocketComponent,int)}.
1118          *
1119          * @param component  The component to add.
1120          * @throws IllegalArgumentException  if the component is already part of some
1121          *                                                                       component tree.
1122          * @see #addChild(RocketComponent,int)
1123          */
1124         public final void addChild(RocketComponent component) {
1125                 checkState();
1126                 addChild(component, children.size());
1127         }
1128         
1129         
1130         /**
1131          * Adds a child to the rocket component tree.  The component is added to
1132          * the given position of the component's child list.
1133          * <p>
1134          * This method may be overridden to enforce more strict component addition rules.
1135          * The tests should be performed first and then this method called.
1136          *
1137          * @param component     The component to add.
1138          * @param index         Position to add component to.
1139          * @throws IllegalArgumentException  If the component is already part of
1140          *                                                                       some component tree.
1141          */
1142         public void addChild(RocketComponent component, int index) {
1143                 checkState();
1144                 
1145                 if (component.parent != null) {
1146                         throw new IllegalArgumentException("component " + component.getComponentName() +
1147                                         " is already in a tree");
1148                 }
1149                 
1150                 // Ensure that the no loops are created in component tree [A -> X -> Y -> B, B.addChild(A)]
1151                 if (this.getRoot().equals(component)) {
1152                         throw new IllegalStateException("Component " + component.getComponentName() +
1153                                         " is a parent of " + this.getComponentName() + ", attempting to create cycle in tree.");
1154                 }
1155                 
1156                 if (!isCompatible(component)) {
1157                         throw new IllegalStateException("Component " + component.getComponentName() +
1158                                         " not currently compatible with component " + getComponentName());
1159                 }
1160                 
1161                 children.add(index, component);
1162                 component.parent = this;
1163                 
1164                 this.checkComponentStructure();
1165                 component.checkComponentStructure();
1166                 
1167                 fireAddRemoveEvent(component);
1168         }
1169         
1170         /**
1171          * Removes a child from the rocket component tree.
1172          *
1173          * @param n  remove the n'th child.
1174          * @throws IndexOutOfBoundsException  if n is out of bounds
1175          */
1176         public final void removeChild(int n) {
1177                 checkState();
1178                 RocketComponent component = children.remove(n);
1179                 component.parent = null;
1180                 
1181                 this.checkComponentStructure();
1182                 component.checkComponentStructure();
1183                 
1184                 fireAddRemoveEvent(component);
1185         }
1186         
1187         /**
1188          * Removes a child from the rocket component tree.  Does nothing if the component
1189          * is not present as a child.
1190          *
1191          * @param component             the component to remove
1192          * @return                              whether the component was a child
1193          */
1194         public final boolean removeChild(RocketComponent component) {
1195                 checkState();
1196                 
1197                 component.checkComponentStructure();
1198                 
1199                 if (children.remove(component)) {
1200                         component.parent = null;
1201                         
1202                         this.checkComponentStructure();
1203                         component.checkComponentStructure();
1204                         
1205                         fireAddRemoveEvent(component);
1206                         return true;
1207                 }
1208                 return false;
1209         }
1210         
1211         
1212         
1213         
1214         /**
1215          * Move a child to another position.
1216          *
1217          * @param component     the component to move
1218          * @param index the component's new position
1219          * @throws IllegalArgumentException If an illegal placement was attempted.
1220          */
1221         public final void moveChild(RocketComponent component, int index) {
1222                 checkState();
1223                 if (children.remove(component)) {
1224                         children.add(index, component);
1225                         
1226                         this.checkComponentStructure();
1227                         component.checkComponentStructure();
1228                         
1229                         fireAddRemoveEvent(component);
1230                 }
1231         }
1232         
1233         
1234         /**
1235          * Fires an AERODYNAMIC_CHANGE, MASS_CHANGE or OTHER_CHANGE event depending on the
1236          * type of component removed.
1237          */
1238         private void fireAddRemoveEvent(RocketComponent component) {
1239                 Iterator<RocketComponent> iter = component.iterator(true);
1240                 int type = ComponentChangeEvent.TREE_CHANGE;
1241                 while (iter.hasNext()) {
1242                         RocketComponent c = iter.next();
1243                         if (c.isAerodynamic())
1244                                 type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
1245                         if (c.isMassive())
1246                                 type |= ComponentChangeEvent.MASS_CHANGE;
1247                 }
1248                 
1249                 fireComponentChangeEvent(type);
1250         }
1251         
1252         
1253         public final int getChildCount() {
1254                 checkState();
1255                 this.checkComponentStructure();
1256                 return children.size();
1257         }
1258         
1259         public final RocketComponent getChild(int n) {
1260                 checkState();
1261                 this.checkComponentStructure();
1262                 return children.get(n);
1263         }
1264         
1265         public final List<RocketComponent> getChildren() {
1266                 checkState();
1267                 this.checkComponentStructure();
1268                 return children.clone();
1269         }
1270         
1271         
1272         /**
1273          * Returns the position of the child in this components child list, or -1 if the
1274          * component is not a child of this component.
1275          *
1276          * @param child  The child to search for.
1277          * @return  Position in the list or -1 if not found.
1278          */
1279         public final int getChildPosition(RocketComponent child) {
1280                 checkState();
1281                 this.checkComponentStructure();
1282                 return children.indexOf(child);
1283         }
1284         
1285         /**
1286          * Get the parent component of this component.  Returns <code>null</code> if the component
1287          * has no parent.
1288          *
1289          * @return  The parent of this component or <code>null</code>.
1290          */
1291         public final RocketComponent getParent() {
1292                 checkState();
1293                 return parent;
1294         }
1295         
1296         /**
1297          * Get the root component of the component tree.
1298          *
1299          * @return  The root component of the component tree.
1300          */
1301         public final RocketComponent getRoot() {
1302                 checkState();
1303                 RocketComponent gp = this;
1304                 while (gp.parent != null)
1305                         gp = gp.parent;
1306                 return gp;
1307         }
1308         
1309         /**
1310          * Returns the root Rocket component of this component tree.  Throws an
1311          * IllegalStateException if the root component is not a Rocket.
1312          *
1313          * @return  The root Rocket component of the component tree.
1314          * @throws  IllegalStateException  If the root component is not a Rocket.
1315          */
1316         public final Rocket getRocket() {
1317                 checkState();
1318                 RocketComponent r = getRoot();
1319                 if (r instanceof Rocket)
1320                         return (Rocket) r;
1321                 throw new IllegalStateException("getRocket() called with root component "
1322                                 + r.getComponentName());
1323         }
1324         
1325         
1326         /**
1327          * Return the Stage component that this component belongs to.  Throws an
1328          * IllegalStateException if a Stage is not in the parentage of this component.
1329          *
1330          * @return      The Stage component this component belongs to.
1331          * @throws      IllegalStateException   if a Stage component is not in the parentage.
1332          */
1333         public final Stage getStage() {
1334                 checkState();
1335                 RocketComponent c = this;
1336                 while (c != null) {
1337                         if (c instanceof Stage)
1338                                 return (Stage) c;
1339                         c = c.getParent();
1340                 }
1341                 throw new IllegalStateException("getStage() called without Stage as a parent.");
1342         }
1343         
1344         /**
1345          * Return the stage number of the stage this component belongs to.  The stages
1346          * are numbered from zero upwards.
1347          *
1348          * @return   the stage number this component belongs to.
1349          */
1350         public final int getStageNumber() {
1351                 checkState();
1352                 if (parent == null) {
1353                         throw new IllegalArgumentException("getStageNumber() called for root component");
1354                 }
1355                 
1356                 RocketComponent stage = this;
1357                 while (!(stage instanceof Stage)) {
1358                         stage = stage.parent;
1359                         if (stage == null || stage.parent == null) {
1360                                 throw new IllegalStateException("getStageNumber() could not find parent " +
1361                                                 "stage.");
1362                         }
1363                 }
1364                 return stage.parent.getChildPosition(stage);
1365         }
1366         
1367         
1368         /**
1369          * Find a component with the given ID.  The component tree is searched from this component
1370          * down (including this component) for the ID and the corresponding component is returned,
1371          * or null if not found.
1372          *
1373          * @param idToFind  ID to search for.
1374          * @return    The component with the ID, or null if not found.
1375          */
1376         public final RocketComponent findComponent(String idToFind) {
1377                 checkState();
1378                 Iterator<RocketComponent> iter = this.iterator(true);
1379                 while (iter.hasNext()) {
1380                         RocketComponent c = iter.next();
1381                         if (c.getID().equals(idToFind))
1382                                 return c;
1383                 }
1384                 return null;
1385         }
1386         
1387         
1388         // TODO: Move these methods elsewhere (used only in SymmetricComponent)
1389         public final RocketComponent getPreviousComponent() {
1390                 checkState();
1391                 this.checkComponentStructure();
1392                 if (parent == null)
1393                         return null;
1394                 int pos = parent.getChildPosition(this);
1395                 if (pos < 0) {
1396                         StringBuffer sb = new StringBuffer();
1397                         sb.append("Inconsistent internal state: ");
1398                         sb.append("this=").append(this).append('[')
1399                                         .append(System.identityHashCode(this)).append(']');
1400                         sb.append(" parent.children=[");
1401                         for (int i = 0; i < parent.children.size(); i++) {
1402                                 RocketComponent c = parent.children.get(i);
1403                                 sb.append(c).append('[').append(System.identityHashCode(c)).append(']');
1404                                 if (i < parent.children.size() - 1)
1405                                         sb.append(", ");
1406                         }
1407                         sb.append(']');
1408                         throw new IllegalStateException(sb.toString());
1409                 }
1410                 assert (pos >= 0);
1411                 if (pos == 0)
1412                         return parent;
1413                 RocketComponent c = parent.getChild(pos - 1);
1414                 while (c.getChildCount() > 0)
1415                         c = c.getChild(c.getChildCount() - 1);
1416                 return c;
1417         }
1418         
1419         // TODO: Move these methods elsewhere (used only in SymmetricComponent)
1420         public final RocketComponent getNextComponent() {
1421                 checkState();
1422                 if (getChildCount() > 0)
1423                         return getChild(0);
1424                 
1425                 RocketComponent current = this;
1426                 RocketComponent nextParent = this.parent;
1427                 
1428                 while (nextParent != null) {
1429                         int pos = nextParent.getChildPosition(current);
1430                         if (pos < nextParent.getChildCount() - 1)
1431                                 return nextParent.getChild(pos + 1);
1432                         
1433                         current = nextParent;
1434                         nextParent = current.parent;
1435                 }
1436                 return null;
1437         }
1438         
1439         
1440         ///////////  Event handling  //////////
1441         //
1442         // Listener lists are provided by the root Rocket component,
1443         // a single listener list for the whole rocket.
1444         //
1445         
1446         /**
1447          * Adds a ComponentChangeListener to the rocket tree.  The listener is added to the root
1448          * component, which must be of type Rocket (which overrides this method).  Events of all
1449          * subcomponents are sent to all listeners.
1450          *
1451          * @throws IllegalStateException - if the root component is not a Rocket
1452          */
1453         public void addComponentChangeListener(ComponentChangeListener l) {
1454                 checkState();
1455                 getRocket().addComponentChangeListener(l);
1456         }
1457         
1458         /**
1459          * Removes a ComponentChangeListener from the rocket tree.  The listener is removed from
1460          * the root component, which must be of type Rocket (which overrides this method).
1461          * Does nothing if the root component is not a Rocket.  (The asymmetry is so
1462          * that listeners can always be removed just in case.)
1463          *
1464          * @param l  Listener to remove
1465          */
1466         public void removeComponentChangeListener(ComponentChangeListener l) {
1467                 if (parent != null) {
1468                         getRoot().removeComponentChangeListener(l);
1469                 }
1470         }
1471         
1472         
1473         /**
1474          * Adds a <code>ChangeListener</code> to the rocket tree.  This is identical to
1475          * <code>addComponentChangeListener()</code> except that it uses a
1476          * <code>ChangeListener</code>.  The same events are dispatched to the
1477          * <code>ChangeListener</code>, as <code>ComponentChangeEvent</code> is a subclass
1478          * of <code>ChangeEvent</code>.
1479          *
1480          * @throws IllegalStateException - if the root component is not a <code>Rocket</code>
1481          */
1482         @Override
1483         public void addChangeListener(EventListener l) {
1484                 checkState();
1485                 getRocket().addChangeListener(l);
1486         }
1487         
1488         /**
1489          * Removes a ChangeListener from the rocket tree.  This is identical to
1490          * removeComponentChangeListener() except it uses a ChangeListener.
1491          * Does nothing if the root component is not a Rocket.  (The asymmetry is so
1492          * that listeners can always be removed just in case.)
1493          *
1494          * @param l  Listener to remove
1495          */
1496         @Override
1497         public void removeChangeListener(EventListener l) {
1498                 if (this.parent != null) {
1499                         getRoot().removeChangeListener(l);
1500                 }
1501         }
1502         
1503         
1504         /**
1505          * Fires a ComponentChangeEvent on the rocket structure.  The call is passed to the
1506          * root component, which must be of type Rocket (which overrides this method).
1507          * Events of all subcomponents are sent to all listeners.
1508          *
1509          * If the component tree root is not a Rocket, the event is ignored.  This is the
1510          * case when constructing components not in any Rocket tree.  In this case it
1511          * would be impossible for the component to have listeners in any case.
1512          *
1513          * @param e  Event to send
1514          */
1515         protected void fireComponentChangeEvent(ComponentChangeEvent e) {
1516                 checkState();
1517                 if (parent == null) {
1518                         /* Ignore if root invalid. */
1519                         log.debug("Attempted firing event " + e + " with root " + this.getComponentName() + ", ignoring event");
1520                         return;
1521                 }
1522                 getRoot().fireComponentChangeEvent(e);
1523         }
1524         
1525         
1526         /**
1527          * Fires a ComponentChangeEvent of the given type.  The source of the event is set to
1528          * this component.
1529          *
1530          * @param type  Type of event
1531          * @see #fireComponentChangeEvent(ComponentChangeEvent)
1532          */
1533         protected void fireComponentChangeEvent(int type) {
1534                 fireComponentChangeEvent(new ComponentChangeEvent(this, type));
1535         }
1536         
1537         
1538         /**
1539          * Checks whether this component has been invalidated and should no longer be used.
1540          * This is a safety check that in-place replaced components are no longer used.
1541          * All non-trivial methods (with the exception of methods simply getting a property)
1542          * should call this method before changing or computing anything.
1543          *
1544          * @throws      BugException    if this component has been invalidated by {@link #copyFrom(RocketComponent)}.
1545          */
1546         protected void checkState() {
1547                 invalidator.check(true);
1548                 mutex.verify();
1549         }
1550         
1551         
1552         /**
1553          * Check that the local component structure is correct.  This can be called after changing
1554          * the component structure in order to verify the integrity.
1555          * <p>
1556          * TODO: Remove this after the "inconsistent internal state" bug has been corrected
1557          */
1558         public void checkComponentStructure() {
1559                 if (this.parent != null) {
1560                         // Test that this component is found in parent's children with == operator
1561                         if (!containsExact(this.parent.children, this)) {
1562                                 throw new BugException("Inconsistent component structure detected, parent does not contain this " +
1563                                                 "component as a child, parent=" + parent.toDebugString() + " this=" + this.toDebugString());
1564                         }
1565                 }
1566                 for (RocketComponent child : this.children) {
1567                         if (child.parent != this) {
1568                                 throw new BugException("Inconsistent component structure detected, child does not have this component " +
1569                                                 "as the parent, this=" + this.toDebugString() + " child=" + child.toDebugString() +
1570                                                 " child.parent=" + (child.parent == null ? "null" : child.parent.toDebugString()));
1571                         }
1572                 }
1573         }
1574         
1575         // Check whether the list contains exactly the searched-for component (with == operator)
1576         private boolean containsExact(List<RocketComponent> haystack, RocketComponent needle) {
1577                 for (RocketComponent c : haystack) {
1578                         if (needle == c) {
1579                                 return true;
1580                         }
1581                 }
1582                 return false;
1583         }
1584         
1585         
1586         ///////////  Iterators  //////////
1587         
1588         /**
1589          * Returns an iterator that iterates over all children and sub-children.
1590          * <p>
1591          * The iterator iterates through all children below this object, including itself if
1592          * <code>returnSelf</code> is true.  The order of the iteration is not specified
1593          * (it may be specified in the future).
1594          * <p>
1595          * If an iterator iterating over only the direct children of the component is required,
1596          * use <code>component.getChildren().iterator()</code>.
1597          *
1598          * TODO: HIGH: Remove this after merges have been done
1599          *
1600          * @param returnSelf boolean value specifying whether the component itself should be
1601          *                                       returned
1602          * @return An iterator for the children and sub-children.
1603          * @deprecated Use {@link #iterator(boolean)} instead
1604          */
1605         @Deprecated
1606         public final Iterator<RocketComponent> deepIterator(boolean returnSelf) {
1607                 return iterator(returnSelf);
1608         }
1609         
1610         
1611         /**
1612          * Returns an iterator that iterates over all children and sub-children, including itself.
1613          * <p>
1614          * This method is equivalent to <code>deepIterator(true)</code>.
1615          *
1616          * TODO: HIGH: Remove this after merges have been done
1617          *
1618          * @return An iterator for this component, its children and sub-children.
1619          * @deprecated Use {@link #iterator()} instead
1620          */
1621         @Deprecated
1622         public final Iterator<RocketComponent> deepIterator() {
1623                 return iterator();
1624         }
1625         
1626         
1627         
1628         /**
1629          * Returns an iterator that iterates over all children and sub-children.
1630          * <p>
1631          * The iterator iterates through all children below this object, including itself if
1632          * <code>returnSelf</code> is true.  The order of the iteration is not specified
1633          * (it may be specified in the future).
1634          * <p>
1635          * If an iterator iterating over only the direct children of the component is required,
1636          * use <code>component.getChildren().iterator()</code>.
1637          *
1638          * @param returnSelf boolean value specifying whether the component itself should be
1639          *                                       returned
1640          * @return An iterator for the children and sub-children.
1641          */
1642         public final Iterator<RocketComponent> iterator(boolean returnSelf) {
1643                 checkState();
1644                 return new RocketComponentIterator(this, returnSelf);
1645         }
1646         
1647         
1648         /**
1649          * Returns an iterator that iterates over this component, its children and sub-children.
1650          * <p>
1651          * This method is equivalent to <code>iterator(true)</code>.
1652          *
1653          * @return An iterator for this component, its children and sub-children.
1654          */
1655         @Override
1656         public final Iterator<RocketComponent> iterator() {
1657                 return iterator(true);
1658         }
1659         
1660         
1661         
1662         
1663         
1664         /**
1665          * Compare component equality based on the ID of this component.  Only the
1666          * ID and class type is used for a basis of comparison.
1667          */
1668         @Override
1669         public boolean equals(Object obj) {
1670                 if (this == obj)
1671                         return true;
1672                 if (obj == null)
1673                         return false;
1674                 if (this.getClass() != obj.getClass())
1675                         return false;
1676                 RocketComponent other = (RocketComponent) obj;
1677                 return this.id.equals(other.id);
1678         }
1679         
1680         
1681         
1682         @Override
1683         public int hashCode() {
1684                 return id.hashCode();
1685         }
1686         
1687         
1688         
1689         ////////////  Helper methods for subclasses
1690         
1691         
1692         
1693         
1694         /**
1695          * Helper method to add rotationally symmetric bounds at the specified coordinates.
1696          * The X-axis value is <code>x</code> and the radius at the specified position is
1697          * <code>r</code>.
1698          */
1699         protected static final void addBound(Collection<Coordinate> bounds, double x, double r) {
1700                 bounds.add(new Coordinate(x, -r, -r));
1701                 bounds.add(new Coordinate(x, r, -r));
1702                 bounds.add(new Coordinate(x, r, r));
1703                 bounds.add(new Coordinate(x, -r, r));
1704         }
1705         
1706         
1707         protected static final Coordinate ringCG(double outerRadius, double innerRadius,
1708                         double x1, double x2, double density) {
1709                 return new Coordinate((x1 + x2) / 2, 0, 0,
1710                                 ringMass(outerRadius, innerRadius, x2 - x1, density));
1711         }
1712         
1713         protected static final double ringMass(double outerRadius, double innerRadius,
1714                         double length, double density) {
1715                 return Math.PI * (MathUtil.pow2(outerRadius) - MathUtil.pow2(innerRadius)) *
1716                                 length * density;
1717         }
1718         
1719         protected static final double ringLongitudinalUnitInertia(double outerRadius,
1720                         double innerRadius, double length) {
1721                 // 1/12 * (3 * (r1^2 + r2^2) + h^2)
1722                 return (3 * (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) + MathUtil.pow2(length)) / 12;
1723         }
1724         
1725         protected static final double ringRotationalUnitInertia(double outerRadius,
1726                         double innerRadius) {
1727                 // 1/2 * (r1^2 + r2^2)
1728                 return (MathUtil.pow2(innerRadius) + MathUtil.pow2(outerRadius)) / 2;
1729         }
1730         
1731         
1732         
1733         ////////////  OTHER
1734         
1735         
1736         /**
1737          * Loads the RocketComponent fields from the given component.  This method is meant
1738          * for in-place replacement of a component.  It is used with the undo/redo
1739          * mechanism and when converting a finset into a freeform fin set.
1740          * This component must not have a parent, otherwise this method will fail.
1741          * <p>
1742          * The child components in the source tree are copied into the current tree, however,
1743          * the original components should not be used since they represent old copies of the
1744          * components.  It is recommended to invalidate them by calling {@link #invalidate()}.
1745          * <p>
1746          * This method returns a list of components that should be invalidated after references
1747          * to them have been removed (for example by firing appropriate events).  The list contains
1748          * all children and sub-children of the current component and the entire component
1749          * tree of <code>src</code>.
1750          *
1751          * @return      a list of components that should not be used after this call.
1752          */
1753         protected List<RocketComponent> copyFrom(RocketComponent src) {
1754                 checkState();
1755                 List<RocketComponent> toInvalidate = new ArrayList<RocketComponent>();
1756                 
1757                 if (this.parent != null) {
1758                         throw new UnsupportedOperationException("copyFrom called for non-root component, parent=" +
1759                                         this.parent.toDebugString() + ", this=" + this.toDebugString());
1760                 }
1761                 
1762                 // Add current structure to be invalidated
1763                 Iterator<RocketComponent> iterator = this.iterator(false);
1764                 while (iterator.hasNext()) {
1765                         toInvalidate.add(iterator.next());
1766                 }
1767                 
1768                 // Remove previous components
1769                 for (RocketComponent child : this.children) {
1770                         child.parent = null;
1771                 }
1772                 this.children.clear();
1773                 
1774                 // Copy new children to this component
1775                 for (RocketComponent c : src.children) {
1776                         RocketComponent copy = c.copyWithOriginalID();
1777                         this.children.add(copy);
1778                         copy.parent = this;
1779                 }
1780                 
1781                 this.checkComponentStructure();
1782                 src.checkComponentStructure();
1783                 
1784                 // Set all parameters
1785                 this.length = src.length;
1786                 this.relativePosition = src.relativePosition;
1787                 this.position = src.position;
1788                 this.color = src.color;
1789                 this.lineStyle = src.lineStyle;
1790                 this.overrideMass = src.overrideMass;
1791                 this.massOverriden = src.massOverriden;
1792                 this.overrideCGX = src.overrideCGX;
1793                 this.cgOverriden = src.cgOverriden;
1794                 this.overrideSubcomponents = src.overrideSubcomponents;
1795                 this.name = src.name;
1796                 this.comment = src.comment;
1797                 this.id = src.id;
1798                 
1799                 // Add source components to invalidation tree
1800                 for (RocketComponent c : src) {
1801                         toInvalidate.add(c);
1802                 }
1803                 
1804                 return toInvalidate;
1805         }
1806         
1807         protected void invalidate() {
1808                 invalidator.invalidate();
1809         }
1810         
1811         
1812         //////////  Iterator implementation  ///////////
1813         
1814         /**
1815          * Private inner class to implement the Iterator.
1816          *
1817          * This iterator is fail-fast if the root of the structure is a Rocket.
1818          */
1819         private static class RocketComponentIterator implements Iterator<RocketComponent> {
1820                 // Stack holds iterators which still have some components left.
1821                 private final Deque<Iterator<RocketComponent>> iteratorStack = new ArrayDeque<Iterator<RocketComponent>>();
1822                 
1823                 private final Rocket root;
1824                 private final int treeModID;
1825                 
1826                 private final RocketComponent original;
1827                 private boolean returnSelf = false;
1828                 
1829                 // Construct iterator with component's child's iterator, if it has elements
1830                 public RocketComponentIterator(RocketComponent c, boolean returnSelf) {
1831                         
1832                         RocketComponent gp = c.getRoot();
1833                         if (gp instanceof Rocket) {
1834                                 root = (Rocket) gp;
1835                                 treeModID = root.getTreeModID();
1836                         } else {
1837                                 root = null;
1838                                 treeModID = -1;
1839                         }
1840                         
1841                         Iterator<RocketComponent> i = c.children.iterator();
1842                         if (i.hasNext())
1843                                 iteratorStack.push(i);
1844                         
1845                         this.original = c;
1846                         this.returnSelf = returnSelf;
1847                 }
1848                 
1849                 @Override
1850                 public boolean hasNext() {
1851                         checkID();
1852                         if (returnSelf)
1853                                 return true;
1854                         return !iteratorStack.isEmpty(); // Elements remain if stack is not empty
1855                 }
1856                 
1857                 @Override
1858                 public RocketComponent next() {
1859                         Iterator<RocketComponent> i;
1860                         
1861                         checkID();
1862                         
1863                         // Return original component first
1864                         if (returnSelf) {
1865                                 returnSelf = false;
1866                                 return original;
1867                         }
1868                         
1869                         // Peek first iterator from stack, throw exception if empty
1870                         i = iteratorStack.peek();
1871                         if (i == null) {
1872                                 throw new NoSuchElementException("No further elements in RocketComponent iterator");
1873                         }
1874                         
1875                         // Retrieve next component of the iterator, remove iterator from stack if empty
1876                         RocketComponent c = i.next();
1877                         if (!i.hasNext())
1878                                 iteratorStack.pop();
1879                         
1880                         // Add iterator of component children to stack if it has children
1881                         i = c.children.iterator();
1882                         if (i.hasNext())
1883                                 iteratorStack.push(i);
1884                         
1885                         return c;
1886                 }
1887                 
1888                 private void checkID() {
1889                         if (root != null) {
1890                                 if (root.getTreeModID() != treeModID) {
1891                                         throw new IllegalStateException("Rocket modified while being iterated");
1892                                 }
1893                         }
1894                 }
1895                 
1896                 @Override
1897                 public void remove() {
1898                         throw new UnsupportedOperationException("remove() not supported by " +
1899                                         "RocketComponent iterator");
1900                 }
1901         }
1902         
1903 }