1 package net.sf.openrocket.gui.plot;
3 import java.awt.AlphaComposite;
5 import java.awt.Composite;
7 import java.awt.Graphics2D;
9 import java.awt.Window;
10 import java.awt.event.ActionEvent;
11 import java.awt.event.ActionListener;
12 import java.awt.geom.Line2D;
13 import java.awt.geom.Point2D;
14 import java.awt.geom.Rectangle2D;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
24 import javax.imageio.ImageIO;
25 import javax.swing.BorderFactory;
26 import javax.swing.JButton;
27 import javax.swing.JCheckBox;
28 import javax.swing.JDialog;
29 import javax.swing.JPanel;
31 import net.miginfocom.swing.MigLayout;
32 import net.sf.openrocket.document.Simulation;
33 import net.sf.openrocket.simulation.FlightDataBranch;
34 import net.sf.openrocket.simulation.FlightEvent;
35 import net.sf.openrocket.unit.Unit;
36 import net.sf.openrocket.unit.UnitGroup;
37 import net.sf.openrocket.util.GUIUtil;
38 import net.sf.openrocket.util.MathUtil;
39 import net.sf.openrocket.util.Pair;
40 import net.sf.openrocket.util.Prefs;
42 import org.jfree.chart.ChartFactory;
43 import org.jfree.chart.ChartPanel;
44 import org.jfree.chart.JFreeChart;
45 import org.jfree.chart.annotations.XYImageAnnotation;
46 import org.jfree.chart.axis.NumberAxis;
47 import org.jfree.chart.axis.ValueAxis;
48 import org.jfree.chart.plot.Marker;
49 import org.jfree.chart.plot.PlotOrientation;
50 import org.jfree.chart.plot.ValueMarker;
51 import org.jfree.chart.plot.XYPlot;
52 import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
53 import org.jfree.chart.title.TextTitle;
54 import org.jfree.data.Range;
55 import org.jfree.data.xy.XYSeries;
56 import org.jfree.data.xy.XYSeriesCollection;
57 import org.jfree.text.TextUtilities;
58 import org.jfree.ui.LengthAdjustmentType;
59 import org.jfree.ui.RectangleAnchor;
60 import org.jfree.ui.TextAnchor;
62 public class PlotDialog extends JDialog {
64 private static final Color DEFAULT_EVENT_COLOR = new Color(0,0,0);
65 private static final Map<FlightEvent.Type, Color> EVENT_COLORS =
66 new HashMap<FlightEvent.Type, Color>();
68 EVENT_COLORS.put(FlightEvent.Type.LAUNCH, new Color(255,0,0));
69 EVENT_COLORS.put(FlightEvent.Type.LIFTOFF, new Color(0,80,196));
70 EVENT_COLORS.put(FlightEvent.Type.LAUNCHROD, new Color(0,100,80));
71 EVENT_COLORS.put(FlightEvent.Type.IGNITION, new Color(230,130,15));
72 EVENT_COLORS.put(FlightEvent.Type.BURNOUT, new Color(80,55,40));
73 EVENT_COLORS.put(FlightEvent.Type.EJECTION_CHARGE, new Color(80,55,40));
74 EVENT_COLORS.put(FlightEvent.Type.STAGE_SEPARATION, new Color(80,55,40));
75 EVENT_COLORS.put(FlightEvent.Type.APOGEE, new Color(15,120,15));
76 EVENT_COLORS.put(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, new Color(0,0,128));
77 EVENT_COLORS.put(FlightEvent.Type.GROUND_HIT, new Color(0,0,0));
78 EVENT_COLORS.put(FlightEvent.Type.SIMULATION_END, new Color(128,0,0));
81 private static final Map<FlightEvent.Type, Image> EVENT_IMAGES =
82 new HashMap<FlightEvent.Type, Image>();
84 loadImage(FlightEvent.Type.LAUNCH, "pix/eventicons/event-launch.png");
85 loadImage(FlightEvent.Type.LIFTOFF, "pix/eventicons/event-liftoff.png");
86 loadImage(FlightEvent.Type.LAUNCHROD, "pix/eventicons/event-launchrod.png");
87 loadImage(FlightEvent.Type.IGNITION, "pix/eventicons/event-ignition.png");
88 loadImage(FlightEvent.Type.BURNOUT, "pix/eventicons/event-burnout.png");
89 loadImage(FlightEvent.Type.EJECTION_CHARGE,"pix/eventicons/event-ejection-charge.png");
90 loadImage(FlightEvent.Type.STAGE_SEPARATION,
91 "pix/eventicons/event-stage-separation.png");
92 loadImage(FlightEvent.Type.APOGEE, "pix/eventicons/event-apogee.png");
93 loadImage(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT,
94 "pix/eventicons/event-recovery-device-deployment.png");
95 loadImage(FlightEvent.Type.GROUND_HIT, "pix/eventicons/event-ground-hit.png");
96 loadImage(FlightEvent.Type.SIMULATION_END, "pix/eventicons/event-simulation-end.png");
99 private static void loadImage(FlightEvent.Type type, String file) {
102 is = ClassLoader.getSystemResourceAsStream(file);
104 System.out.println("ERROR: File " + file + " not found!");
109 Image image = ImageIO.read(is);
110 EVENT_IMAGES.put(type, image);
111 } catch (IOException ignore) {
112 ignore.printStackTrace();
119 private final List<ModifiedXYItemRenderer> renderers =
120 new ArrayList<ModifiedXYItemRenderer>();
122 private PlotDialog(Window parent, Simulation simulation, PlotConfiguration config) {
123 super(parent, "Flight data plot");
124 this.setModalityType(ModalityType.DOCUMENT_MODAL);
126 final boolean initialShowPoints = Prefs.getBoolean(Prefs.PLOT_SHOW_POINTS, false);
129 // Fill the auto-selections
130 FlightDataBranch branch = simulation.getSimulatedData().getBranch(0);
131 PlotConfiguration filled = config.fillAutoAxes(branch);
132 List<Axis> axes = filled.getAllAxes();
135 // Create the data series for both axes
136 XYSeriesCollection[] data = new XYSeriesCollection[2];
137 data[0] = new XYSeriesCollection();
138 data[1] = new XYSeriesCollection();
141 // Get the domain axis type
142 final FlightDataBranch.Type domainType = filled.getDomainAxisType();
143 final Unit domainUnit = filled.getDomainAxisUnit();
144 if (domainType == null) {
145 throw new IllegalArgumentException("Domain axis type not specified.");
147 List<Double> x = branch.get(domainType);
150 // Get plot length (ignore trailing NaN's)
151 int typeCount = filled.getTypeCount();
153 for (int i=0; i<typeCount; i++) {
154 FlightDataBranch.Type type = filled.getType(i);
155 List<Double> y = branch.get(type);
157 for (int j = dataLength; j < y.size(); j++) {
158 if (!Double.isNaN(y.get(j)) && !Double.isInfinite(y.get(j)))
162 dataLength = Math.min(dataLength, x.size());
165 // Create the XYSeries objects from the flight data and store into the collections
166 String[] axisLabel = new String[2];
167 for (int i = 0; i < typeCount; i++) {
169 FlightDataBranch.Type type = filled.getType(i);
170 Unit unit = filled.getUnit(i);
171 int axis = filled.getAxis(i);
172 String name = getLabel(type, unit);
174 // Store data in provided units
175 List<Double> y = branch.get(type);
176 XYSeries series = new XYSeries(name, false, true);
177 for (int j=0; j < dataLength; j++) {
178 series.add(domainUnit.toUnit(x.get(j)), unit.toUnit(y.get(j)));
180 data[axis].addSeries(series);
183 if (axisLabel[axis] == null)
184 axisLabel[axis] = type.getName();
186 axisLabel[axis] += "; " + type.getName();
190 // Create the chart using the factory to get all default settings
191 JFreeChart chart = ChartFactory.createXYLineChart(
196 PlotOrientation.VERTICAL,
202 chart.addSubtitle(new TextTitle(config.getName()));
204 // Add the data and formatting to the plot
205 XYPlot plot = chart.getXYPlot();
207 for (int i=0; i<2; i++) {
208 // Check whether axis has any data
209 if (data[i].getSeriesCount() > 0) {
210 // Create and set axis
211 double min = axes.get(i).getMinValue();
212 double max = axes.get(i).getMaxValue();
213 NumberAxis axis = new PresetNumberAxis(min, max);
214 axis.setLabel(axisLabel[i]);
215 // axis.setRange(axes.get(i).getMinValue(), axes.get(i).getMaxValue());
216 plot.setRangeAxis(axisno, axis);
218 // Add data and map to the axis
219 plot.setDataset(axisno, data[i]);
220 ModifiedXYItemRenderer r = new ModifiedXYItemRenderer();
221 r.setBaseShapesVisible(initialShowPoints);
222 r.setBaseShapesFilled(true);
224 plot.setRenderer(axisno, r);
225 plot.mapDatasetToRangeAxis(axisno, axisno);
230 plot.getDomainAxis().setLabel(getLabel(domainType,domainUnit));
231 plot.addDomainMarker(new ValueMarker(0));
232 plot.addRangeMarker(new ValueMarker(0));
236 // Create list of events to show (combine event too close to each other)
237 ArrayList<Double> timeList = new ArrayList<Double>();
238 ArrayList<String> eventList = new ArrayList<String>();
239 ArrayList<Color> colorList = new ArrayList<Color>();
240 ArrayList<Image> imageList = new ArrayList<Image>();
242 HashSet<FlightEvent.Type> typeSet = new HashSet<FlightEvent.Type>();
244 double prevTime = -100;
249 List<Pair<Double, FlightEvent>> events = branch.getEvents();
250 for (int i=0; i < events.size(); i++) {
251 Pair<Double, FlightEvent> event = events.get(i);
252 double t = event.getU();
253 FlightEvent.Type type = event.getV().getType();
255 if (type != FlightEvent.Type.ALTITUDE && config.isEventActive(type)) {
256 if (Math.abs(t - prevTime) <= 0.01) {
258 if (!typeSet.contains(type)) {
259 text = text + ", " + event.getV().getType().toString();
260 color = getEventColor(type);
261 image = EVENT_IMAGES.get(type);
268 timeList.add(prevTime);
270 colorList.add(color);
271 imageList.add(image);
274 text = type.toString();
275 color = getEventColor(type);
276 image = EVENT_IMAGES.get(type);
284 timeList.add(prevTime);
286 colorList.add(color);
287 imageList.add(image);
291 // Create the event markers
293 if (config.getDomainAxisType() == FlightDataBranch.TYPE_TIME) {
295 // Domain time is plotted as vertical markers
296 for (int i=0; i < eventList.size(); i++) {
297 double t = timeList.get(i);
298 String event = eventList.get(i);
299 color = colorList.get(i);
301 ValueMarker m = new ValueMarker(t);
304 m.setLabelPaint(color);
306 plot.addDomainMarker(m);
311 // Other domains are plotted as image annotations
312 List<Double> time = branch.get(FlightDataBranch.TYPE_TIME);
313 List<Double> domain = branch.get(config.getDomainAxisType());
315 for (int i=0; i < eventList.size(); i++) {
316 final double t = timeList.get(i);
317 String event = eventList.get(i);
318 image = imageList.get(i);
323 // Calculate index and interpolation position a
325 int tindex = Collections.binarySearch(time, t);
329 if (tindex >= time.size()) {
330 // index greater than largest value in time list
331 tindex = time.size()-1;
333 } else if (tindex <= 0) {
334 // index smaller than smallest value in time list
340 double t1 = time.get(tindex);
341 double t2 = time.get(tindex+1);
343 if ((t1 > t) || (t2 < t)) {
344 throw new RuntimeException("BUG: t1="+t1+" t2="+t2+" t="+t);
347 if (MathUtil.equals(t1, t2)) {
350 a = 1 - (t-t1) / (t2-t1);
356 xcoord = domain.get(tindex);
358 xcoord = a * domain.get(tindex) + (1-a) * domain.get(tindex+1);
361 for (int index = 0; index < config.getTypeCount(); index++) {
362 FlightDataBranch.Type type = config.getType(index);
363 List<Double> range = branch.get(type);
367 ycoord = range.get(tindex);
369 ycoord = a * range.get(tindex) + (1-a) * range.get(tindex+1);
372 XYImageAnnotation annotation =
373 new XYImageAnnotation(xcoord, ycoord, image, RectangleAnchor.CENTER);
374 annotation.setToolTipText(event);
375 plot.addAnnotation(annotation);
383 JPanel panel = new JPanel(new MigLayout("fill"));
386 ChartPanel chartPanel = new ChartPanel(chart,
392 chartPanel.setMouseWheelEnabled(true);
393 chartPanel.setEnforceFileExtensions(true);
394 chartPanel.setInitialDelay(500);
396 chartPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
398 panel.add(chartPanel, "grow, wrap 20lp");
400 final JCheckBox check = new JCheckBox("Show data points");
401 check.setSelected(initialShowPoints);
402 check.addActionListener(new ActionListener() {
404 public void actionPerformed(ActionEvent e) {
405 boolean show = check.isSelected();
406 Prefs.putBoolean(Prefs.PLOT_SHOW_POINTS, show);
407 for (ModifiedXYItemRenderer r: renderers) {
408 r.setBaseShapesVisible(show);
412 panel.add(check, "split, left");
414 panel.add(new JPanel(), "growx");
416 JButton button = new JButton("Close");
417 button.addActionListener(new ActionListener() {
419 public void actionPerformed(ActionEvent e) {
420 PlotDialog.this.dispose();
423 panel.add(button, "right");
425 this.setLocationByPlatform(true);
428 GUIUtil.setDisposableDialogOptions(this, button);
432 private String getLabel(FlightDataBranch.Type type, Unit unit) {
433 String name = type.getName();
434 if (unit != null && !UnitGroup.UNITS_NONE.contains(unit) &&
435 !UnitGroup.UNITS_COEFFICIENT.contains(unit) && unit.getUnit().length() > 0)
436 name += " ("+unit.getUnit() + ")";
442 private class PresetNumberAxis extends NumberAxis {
443 private final double min;
444 private final double max;
446 public PresetNumberAxis(double min, double max) {
453 protected void autoAdjustRange() {
454 this.setRange(min, max);
460 * Static method that shows a plot with the specified parameters.
462 * @param parent the parent window, which will be blocked.
463 * @param simulation the simulation to plot.
464 * @param config the configuration of the plot.
466 public static void showPlot(Window parent, Simulation simulation, PlotConfiguration config) {
467 new PlotDialog(parent, simulation, config).setVisible(true);
472 private static Color getEventColor(FlightEvent.Type type) {
473 Color c = EVENT_COLORS.get(type);
476 return DEFAULT_EVENT_COLOR;
484 * A modification to the standard renderer that renders the domain marker
485 * labels vertically instead of horizontally.
487 private static class ModifiedXYItemRenderer extends StandardXYItemRenderer {
490 public void drawDomainMarker(Graphics2D g2, XYPlot plot, ValueAxis domainAxis,
491 Marker marker, Rectangle2D dataArea) {
493 if (!(marker instanceof ValueMarker)) {
494 // Use parent for all others
495 super.drawDomainMarker(g2, plot, domainAxis, marker, dataArea);
500 * Draw the normal marker, but with rotated text.
501 * Copied from the overridden method.
503 ValueMarker vm = (ValueMarker) marker;
504 double value = vm.getValue();
505 Range range = domainAxis.getRange();
506 if (!range.contains(value)) {
510 double v = domainAxis.valueToJava2D(value, dataArea, plot.getDomainAxisEdge());
512 PlotOrientation orientation = plot.getOrientation();
514 if (orientation == PlotOrientation.HORIZONTAL) {
515 line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v);
517 line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY());
520 final Composite originalComposite = g2.getComposite();
521 g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, marker
523 g2.setPaint(marker.getPaint());
524 g2.setStroke(marker.getStroke());
527 String label = marker.getLabel();
528 RectangleAnchor anchor = marker.getLabelAnchor();
530 Font labelFont = marker.getLabelFont();
531 g2.setFont(labelFont);
532 g2.setPaint(marker.getLabelPaint());
533 Point2D coordinates = calculateDomainMarkerTextAnchorPoint(g2,
534 orientation, dataArea, line.getBounds2D(), marker
535 .getLabelOffset(), LengthAdjustmentType.EXPAND, anchor);
538 TextAnchor textAnchor = TextAnchor.TOP_RIGHT;
539 TextUtilities.drawRotatedString(label, g2, (float) coordinates.getX()+2,
540 (float) coordinates.getY(), textAnchor,
541 -Math.PI/2, textAnchor);
543 g2.setComposite(originalComposite);