DGP - 1st printing
[debian/openrocket] / src / net / sf / openrocket / rocketcomponent / Rocket.java
1 package net.sf.openrocket.rocketcomponent;
2
3 import net.sf.openrocket.motor.Motor;
4 import net.sf.openrocket.util.Chars;
5 import net.sf.openrocket.util.Coordinate;
6 import net.sf.openrocket.util.MathUtil;
7
8 import javax.swing.event.ChangeListener;
9 import javax.swing.event.EventListenerList;
10 import java.util.ArrayList;
11 import java.util.Collection;
12 import java.util.Collections;
13 import java.util.HashMap;
14 import java.util.Iterator;
15 import java.util.LinkedList;
16 import java.util.List;
17 import java.util.UUID;
18
19
20 /**
21  * Base for all rocket components.  This is the "starting point" for all rocket trees.
22  * It provides the actual implementations of several methods defined in RocketComponent
23  * (eg. the rocket listener lists) and the methods defined in RocketComponent call these.
24  * It also defines some other methods that concern the whole rocket, and helper methods
25  * that keep information about the program state.
26  * 
27  * @author Sampo Niskanen <sampo.niskanen@iki.fi>
28  */
29
30 public class Rocket extends RocketComponent {
31         public static final double DEFAULT_REFERENCE_LENGTH = 0.01;
32         
33         private static final boolean DEBUG_LISTENERS = false;
34
35         
36         /**
37          * The next modification ID to use.  This variable may only be accessed via
38          * the synchronized {@link #getNextModID()} method!
39          */
40         private static int nextModID = 1;
41
42
43         /**
44          * List of component change listeners.
45          */
46         private EventListenerList listenerList = new EventListenerList();
47         
48         /**
49          * When freezeList != null, events are not dispatched but stored in the list.
50          * When the structure is thawed, a single combined event will be fired.
51          */
52         private List<ComponentChangeEvent> freezeList = null;
53         
54         
55         private int modID;
56         private int massModID;
57         private int aeroModID;
58         private int treeModID;
59         private int functionalModID;
60         
61         
62         private ReferenceType refType = ReferenceType.MAXIMUM;  // Set in constructor
63         private double customReferenceLength = DEFAULT_REFERENCE_LENGTH;
64         
65         
66         // The default configuration used in dialogs
67         private final Configuration defaultConfiguration;
68         
69         
70         private String designer = "";
71         private String revision = "";
72         
73         
74         // Motor configuration list
75         private ArrayList<String> motorConfigurationIDs = new ArrayList<String>();
76         private HashMap<String, String> motorConfigurationNames = new HashMap<String, String>();
77         {
78                 motorConfigurationIDs.add(null);
79         }
80         
81         
82         // Does the rocket have a perfect finish (a notable amount of laminar flow)
83         private boolean perfectFinish = false;
84         
85         
86         
87         /////////////  Constructor  /////////////
88         
89         public Rocket() {
90                 super(RocketComponent.Position.AFTER);
91                 modID = getNextModID();
92                 massModID = modID;
93                 aeroModID = modID;
94                 treeModID = modID;
95                 functionalModID = modID;
96                 defaultConfiguration = new Configuration(this);
97         }
98         
99         
100         
101         public String getDesigner() {
102                 return designer;
103         }
104         
105         public void setDesigner(String s) {
106                 if (s == null)
107                         s = "";
108                 designer = s;
109                 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
110         }
111         
112
113         public String getRevision() {
114                 return revision;
115         }
116         
117         public void setRevision(String s) {
118                 if (s == null)
119                         s = "";
120                 revision = s;
121                 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
122         }
123         
124         
125         
126
127         /**
128          * Return the number of stages in this rocket.
129          * 
130          * @return   the number of stages in this rocket.
131          */
132         public int getStageCount() {
133                 return this.getChildCount();
134         }
135         
136         
137         /**
138          * Return the non-negative modification ID of this rocket.  The ID is changed
139          * every time any change occurs in the rocket.  This can be used to check 
140          * whether it is necessary to void cached data in cases where listeners can not
141          * or should not be used.
142          * <p>
143          * Three other modification IDs are also available, {@link #getMassModID()},
144          * {@link #getAerodynamicModID()} {@link #getTreeModID()}, which change every time 
145          * a mass change, aerodynamic change, or tree change occur.  Even though the values 
146          * of the different modification ID's may be equal, they should be treated totally 
147          * separate.
148          * <p>
149          * Note that undo events restore the modification IDs that were in use at the
150          * corresponding undo level.  Subsequent modifications, however, produce modIDs
151          * distinct from those already used.
152          * 
153          * @return   a unique ID number for this modification state.
154          */
155         public int getModID() {
156                 return modID;
157         }
158         
159         /**
160          * Return the non-negative mass modification ID of this rocket.  See
161          * {@link #getModID()} for details.
162          * 
163          * @return   a unique ID number for this mass-modification state.
164          */
165         public int getMassModID() {
166                 return massModID;
167         }
168         
169         /**
170          * Return the non-negative aerodynamic modification ID of this rocket.  See
171          * {@link #getModID()} for details.
172          * 
173          * @return   a unique ID number for this aerodynamic-modification state.
174          */
175         public int getAerodynamicModID() {
176                 return aeroModID;
177         }
178         
179         /**
180          * Return the non-negative tree modification ID of this rocket.  See
181          * {@link #getModID()} for details.
182          * 
183          * @return   a unique ID number for this tree-modification state.
184          */
185         public int getTreeModID() {
186                 return treeModID;
187         }
188         
189         /**
190          * Return the non-negative functional modificationID of this rocket.
191          * This changes every time a functional change occurs.
192          * 
193          * @return      a unique ID number for this functional modification state.
194          */
195         public int getFunctionalModID() {
196                 return functionalModID;
197         }
198         
199         
200         
201         
202         public ReferenceType getReferenceType() {
203                 return refType;
204         }
205         
206         public void setReferenceType(ReferenceType type) {
207                 if (refType == type)
208                         return;
209                 refType = type;
210                 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
211         }
212         
213         
214         public double getCustomReferenceLength() {
215                 return customReferenceLength;
216         }
217         
218         public void setCustomReferenceLength(double length) {
219                 if (MathUtil.equals(customReferenceLength, length))
220                         return;
221                 
222                 this.customReferenceLength = Math.max(length,0.001);
223                 
224                 if (refType == ReferenceType.CUSTOM) {
225                         fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
226                 }
227         }
228         
229         
230         
231         
232         
233         /**
234          * Set whether the rocket has a perfect finish.  This will affect whether the
235          * boundary layer is assumed to be fully turbulent or not.
236          * 
237          * @param perfectFinish         whether the finish is perfect.
238          */
239         public void setPerfectFinish(boolean perfectFinish) {
240                 if (this.perfectFinish == perfectFinish)
241                         return;
242                 this.perfectFinish = perfectFinish;
243                 fireComponentChangeEvent(ComponentChangeEvent.AERODYNAMIC_CHANGE);
244         }
245
246
247
248         /**
249          * Get whether the rocket has a perfect finish.
250          * 
251          * @return the perfectFinish
252          */
253         public boolean isPerfectFinish() {
254                 return perfectFinish;
255         }
256
257
258
259         /**
260          * Return a new unique modification ID.  This method is thread-safe.
261          * 
262          * @return  a new modification ID unique to this session.
263          */
264         private synchronized int getNextModID() {
265                 return nextModID++;
266         }
267         
268
269         
270         
271         
272         /**
273          * Make a deep copy of the Rocket structure.  This is a helper method which simply 
274          * casts the result of the superclass method to a Rocket.
275          */
276         @SuppressWarnings("unchecked")
277         @Override
278         public Rocket copy() {
279                 Rocket copy = (Rocket)super.copy();
280                 copy.motorConfigurationIDs = (ArrayList<String>) this.motorConfigurationIDs.clone();
281                 copy.motorConfigurationNames = 
282                         (HashMap<String, String>) this.motorConfigurationNames.clone();
283                 copy.resetListeners();
284                 
285                 return copy;
286         }
287         
288         /**
289          * Load the rocket structure from the source.  The method loads the fields of this
290          * Rocket object and copies the references to siblings from the <code>source</code>.
291          * The object <code>source</code> should not be used after this call, as it is in
292          * an illegal state!
293          * <p>
294          * This method is meant to be used in conjunction with undo/redo functionality,
295          * and therefore fires an UNDO_EVENT, masked with all applicable mass/aerodynamic/tree
296          * changes.
297          */
298         @SuppressWarnings("unchecked")
299         public void loadFrom(Rocket r) {
300                 super.copyFrom(r);
301                 
302                 int type = ComponentChangeEvent.UNDO_CHANGE | ComponentChangeEvent.NONFUNCTIONAL_CHANGE;
303                 if (this.massModID != r.massModID)
304                         type |= ComponentChangeEvent.MASS_CHANGE;
305                 if (this.aeroModID != r.aeroModID)
306                         type |= ComponentChangeEvent.AERODYNAMIC_CHANGE;
307                 if (this.treeModID != r.treeModID)
308                         type |= ComponentChangeEvent.TREE_CHANGE;
309                 
310                 this.modID = r.modID;
311                 this.massModID = r.massModID;
312                 this.aeroModID = r.aeroModID;
313                 this.treeModID = r.treeModID;
314                 this.functionalModID = r.functionalModID;
315                 this.refType = r.refType;
316                 this.customReferenceLength = r.customReferenceLength;
317                 
318                 this.motorConfigurationIDs = (ArrayList<String>) r.motorConfigurationIDs.clone();
319                 this.motorConfigurationNames = 
320                         (HashMap<String, String>) r.motorConfigurationNames.clone();
321                 this.perfectFinish = r.perfectFinish;
322                 
323                 String id = defaultConfiguration.getMotorConfigurationID();
324                 if (!this.motorConfigurationIDs.contains(id))
325                         defaultConfiguration.setMotorConfigurationID(null);
326                 
327                 fireComponentChangeEvent(type);
328         }
329
330         
331         
332         
333         ///////  Implement the ComponentChangeListener lists
334         
335         /**
336          * Creates a new EventListenerList for this component.  This is necessary when cloning
337          * the structure.
338          */
339         public void resetListeners() {
340 //              System.out.println("RESETTING LISTENER LIST of Rocket "+this);
341                 listenerList = new EventListenerList();
342         }
343         
344         
345         public void printListeners() {
346                 System.out.println(""+this+" has "+listenerList.getListenerCount()+" listeners:");
347                 Object[] list = listenerList.getListenerList();
348                 for (int i=1; i<list.length; i+=2)
349                         System.out.println("  "+((i+1)/2)+": "+list[i]);
350         }
351         
352         @Override
353         public void addComponentChangeListener(ComponentChangeListener l) {
354                 listenerList.add(ComponentChangeListener.class,l);
355                 if (DEBUG_LISTENERS)
356                         System.out.println(this+": Added listner (now "+listenerList.getListenerCount()+
357                                         " listeners): "+l);
358         }
359         @Override
360         public void removeComponentChangeListener(ComponentChangeListener l) {
361                 listenerList.remove(ComponentChangeListener.class, l);
362                 if (DEBUG_LISTENERS)
363                         System.out.println(this+": Removed listner (now "+listenerList.getListenerCount()+
364                                         " listeners): "+l);
365         }
366         
367
368         @Override
369         public void addChangeListener(ChangeListener l) {
370                 listenerList.add(ChangeListener.class,l);
371                 if (DEBUG_LISTENERS)
372                         System.out.println(this+": Added listner (now "+listenerList.getListenerCount()+
373                                         " listeners): "+l);
374         }
375         @Override
376         public void removeChangeListener(ChangeListener l) {
377                 listenerList.remove(ChangeListener.class, l);
378                 if (DEBUG_LISTENERS)
379                         System.out.println(this+": Removed listner (now "+listenerList.getListenerCount()+
380                                         " listeners): "+l);
381         }
382
383         
384         @Override
385         protected void fireComponentChangeEvent(ComponentChangeEvent e) {
386
387                 // Update modification ID's only for normal (not undo/redo) events
388                 if (!e.isUndoChange()) {
389                         modID = getNextModID();
390                         if (e.isMassChange())
391                                 massModID = modID;
392                         if (e.isAerodynamicChange())
393                                 aeroModID = modID;
394                         if (e.isTreeChange())
395                                 treeModID = modID;
396                         if (e.getType() != ComponentChangeEvent.NONFUNCTIONAL_CHANGE)
397                                 functionalModID = modID;
398                 }
399                 
400                 if (DEBUG_LISTENERS)
401                         System.out.println("FIRING "+e);
402                 
403                 // Check whether frozen
404                 if (freezeList != null) {
405                         freezeList.add(e);
406                         return;
407                 }
408                 
409                 // Notify all components first
410                 Iterator<RocketComponent> iterator = this.deepIterator(true);
411                 while (iterator.hasNext()) {
412                         iterator.next().componentChanged(e);
413                 }
414
415                 // Notify all listeners
416                 Object[] listeners = listenerList.getListenerList();
417                 for (int i = listeners.length-2; i>=0; i-=2) {
418                         if (listeners[i] == ComponentChangeListener.class) {
419                                 ((ComponentChangeListener) listeners[i+1]).componentChanged(e);
420                         } else if (listeners[i] == ChangeListener.class) {
421                                 ((ChangeListener) listeners[i+1]).stateChanged(e);
422                         }
423                 }
424         }
425         
426                 
427         /**
428          * Freezes the rocket structure from firing any events.  This may be performed to
429          * combine several actions on the structure into a single large action.
430          * <code>thaw()</code> must always be called afterwards.
431          * 
432          * NOTE:  Always use a try/finally to ensure <code>thaw()</code> is called:
433          * <pre>
434          *     Rocket r = c.getRocket();
435          *     try {
436          *         r.freeze();
437          *         // do stuff
438          *     } finally {
439          *         r.thaw();
440          *     }
441          * </pre>
442          * 
443          * @see #thaw()
444          */
445         public void freeze() {
446                 if (freezeList == null)
447                         freezeList = new LinkedList<ComponentChangeEvent>();
448         }
449         
450         /**
451          * Thaws a frozen rocket structure and fires a combination of the events fired during
452          * the freeze.  The event type is a combination of those fired and the source is the
453          * last component to have been an event source.
454          *
455          * @see #freeze()
456          */
457         public void thaw() {
458                 if (freezeList == null)
459                         return;
460                 if (freezeList.size()==0) {
461                         freezeList = null;
462                         return;
463                 }
464                 
465                 int type = 0;
466                 Object c = null;
467                 for (ComponentChangeEvent e: freezeList) {
468                         type = type | e.getType();
469                         c = e.getSource();
470                 }
471                 freezeList = null;
472                 
473                 fireComponentChangeEvent(new ComponentChangeEvent((RocketComponent)c,type));
474         }
475         
476         
477
478         
479         ////////  Motor configurations  ////////
480         
481         
482         /**
483          * Return the default configuration.  This should be used in the user interface
484          * to ensure a consistent rocket configuration between dialogs.  It should NOT
485          * be used in simulations not relating to the UI.
486          * 
487          * @return   the default {@link Configuration}.
488          */
489         public Configuration getDefaultConfiguration() {
490                 return defaultConfiguration;
491         }
492         
493         
494         /**
495          * Return an array of the motor configuration IDs.  This array is guaranteed
496          * to contain the <code>null</code> ID as the first element.
497          * 
498          * @return  an array of the motor configuration IDs.
499          */
500         public String[] getMotorConfigurationIDs() {
501                 return motorConfigurationIDs.toArray(new String[0]);
502         }
503         
504         /**
505          * Add a new motor configuration ID to the motor configurations.  The new ID
506          * is returned.
507          * 
508          * @return  the new motor configuration ID.
509          */
510         public String newMotorConfigurationID() {
511                 String id = UUID.randomUUID().toString();
512                 motorConfigurationIDs.add(id);
513                 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
514                 return id;
515         }
516         
517         /**
518          * Add a specified motor configuration ID to the motor configurations.
519          * 
520          * @param id    the motor configuration ID.
521          * @return              true if successful, false if the ID was already used.
522          */
523         public boolean addMotorConfigurationID(String id) {
524                 if (id == null || motorConfigurationIDs.contains(id))
525                         return false;
526                 motorConfigurationIDs.add(id);
527                 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
528                 return true;
529         }
530
531         /**
532          * Remove a motor configuration ID from the configuration IDs.  The <code>null</code>
533          * ID cannot be removed, and an attempt to remove it will be silently ignored.
534          * 
535          * @param id   the motor configuration ID to remove
536          */
537         public void removeMotorConfigurationID(String id) {
538                 if (id == null)
539                         return;
540                 motorConfigurationIDs.remove(id);
541                 fireComponentChangeEvent(ComponentChangeEvent.MOTOR_CHANGE);
542         }
543
544         
545         /**
546          * Check whether <code>id</code> is a valid motor configuration ID.
547          * 
548          * @param id    the configuration ID.
549          * @return              whether a motor configuration with that ID exists.
550          */
551         public boolean isMotorConfigurationID(String id) {
552                 return motorConfigurationIDs.contains(id);
553         }
554         
555         
556         
557         /**
558          * Check whether the given motor configuration ID has motors defined for it.
559          * 
560          * @param id    the motor configuration ID (may be invalid).
561          * @return              whether any motors are defined for it.
562          */
563         public boolean hasMotors(String id) {
564                 if (id == null)
565                         return false;
566                 
567                 Iterator<RocketComponent> iterator = this.deepIterator();
568                 while (iterator.hasNext()) {
569                         RocketComponent c = iterator.next();
570
571                         if (c instanceof MotorMount) {
572                                 MotorMount mount = (MotorMount) c;
573                                 if (!mount.isMotorMount())
574                                         continue;
575                                 if (mount.getMotor(id) != null) {
576                                         return true;
577                                 }
578                         }
579                 }
580                 return false;
581         }
582         
583         
584         /**
585          * Return the user-set name of the motor configuration.  If no name has been set,
586          * returns an empty string (not null).
587          *  
588          * @param id   the motor configuration id
589          * @return         the configuration name
590          */
591         public String getMotorConfigurationName(String id) {
592                 if (!isMotorConfigurationID(id))
593                         return "";
594                 String s = motorConfigurationNames.get(id);
595                 if (s == null)
596                         return "";
597                 return s;
598         }
599         
600         
601         /**
602          * Set the name of the motor configuration.  A name can be unset by passing
603          * <code>null</code> or an empty string.
604          * 
605          * @param id    the motor configuration id
606          * @param name  the name for the motor configuration
607          */
608         public void setMotorConfigurationName(String id, String name) {
609                 motorConfigurationNames.put(id,name);
610                 fireComponentChangeEvent(ComponentChangeEvent.NONFUNCTIONAL_CHANGE);
611         }
612         
613         
614         /**
615          * Return either the motor configuration name (if set) or its description. 
616          * 
617          * @param id  the motor configuration ID.
618          * @return    a textual representation of the configuration
619          */
620         public String getMotorConfigurationNameOrDescription(String id) {
621                 String name;
622                 
623                 name = getMotorConfigurationName(id);
624                 if (name != null  &&  !name.equals(""))
625                         return name;
626
627                 return getMotorConfigurationDescription(id);
628         }
629         
630         /**
631          * Return a description for the motor configuration, generated from the motor 
632          * designations of the components.
633          * 
634          * @param id  the motor configuration ID.
635          * @return    a textual representation of the configuration
636          */
637         @SuppressWarnings("null")
638         public String getMotorConfigurationDescription(String id) {
639                 String name;
640                 int motorCount = 0;
641                 
642                 // Generate the description
643                 
644                 // First iterate over each stage and store the designations of each motor
645                 List<List<String>> list = new ArrayList<List<String>>();
646                 List<String> currentList = null;
647                 
648                 Iterator<RocketComponent> iterator = this.deepIterator();
649                 while (iterator.hasNext()) {
650                         RocketComponent c = iterator.next();
651                         
652                         if (c instanceof Stage) {
653                                 
654                                 currentList = new ArrayList<String>();
655                                 list.add(currentList);
656                                 
657                         } else if (c instanceof MotorMount) {
658                                 
659                                 MotorMount mount = (MotorMount) c;
660                                 Motor motor = mount.getMotor(id);
661                                 
662                                 if (mount.isMotorMount() && motor != null) {
663                                         String designation = motor.getDesignation(mount.getMotorDelay(id));
664                                         
665                                         for (int i=0; i < mount.getMotorCount(); i++) {
666                                                 currentList.add(designation);
667                                                 motorCount++;
668                                         }
669                                 }
670                                 
671                         }
672                 }
673                 
674                 if (motorCount == 0) {
675                         return "[No motors]";
676                 }
677                 
678                 // Change multiple occurrences of a motor to n x motor 
679                 List<String> stages = new ArrayList<String>();
680                 
681                 for (List<String> stage: list) {
682                         String stageName = "";
683                         String previous = null;
684                         int count = 0;
685                         
686                         Collections.sort(stage);
687                         for (String current: stage) {
688                                 if (current.equals(previous)) {
689                                         
690                                         count++;
691                                         
692                                 } else {
693                                         
694                                         if (previous != null) {
695                                                 String s = "";
696                                                 if (count > 1) {
697                                                         s = "" + count + Chars.TIMES + previous;
698                                                 } else {
699                                                         s = previous;
700                                                 }
701                                                 
702                                                 if (stageName.equals(""))
703                                                         stageName = s;
704                                                 else
705                                                         stageName = stageName + "," + s;
706                                         }
707                                         
708                                         previous = current;
709                                         count = 1;
710                                         
711                                 }
712                         }
713                         if (previous != null) {
714                                 String s = "";
715                                 if (count > 1) {
716                                         s = "" + count + Chars.TIMES + previous;
717                                 } else {
718                                         s = previous;
719                                 }
720                                 
721                                 if (stageName.equals(""))
722                                         stageName = s;
723                                 else
724                                         stageName = stageName + "," + s;
725                         }
726                         
727                         stages.add(stageName);
728                 }
729                 
730                 name = "[";
731                 for (int i=0; i < stages.size(); i++) {
732                         String s = stages.get(i);
733                         if (s.equals(""))
734                                 s = "None";
735                         if (i==0)
736                                 name = name + s;
737                         else
738                                 name = name + "; " + s;
739                 }
740                 name += "]";
741                 return name;
742         }
743         
744
745
746         ////////  Obligatory component information
747         
748         
749         @Override
750         public String getComponentName() {
751                 return "Rocket";
752         }
753
754         @Override
755         public Coordinate getComponentCG() {
756                 return new Coordinate(0,0,0,0);
757         }
758
759         @Override
760         public double getComponentMass() {
761                 return 0;
762         }
763
764         @Override
765         public double getLongitudalUnitInertia() {
766                 return 0;
767         }
768
769         @Override
770         public double getRotationalUnitInertia() {
771                 return 0;
772         }
773         
774         @Override
775         public Collection<Coordinate> getComponentBounds() {
776                 return Collections.emptyList();
777         }
778
779         @Override
780         public boolean isAerodynamic() {
781                 return false;
782         }
783
784         @Override
785         public boolean isMassive() {
786                 return false;
787         }
788
789         /**
790          * Allows only <code>Stage</code> components to be added to the type Rocket.
791          */
792         @Override
793         public boolean isCompatible(Class<? extends RocketComponent> type) {
794                 return (Stage.class.isAssignableFrom(type));
795         }
796
797     /**
798      * Accept a visitor to this Rocket in the component hierarchy.
799      * 
800      * @param theVisitor  the visitor that will be called back with a reference to this Rocket
801      */    
802         @Override 
803     public void accept (final ComponentVisitor theVisitor) {
804         theVisitor.visit(this);
805     }    
806 }