1 package net.sf.openrocket.gui.scalefigure;
4 import java.awt.BorderLayout;
5 import java.awt.Dimension;
8 import java.awt.event.ActionEvent;
9 import java.awt.event.InputEvent;
10 import java.awt.event.MouseEvent;
11 import java.util.ArrayList;
12 import java.util.Collection;
13 import java.util.EventListener;
14 import java.util.EventObject;
15 import java.util.List;
16 import java.util.concurrent.Executor;
17 import java.util.concurrent.Executors;
18 import java.util.concurrent.ThreadFactory;
20 import javax.swing.AbstractAction;
21 import javax.swing.Action;
22 import javax.swing.ButtonGroup;
23 import javax.swing.JComboBox;
24 import javax.swing.JLabel;
25 import javax.swing.JPanel;
26 import javax.swing.JSlider;
27 import javax.swing.JToggleButton;
28 import javax.swing.JViewport;
29 import javax.swing.SwingUtilities;
30 import javax.swing.event.TreeSelectionEvent;
31 import javax.swing.event.TreeSelectionListener;
32 import javax.swing.tree.TreePath;
33 import javax.swing.tree.TreeSelectionModel;
35 import net.miginfocom.swing.MigLayout;
36 import net.sf.openrocket.aerodynamics.AerodynamicCalculator;
37 import net.sf.openrocket.aerodynamics.BarrowmanCalculator;
38 import net.sf.openrocket.aerodynamics.FlightConditions;
39 import net.sf.openrocket.aerodynamics.WarningSet;
40 import net.sf.openrocket.document.OpenRocketDocument;
41 import net.sf.openrocket.document.Simulation;
42 import net.sf.openrocket.gui.adaptors.DoubleModel;
43 import net.sf.openrocket.gui.adaptors.MotorConfigurationModel;
44 import net.sf.openrocket.gui.components.BasicSlider;
45 import net.sf.openrocket.gui.components.StageSelector;
46 import net.sf.openrocket.gui.components.UnitSelector;
47 import net.sf.openrocket.gui.configdialog.ComponentConfigDialog;
48 import net.sf.openrocket.gui.figure3d.RocketFigure3d;
49 import net.sf.openrocket.gui.figureelements.CGCaret;
50 import net.sf.openrocket.gui.figureelements.CPCaret;
51 import net.sf.openrocket.gui.figureelements.Caret;
52 import net.sf.openrocket.gui.figureelements.RocketInfo;
53 import net.sf.openrocket.gui.main.SimulationWorker;
54 import net.sf.openrocket.gui.main.componenttree.ComponentTreeModel;
55 import net.sf.openrocket.gui.util.SwingPreferences;
56 import net.sf.openrocket.l10n.Translator;
57 import net.sf.openrocket.masscalc.BasicMassCalculator;
58 import net.sf.openrocket.masscalc.MassCalculator;
59 import net.sf.openrocket.masscalc.MassCalculator.MassCalcType;
60 import net.sf.openrocket.rocketcomponent.Configuration;
61 import net.sf.openrocket.rocketcomponent.Rocket;
62 import net.sf.openrocket.rocketcomponent.RocketComponent;
63 import net.sf.openrocket.rocketcomponent.SymmetricComponent;
64 import net.sf.openrocket.simulation.FlightData;
65 import net.sf.openrocket.simulation.listeners.SimulationListener;
66 import net.sf.openrocket.simulation.listeners.system.ApogeeEndListener;
67 import net.sf.openrocket.simulation.listeners.system.InterruptListener;
68 import net.sf.openrocket.startup.Application;
69 import net.sf.openrocket.unit.UnitGroup;
70 import net.sf.openrocket.util.ChangeSource;
71 import net.sf.openrocket.util.Chars;
72 import net.sf.openrocket.util.Coordinate;
73 import net.sf.openrocket.util.MathUtil;
74 import net.sf.openrocket.util.StateChangeListener;
77 * A JPanel that contains a RocketFigure and buttons to manipulate the figure.
79 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
80 * @author Bill Kuker <bkuker@billkuker.com>
82 public class RocketPanel extends JPanel implements TreeSelectionListener, ChangeSource {
83 private static final long serialVersionUID = 1L;
85 private static final Translator trans = Application.getTranslator();
88 private final RocketFigure figure;
89 private final RocketFigure3d figure3d;
92 private final ScaleScrollPane scrollPane;
94 private final JPanel figureHolder;
96 private JLabel infoMessage;
98 private TreeSelectionModel selectionModel = null;
100 private BasicSlider rotationSlider;
101 ScaleSelector scaleSelector;
104 /* Calculation of CP and CG */
105 private AerodynamicCalculator aerodynamicCalculator;
106 private MassCalculator massCalculator;
109 private final OpenRocketDocument document;
110 private final Configuration configuration;
112 private Caret extraCP = null;
113 private Caret extraCG = null;
114 private RocketInfo extraText = null;
117 private double cpAOA = Double.NaN;
118 private double cpTheta = Double.NaN;
119 private double cpMach = Double.NaN;
120 private double cpRoll = Double.NaN;
122 // The functional ID of the rocket that was simulated
123 private int flightDataFunctionalID = -1;
124 private String flightDataMotorID = null;
127 private SimulationWorker backgroundSimulationWorker = null;
129 private List<EventListener> listeners = new ArrayList<EventListener>();
133 * The executor service used for running the background simulations.
134 * This uses a fixed-sized thread pool for all background simulations
135 * with all threads in daemon mode and with minimum priority.
137 private static final Executor backgroundSimulationExecutor;
139 backgroundSimulationExecutor = Executors.newFixedThreadPool(SwingPreferences.getMaxThreadCount(),
140 new ThreadFactory() {
141 private ThreadFactory factory = Executors.defaultThreadFactory();
144 public Thread newThread(Runnable r) {
145 Thread t = factory.newThread(r);
147 t.setPriority(Thread.MIN_PRIORITY);
154 public RocketPanel(OpenRocketDocument document) {
156 this.document = document;
157 configuration = document.getDefaultConfiguration();
159 // TODO: FUTURE: calculator selection
160 aerodynamicCalculator = new BarrowmanCalculator();
161 massCalculator = new BasicMassCalculator();
163 // Create figure and custom scroll pane
164 figure = new RocketFigure(configuration);
165 figure3d = new RocketFigure3d(configuration);
167 figureHolder = new JPanel(new BorderLayout());
169 scrollPane = new ScaleScrollPane(figure) {
170 private static final long serialVersionUID = 1L;
173 public void mouseClicked(MouseEvent event) {
174 handleMouseClick(event);
177 scrollPane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
178 scrollPane.setFitting(true);
185 configuration.addChangeListener(new StateChangeListener() {
187 public void stateChanged(EventObject e) {
188 // System.out.println("Configuration changed, calling updateFigure");
194 figure3d.addComponentSelectionListener(new RocketFigure3d.ComponentSelectionListener() {
196 public void componentClicked(RocketComponent clicked[], MouseEvent event) {
197 handleComponentClick(clicked, event);
202 private void updateFigures() {
204 figure.updateFigure();
206 figure3d.updateFigure();
209 private void go3D() {
213 figureHolder.remove(scrollPane);
214 figureHolder.add(figure3d, BorderLayout.CENTER);
215 rotationSlider.setEnabled(false);
216 scaleSelector.setEnabled(false);
219 figureHolder.revalidate();
224 private void go2D() {
228 figureHolder.remove(figure3d);
229 figureHolder.add(scrollPane, BorderLayout.CENTER);
230 rotationSlider.setEnabled(true);
231 scaleSelector.setEnabled(true);
233 figureHolder.revalidate();
238 * Creates the layout and components of the panel.
240 private void createPanel() {
241 setLayout(new MigLayout("", "[shrink][grow]", "[shrink][shrink][grow][shrink]"));
243 setPreferredSize(new Dimension(800, 300));
248 ButtonGroup bg = new ButtonGroup();
251 FigureTypeAction action = new FigureTypeAction(RocketFigure.TYPE_SIDE);
253 action.putValue(Action.NAME, trans.get("RocketPanel.FigTypeAct.Sideview"));
255 action.putValue(Action.SHORT_DESCRIPTION, trans.get("RocketPanel.FigTypeAct.ttip.Sideview"));
256 JToggleButton toggle = new JToggleButton(action);
258 add(toggle, "spanx, split");
260 action = new FigureTypeAction(RocketFigure.TYPE_BACK);
262 action.putValue(Action.NAME, trans.get("RocketPanel.FigTypeAct.Backview"));
264 action.putValue(Action.SHORT_DESCRIPTION, trans.get("RocketPanel.FigTypeAct.ttip.Backview"));
265 toggle = new JToggleButton(action);
267 add(toggle, "gap rel");
270 final JToggleButton toggle3d = new JToggleButton(new AbstractAction("3D") {
271 private static final long serialVersionUID = 1L;
273 putValue(Action.NAME, "3D");//TODO
274 putValue(Action.SHORT_DESCRIPTION, "3D"); //TODO
277 public void actionPerformed(ActionEvent e) {
278 if ( ((JToggleButton)e.getSource()).isSelected() ){
286 add(toggle3d, "gap rel");
289 // Zoom level selector
290 scaleSelector = new ScaleSelector(scrollPane);
296 StageSelector stageSelector = new StageSelector(configuration);
297 add(stageSelector, "");
301 // Motor configuration selector
302 //// Motor configuration:
303 JLabel label = new JLabel(trans.get("RocketPanel.lbl.Motorcfg"));
304 label.setHorizontalAlignment(JLabel.RIGHT);
305 add(label, "growx, right");
306 add(new JComboBox(new MotorConfigurationModel(configuration)), "wrap");
312 // Create slider and scroll pane
314 DoubleModel theta = new DoubleModel(figure, "Rotation",
315 UnitGroup.UNITS_ANGLE, 0, 2 * Math.PI);
316 UnitSelector us = new UnitSelector(theta, true);
317 us.setHorizontalAlignment(JLabel.CENTER);
318 add(us, "alignx 50%, growx");
320 // Add the rocket figure
321 add(figureHolder, "grow, spany 2, wmin 300lp, hmin 100lp, wrap");
324 // Add rotation slider
325 // Minimum size to fit "360deg"
326 JLabel l = new JLabel("360" + Chars.DEGREE);
327 Dimension d = l.getPreferredSize();
329 add(rotationSlider = new BasicSlider(theta.getSliderModel(0, 2 * Math.PI), JSlider.VERTICAL, true),
330 "ax 50%, wrap, width " + (d.width + 6) + "px:null:null, growy");
333 //// <html>Click to select Shift+click to select other Double-click to edit Click+drag to move
334 infoMessage = new JLabel(trans.get("RocketPanel.lbl.infoMessage"));
335 infoMessage.setFont(new Font("Sans Serif", Font.PLAIN, 9));
336 add(infoMessage, "skip, span, gapleft 25, wrap");
344 public RocketFigure getFigure() {
348 public AerodynamicCalculator getAerodynamicCalculator() {
349 return aerodynamicCalculator;
352 public Configuration getConfiguration() {
353 return configuration;
357 * Get the center of pressure figure element.
359 * @return center of pressure info
361 public Caret getExtraCP() {
366 * Get the center of gravity figure element.
368 * @return center of gravity info
370 public Caret getExtraCG() {
375 * Get the extra text figure element.
377 * @return extra text that contains info about the rocket design
379 public RocketInfo getExtraText() {
383 public void setSelectionModel(TreeSelectionModel m) {
384 if (selectionModel != null) {
385 selectionModel.removeTreeSelectionListener(this);
388 selectionModel.addTreeSelectionListener(this);
389 valueChanged((TreeSelectionEvent) null); // updates FigureParameters
395 * Return the angle of attack used in CP calculation. NaN signifies the default value
397 * @return the angle of attack used, or NaN.
399 public double getCPAOA() {
404 * Set the angle of attack to be used in CP calculation. A value of NaN signifies that
405 * the default AOA (zero) should be used.
406 * @param aoa the angle of attack to use, or NaN
408 public void setCPAOA(double aoa) {
409 if (MathUtil.equals(aoa, cpAOA) ||
410 (Double.isNaN(aoa) && Double.isNaN(cpAOA)))
418 public double getCPTheta() {
422 public void setCPTheta(double theta) {
423 if (MathUtil.equals(theta, cpTheta) ||
424 (Double.isNaN(theta) && Double.isNaN(cpTheta)))
427 if (!Double.isNaN(theta))
428 figure.setRotation(theta);
434 public double getCPMach() {
438 public void setCPMach(double mach) {
439 if (MathUtil.equals(mach, cpMach) ||
440 (Double.isNaN(mach) && Double.isNaN(cpMach)))
448 public double getCPRoll() {
452 public void setCPRoll(double roll) {
453 if (MathUtil.equals(roll, cpRoll) ||
454 (Double.isNaN(roll) && Double.isNaN(cpRoll)))
465 public void addChangeListener(EventListener listener) {
466 listeners.add(0, listener);
470 public void removeChangeListener(EventListener listener) {
471 listeners.remove(listener);
474 protected void fireChangeEvent() {
475 EventObject e = new EventObject(this);
476 for (EventListener l : listeners) {
477 if ( l instanceof StateChangeListener ) {
478 ((StateChangeListener)l).stateChanged(e);
487 * Handle clicking on figure shapes. The functioning is the following:
489 * Get the components clicked.
490 * If no component is clicked, do nothing.
491 * If the currently selected component is in the set, keep it,
492 * unless the selector specified is pressed. If it is pressed, cycle to
493 * the next component. Otherwise select the first component in the list.
495 public static final int CYCLE_SELECTION_MODIFIER = InputEvent.SHIFT_DOWN_MASK;
497 private void handleMouseClick(MouseEvent event) {
498 if (event.getButton() != MouseEvent.BUTTON1)
500 Point p0 = event.getPoint();
501 Point p1 = scrollPane.getViewport().getViewPosition();
505 RocketComponent[] clicked = figure.getComponentsByPoint(x, y);
507 handleComponentClick(clicked, event);
510 private void handleComponentClick(RocketComponent[] clicked, MouseEvent event){
512 // If no component is clicked, do nothing
513 if (clicked.length == 0)
516 // Check whether the currently selected component is in the clicked components.
517 TreePath path = selectionModel.getSelectionPath();
519 RocketComponent current = (RocketComponent) path.getLastPathComponent();
521 for (int i = 0; i < clicked.length; i++) {
522 if (clicked[i] == current) {
523 if (event.isShiftDown() && (event.getClickCount() == 1)) {
524 path = ComponentTreeModel.makeTreePath(clicked[(i + 1) % clicked.length]);
526 path = ComponentTreeModel.makeTreePath(clicked[i]);
533 // Currently selected component not clicked
535 if (event.isShiftDown() && event.getClickCount() == 1 && clicked.length > 1) {
536 path = ComponentTreeModel.makeTreePath(clicked[1]);
538 path = ComponentTreeModel.makeTreePath(clicked[0]);
542 // Set selection and check for double-click
543 selectionModel.setSelectionPath(path);
544 if (event.getClickCount() == 2) {
545 RocketComponent component = (RocketComponent) path.getLastPathComponent();
547 ComponentConfigDialog.showDialog(SwingUtilities.getWindowAncestor(this),
548 document, component);
556 * Updates the extra data included in the figure. Currently this includes
557 * the CP and CG carets.
559 private WarningSet warnings = new WarningSet();
561 private void updateExtras() {
565 // TODO: MEDIUM: User-definable conditions
566 FlightConditions conditions = new FlightConditions(configuration);
569 if (!Double.isNaN(cpMach)) {
570 conditions.setMach(cpMach);
571 extraText.setMach(cpMach);
573 conditions.setMach(Application.getPreferences().getDefaultMach());
574 extraText.setMach(Application.getPreferences().getDefaultMach());
577 if (!Double.isNaN(cpAOA)) {
578 conditions.setAOA(cpAOA);
580 conditions.setAOA(0);
582 extraText.setAOA(cpAOA);
584 if (!Double.isNaN(cpRoll)) {
585 conditions.setRollRate(cpRoll);
587 conditions.setRollRate(0);
590 if (!Double.isNaN(cpTheta)) {
591 conditions.setTheta(cpTheta);
592 cp = aerodynamicCalculator.getCP(configuration, conditions, warnings);
594 cp = aerodynamicCalculator.getWorstCP(configuration, conditions, warnings);
596 extraText.setTheta(cpTheta);
599 cg = massCalculator.getCG(configuration, MassCalcType.LAUNCH_MASS);
600 // System.out.println("CG computed as "+cg+ " CP as "+cp);
602 if (cp.weight > 0.000001)
607 if (cg.weight > 0.000001)
615 // Length bound is assumed to be tight
616 double length = 0, diameter = 0;
617 Collection<Coordinate> bounds = configuration.getBounds();
618 if (!bounds.isEmpty()) {
619 double minX = Double.POSITIVE_INFINITY, maxX = Double.NEGATIVE_INFINITY;
620 for (Coordinate c : bounds) {
626 length = maxX - minX;
629 for (RocketComponent c : configuration) {
630 if (c instanceof SymmetricComponent) {
631 double d1 = ((SymmetricComponent) c).getForeRadius() * 2;
632 double d2 = ((SymmetricComponent) c).getAftRadius() * 2;
633 diameter = MathUtil.max(diameter, d1, d2);
637 extraText.setCG(cgx);
638 extraText.setCP(cpx);
639 extraText.setLength(length);
640 extraText.setDiameter(diameter);
641 extraText.setMass(cg.weight);
642 extraText.setWarnings(warnings);
645 if (figure.getType() == RocketFigure.TYPE_SIDE && length > 0) {
647 // TODO: LOW: Y-coordinate and rotation
648 extraCP.setPosition(cpx * RocketFigure.EXTRA_SCALE, 0);
649 extraCG.setPosition(cgx * RocketFigure.EXTRA_SCALE, 0);
653 extraCP.setPosition(Double.NaN, Double.NaN);
654 extraCG.setPosition(Double.NaN, Double.NaN);
659 //////// Flight simulation in background
661 // Check whether to compute or not
662 if (!((SwingPreferences) Application.getPreferences()).computeFlightInBackground()) {
663 extraText.setFlightData(null);
664 extraText.setCalculatingData(false);
665 stopBackgroundSimulation();
669 // Check whether data is already up to date
670 if (flightDataFunctionalID == configuration.getRocket().getFunctionalModID() &&
671 flightDataMotorID == configuration.getMotorConfigurationID()) {
675 flightDataFunctionalID = configuration.getRocket().getFunctionalModID();
676 flightDataMotorID = configuration.getMotorConfigurationID();
678 // Stop previous computation (if any)
679 stopBackgroundSimulation();
681 // Check that configuration has motors
682 if (!configuration.hasMotors()) {
683 extraText.setFlightData(FlightData.NaN_DATA);
684 extraText.setCalculatingData(false);
688 // Start calculation process
689 extraText.setCalculatingData(true);
691 Rocket duplicate = (Rocket) configuration.getRocket().copy();
692 Simulation simulation = ((SwingPreferences)Application.getPreferences()).getBackgroundSimulation(duplicate);
693 simulation.getOptions().setMotorConfigurationID(
694 configuration.getMotorConfigurationID());
696 backgroundSimulationWorker = new BackgroundSimulationWorker(simulation);
697 backgroundSimulationExecutor.execute(backgroundSimulationWorker);
701 * Cancels the current background simulation worker, if any.
703 private void stopBackgroundSimulation() {
704 if (backgroundSimulationWorker != null) {
705 backgroundSimulationWorker.cancel(true);
706 backgroundSimulationWorker = null;
712 * A SimulationWorker that simulates the rocket flight in the background and
713 * sets the results to the extra text when finished. The worker can be cancelled
716 private class BackgroundSimulationWorker extends SimulationWorker {
718 public BackgroundSimulationWorker(Simulation sim) {
723 protected FlightData doInBackground() {
725 // Pause a little while to allow faster UI reaction
728 } catch (InterruptedException ignore) {
730 if (isCancelled() || backgroundSimulationWorker != this)
733 return super.doInBackground();
737 protected void simulationDone() {
738 // Do nothing if cancelled
739 if (isCancelled() || backgroundSimulationWorker != this)
742 backgroundSimulationWorker = null;
743 extraText.setFlightData(simulation.getSimulatedData());
744 extraText.setCalculatingData(false);
750 protected SimulationListener[] getExtraListeners() {
751 return new SimulationListener[] {
752 InterruptListener.INSTANCE,
753 ApogeeEndListener.INSTANCE };
757 protected void simulationInterrupted(Throwable t) {
758 // Do nothing on cancel, set N/A data otherwise
759 if (isCancelled() || backgroundSimulationWorker != this) // Double-check
762 backgroundSimulationWorker = null;
763 extraText.setFlightData(FlightData.NaN_DATA);
764 extraText.setCalculatingData(false);
773 * Adds the extra data to the figure. Currently this includes the CP and CG carets.
775 private void addExtras() {
776 extraCG = new CGCaret(0, 0);
777 extraCP = new CPCaret(0, 0);
778 extraText = new RocketInfo(configuration);
781 figure.clearRelativeExtra();
782 figure.addRelativeExtra(extraCP);
783 figure.addRelativeExtra(extraCG);
784 figure.addAbsoluteExtra(extraText);
787 figure3d.clearRelativeExtra();
788 //figure3d.addRelativeExtra(extraCP);
789 //figure3d.addRelativeExtra(extraCG);
790 figure3d.addAbsoluteExtra(extraText);
796 * Updates the selection in the FigureParameters and repaints the figure.
797 * Ignores the event itself.
800 public void valueChanged(TreeSelectionEvent e) {
801 TreePath[] paths = selectionModel.getSelectionPaths();
803 figure.setSelection(null);
807 RocketComponent[] components = new RocketComponent[paths.length];
808 for (int i = 0; i < paths.length; i++)
809 components[i] = (RocketComponent) paths[i].getLastPathComponent();
810 figure.setSelection(components);
812 figure3d.setSelection(components);
818 * An <code>Action</code> that shows whether the figure type is the type
819 * given in the constructor.
821 * @author Sampo Niskanen <sampo.niskanen@iki.fi>
823 private class FigureTypeAction extends AbstractAction implements StateChangeListener {
824 private static final long serialVersionUID = 1L;
825 private final int type;
827 public FigureTypeAction(int type) {
830 figure.addChangeListener(this);
834 public void actionPerformed(ActionEvent e) {
835 boolean state = (Boolean) getValue(Action.SELECTED_KEY);
837 // This view has been selected
838 figure.setType(type);
846 public void stateChanged(EventObject e) {
847 putValue(Action.SELECTED_KEY, figure.getType() == type && !is3d);