1 package net.sf.openrocket.gui.plot;
3 import java.awt.AlphaComposite;
4 import java.awt.BasicStroke;
6 import java.awt.Composite;
8 import java.awt.Graphics2D;
10 import java.awt.Window;
11 import java.awt.event.ActionEvent;
12 import java.awt.event.ActionListener;
13 import java.awt.geom.Line2D;
14 import java.awt.geom.Point2D;
15 import java.awt.geom.Rectangle2D;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.List;
25 import javax.imageio.ImageIO;
26 import javax.swing.BorderFactory;
27 import javax.swing.JButton;
28 import javax.swing.JCheckBox;
29 import javax.swing.JDialog;
30 import javax.swing.JPanel;
32 import net.miginfocom.swing.MigLayout;
33 import net.sf.openrocket.document.Simulation;
34 import net.sf.openrocket.simulation.FlightDataBranch;
35 import net.sf.openrocket.simulation.FlightDataType;
36 import net.sf.openrocket.simulation.FlightEvent;
37 import net.sf.openrocket.unit.Unit;
38 import net.sf.openrocket.unit.UnitGroup;
39 import net.sf.openrocket.util.BugException;
40 import net.sf.openrocket.util.GUIUtil;
41 import net.sf.openrocket.util.MathUtil;
42 import net.sf.openrocket.util.Prefs;
44 import org.jfree.chart.ChartFactory;
45 import org.jfree.chart.ChartPanel;
46 import org.jfree.chart.JFreeChart;
47 import org.jfree.chart.annotations.XYImageAnnotation;
48 import org.jfree.chart.axis.NumberAxis;
49 import org.jfree.chart.axis.ValueAxis;
50 import org.jfree.chart.plot.Marker;
51 import org.jfree.chart.plot.PlotOrientation;
52 import org.jfree.chart.plot.ValueMarker;
53 import org.jfree.chart.plot.XYPlot;
54 import org.jfree.chart.renderer.xy.StandardXYItemRenderer;
55 import org.jfree.chart.title.TextTitle;
56 import org.jfree.data.Range;
57 import org.jfree.data.xy.XYSeries;
58 import org.jfree.data.xy.XYSeriesCollection;
59 import org.jfree.text.TextUtilities;
60 import org.jfree.ui.LengthAdjustmentType;
61 import org.jfree.ui.RectangleAnchor;
62 import org.jfree.ui.TextAnchor;
64 public class PlotDialog extends JDialog {
66 private static final float PLOT_STROKE_WIDTH = 1.5f;
68 private static final Color DEFAULT_EVENT_COLOR = new Color(0, 0, 0);
69 private static final Map<FlightEvent.Type, Color> EVENT_COLORS =
70 new HashMap<FlightEvent.Type, Color>();
72 EVENT_COLORS.put(FlightEvent.Type.LAUNCH, new Color(255, 0, 0));
73 EVENT_COLORS.put(FlightEvent.Type.LIFTOFF, new Color(0, 80, 196));
74 EVENT_COLORS.put(FlightEvent.Type.LAUNCHROD, new Color(0, 100, 80));
75 EVENT_COLORS.put(FlightEvent.Type.IGNITION, new Color(230, 130, 15));
76 EVENT_COLORS.put(FlightEvent.Type.BURNOUT, new Color(80, 55, 40));
77 EVENT_COLORS.put(FlightEvent.Type.EJECTION_CHARGE, new Color(80, 55, 40));
78 EVENT_COLORS.put(FlightEvent.Type.STAGE_SEPARATION, new Color(80, 55, 40));
79 EVENT_COLORS.put(FlightEvent.Type.APOGEE, new Color(15, 120, 15));
80 EVENT_COLORS.put(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, new Color(0, 0, 128));
81 EVENT_COLORS.put(FlightEvent.Type.GROUND_HIT, new Color(0, 0, 0));
82 EVENT_COLORS.put(FlightEvent.Type.SIMULATION_END, new Color(128, 0, 0));
85 private static final Map<FlightEvent.Type, Image> EVENT_IMAGES =
86 new HashMap<FlightEvent.Type, Image>();
88 loadImage(FlightEvent.Type.LAUNCH, "pix/eventicons/event-launch.png");
89 loadImage(FlightEvent.Type.LIFTOFF, "pix/eventicons/event-liftoff.png");
90 loadImage(FlightEvent.Type.LAUNCHROD, "pix/eventicons/event-launchrod.png");
91 loadImage(FlightEvent.Type.IGNITION, "pix/eventicons/event-ignition.png");
92 loadImage(FlightEvent.Type.BURNOUT, "pix/eventicons/event-burnout.png");
93 loadImage(FlightEvent.Type.EJECTION_CHARGE, "pix/eventicons/event-ejection-charge.png");
94 loadImage(FlightEvent.Type.STAGE_SEPARATION,
95 "pix/eventicons/event-stage-separation.png");
96 loadImage(FlightEvent.Type.APOGEE, "pix/eventicons/event-apogee.png");
97 loadImage(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT,
98 "pix/eventicons/event-recovery-device-deployment.png");
99 loadImage(FlightEvent.Type.GROUND_HIT, "pix/eventicons/event-ground-hit.png");
100 loadImage(FlightEvent.Type.SIMULATION_END, "pix/eventicons/event-simulation-end.png");
103 private static void loadImage(FlightEvent.Type type, String file) {
106 is = ClassLoader.getSystemResourceAsStream(file);
108 System.out.println("ERROR: File " + file + " not found!");
113 Image image = ImageIO.read(is);
114 EVENT_IMAGES.put(type, image);
115 } catch (IOException ignore) {
116 ignore.printStackTrace();
123 private final List<ModifiedXYItemRenderer> renderers =
124 new ArrayList<ModifiedXYItemRenderer>();
126 private PlotDialog(Window parent, Simulation simulation, PlotConfiguration config) {
127 super(parent, "Flight data plot");
128 this.setModalityType(ModalityType.DOCUMENT_MODAL);
130 final boolean initialShowPoints = Prefs.getBoolean(Prefs.PLOT_SHOW_POINTS, false);
133 // Fill the auto-selections
134 FlightDataBranch branch = simulation.getSimulatedData().getBranch(0);
135 PlotConfiguration filled = config.fillAutoAxes(branch);
136 List<Axis> axes = filled.getAllAxes();
139 // Create the data series for both axes
140 XYSeriesCollection[] data = new XYSeriesCollection[2];
141 data[0] = new XYSeriesCollection();
142 data[1] = new XYSeriesCollection();
145 // Get the domain axis type
146 final FlightDataType domainType = filled.getDomainAxisType();
147 final Unit domainUnit = filled.getDomainAxisUnit();
148 if (domainType == null) {
149 throw new IllegalArgumentException("Domain axis type not specified.");
151 List<Double> x = branch.get(domainType);
154 // Get plot length (ignore trailing NaN's)
155 int typeCount = filled.getTypeCount();
157 for (int i = 0; i < typeCount; i++) {
158 FlightDataType type = filled.getType(i);
159 List<Double> y = branch.get(type);
161 for (int j = dataLength; j < y.size(); j++) {
162 if (!Double.isNaN(y.get(j)) && !Double.isInfinite(y.get(j)))
166 dataLength = Math.min(dataLength, x.size());
169 // Create the XYSeries objects from the flight data and store into the collections
170 String[] axisLabel = new String[2];
171 for (int i = 0; i < typeCount; i++) {
173 FlightDataType type = filled.getType(i);
174 Unit unit = filled.getUnit(i);
175 int axis = filled.getAxis(i);
176 String name = getLabel(type, unit);
178 // Store data in provided units
179 List<Double> y = branch.get(type);
180 XYSeries series = new XYSeries(name, false, true);
181 for (int j = 0; j < dataLength; j++) {
182 series.add(domainUnit.toUnit(x.get(j)), unit.toUnit(y.get(j)));
184 data[axis].addSeries(series);
187 if (axisLabel[axis] == null)
188 axisLabel[axis] = type.getName();
190 axisLabel[axis] += "; " + type.getName();
194 // Create the chart using the factory to get all default settings
195 JFreeChart chart = ChartFactory.createXYLineChart(
200 PlotOrientation.VERTICAL,
206 chart.addSubtitle(new TextTitle(config.getName()));
208 // Add the data and formatting to the plot
209 XYPlot plot = chart.getXYPlot();
211 for (int i = 0; i < 2; i++) {
212 // Check whether axis has any data
213 if (data[i].getSeriesCount() > 0) {
214 // Create and set axis
215 double min = axes.get(i).getMinValue();
216 double max = axes.get(i).getMaxValue();
217 NumberAxis axis = new PresetNumberAxis(min, max);
218 axis.setLabel(axisLabel[i]);
219 // axis.setRange(axes.get(i).getMinValue(), axes.get(i).getMaxValue());
220 plot.setRangeAxis(axisno, axis);
222 // Add data and map to the axis
223 plot.setDataset(axisno, data[i]);
224 ModifiedXYItemRenderer r = new ModifiedXYItemRenderer();
225 r.setBaseShapesVisible(initialShowPoints);
226 r.setBaseShapesFilled(true);
227 for (int j = 0; j < data[i].getSeriesCount(); j++) {
228 r.setSeriesStroke(j, new BasicStroke(PLOT_STROKE_WIDTH));
231 plot.setRenderer(axisno, r);
232 plot.mapDatasetToRangeAxis(axisno, axisno);
237 plot.getDomainAxis().setLabel(getLabel(domainType, domainUnit));
238 plot.addDomainMarker(new ValueMarker(0));
239 plot.addRangeMarker(new ValueMarker(0));
243 // Create list of events to show (combine event too close to each other)
244 ArrayList<Double> timeList = new ArrayList<Double>();
245 ArrayList<String> eventList = new ArrayList<String>();
246 ArrayList<Color> colorList = new ArrayList<Color>();
247 ArrayList<Image> imageList = new ArrayList<Image>();
249 HashSet<FlightEvent.Type> typeSet = new HashSet<FlightEvent.Type>();
251 double prevTime = -100;
256 List<FlightEvent> events = branch.getEvents();
257 for (int i = 0; i < events.size(); i++) {
258 FlightEvent event = events.get(i);
259 double t = event.getTime();
260 FlightEvent.Type type = event.getType();
262 if (type != FlightEvent.Type.ALTITUDE && config.isEventActive(type)) {
263 if (Math.abs(t - prevTime) <= 0.01) {
265 if (!typeSet.contains(type)) {
266 text = text + ", " + type.toString();
267 color = getEventColor(type);
268 image = EVENT_IMAGES.get(type);
275 timeList.add(prevTime);
277 colorList.add(color);
278 imageList.add(image);
281 text = type.toString();
282 color = getEventColor(type);
283 image = EVENT_IMAGES.get(type);
291 timeList.add(prevTime);
293 colorList.add(color);
294 imageList.add(image);
298 // Create the event markers
300 if (config.getDomainAxisType() == FlightDataType.TYPE_TIME) {
302 // Domain time is plotted as vertical markers
303 for (int i = 0; i < eventList.size(); i++) {
304 double t = timeList.get(i);
305 String event = eventList.get(i);
306 color = colorList.get(i);
308 ValueMarker m = new ValueMarker(t);
311 m.setLabelPaint(color);
313 plot.addDomainMarker(m);
318 // Other domains are plotted as image annotations
319 List<Double> time = branch.get(FlightDataType.TYPE_TIME);
320 List<Double> domain = branch.get(config.getDomainAxisType());
322 for (int i = 0; i < eventList.size(); i++) {
323 final double t = timeList.get(i);
324 String event = eventList.get(i);
325 image = imageList.get(i);
330 // Calculate index and interpolation position a
332 int tindex = Collections.binarySearch(time, t);
334 tindex = -tindex - 1;
336 if (tindex >= time.size()) {
337 // index greater than largest value in time list
338 tindex = time.size() - 1;
340 } else if (tindex <= 0) {
341 // index smaller than smallest value in time list
346 double t1 = time.get(tindex);
347 double t2 = time.get(tindex + 1);
349 if ((t1 > t) || (t2 < t)) {
350 throw new BugException("t1=" + t1 + " t2=" + t2 + " t=" + t);
353 if (MathUtil.equals(t1, t2)) {
356 a = 1 - (t - t1) / (t2 - t1);
362 xcoord = domain.get(tindex);
364 xcoord = a * domain.get(tindex) + (1 - a) * domain.get(tindex + 1);
367 for (int index = 0; index < config.getTypeCount(); index++) {
368 FlightDataType type = config.getType(index);
369 List<Double> range = branch.get(type);
373 ycoord = range.get(tindex);
375 ycoord = a * range.get(tindex) + (1 - a) * range.get(tindex + 1);
378 XYImageAnnotation annotation =
379 new XYImageAnnotation(xcoord, ycoord, image, RectangleAnchor.CENTER);
380 annotation.setToolTipText(event);
381 plot.addAnnotation(annotation);
389 JPanel panel = new JPanel(new MigLayout("fill"));
392 ChartPanel chartPanel = new ChartPanel(chart,
398 chartPanel.setMouseWheelEnabled(true);
399 chartPanel.setEnforceFileExtensions(true);
400 chartPanel.setInitialDelay(500);
402 chartPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
404 panel.add(chartPanel, "grow, wrap 20lp");
406 final JCheckBox check = new JCheckBox("Show data points");
407 check.setSelected(initialShowPoints);
408 check.addActionListener(new ActionListener() {
410 public void actionPerformed(ActionEvent e) {
411 boolean show = check.isSelected();
412 Prefs.putBoolean(Prefs.PLOT_SHOW_POINTS, show);
413 for (ModifiedXYItemRenderer r : renderers) {
414 r.setBaseShapesVisible(show);
418 panel.add(check, "split, left");
420 panel.add(new JPanel(), "growx");
422 JButton button = new JButton("Close");
423 button.addActionListener(new ActionListener() {
425 public void actionPerformed(ActionEvent e) {
426 PlotDialog.this.dispose();
429 panel.add(button, "right");
431 this.setLocationByPlatform(true);
434 GUIUtil.setDisposableDialogOptions(this, button);
438 private String getLabel(FlightDataType type, Unit unit) {
439 String name = type.getName();
440 if (unit != null && !UnitGroup.UNITS_NONE.contains(unit) &&
441 !UnitGroup.UNITS_COEFFICIENT.contains(unit) && unit.getUnit().length() > 0)
442 name += " (" + unit.getUnit() + ")";
448 private class PresetNumberAxis extends NumberAxis {
449 private final double min;
450 private final double max;
452 public PresetNumberAxis(double min, double max) {
459 protected void autoAdjustRange() {
460 this.setRange(min, max);
466 * Static method that shows a plot with the specified parameters.
468 * @param parent the parent window, which will be blocked.
469 * @param simulation the simulation to plot.
470 * @param config the configuration of the plot.
472 public static void showPlot(Window parent, Simulation simulation, PlotConfiguration config) {
473 new PlotDialog(parent, simulation, config).setVisible(true);
478 private static Color getEventColor(FlightEvent.Type type) {
479 Color c = EVENT_COLORS.get(type);
482 return DEFAULT_EVENT_COLOR;
490 * A modification to the standard renderer that renders the domain marker
491 * labels vertically instead of horizontally.
493 private static class ModifiedXYItemRenderer extends StandardXYItemRenderer {
496 public void drawDomainMarker(Graphics2D g2, XYPlot plot, ValueAxis domainAxis,
497 Marker marker, Rectangle2D dataArea) {
499 if (!(marker instanceof ValueMarker)) {
500 // Use parent for all others
501 super.drawDomainMarker(g2, plot, domainAxis, marker, dataArea);
506 * Draw the normal marker, but with rotated text.
507 * Copied from the overridden method.
509 ValueMarker vm = (ValueMarker) marker;
510 double value = vm.getValue();
511 Range range = domainAxis.getRange();
512 if (!range.contains(value)) {
516 double v = domainAxis.valueToJava2D(value, dataArea, plot.getDomainAxisEdge());
518 PlotOrientation orientation = plot.getOrientation();
520 if (orientation == PlotOrientation.HORIZONTAL) {
521 line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v);
523 line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY());
526 final Composite originalComposite = g2.getComposite();
527 g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, marker
529 g2.setPaint(marker.getPaint());
530 g2.setStroke(marker.getStroke());
533 String label = marker.getLabel();
534 RectangleAnchor anchor = marker.getLabelAnchor();
536 Font labelFont = marker.getLabelFont();
537 g2.setFont(labelFont);
538 g2.setPaint(marker.getLabelPaint());
539 Point2D coordinates = calculateDomainMarkerTextAnchorPoint(g2,
540 orientation, dataArea, line.getBounds2D(), marker
541 .getLabelOffset(), LengthAdjustmentType.EXPAND, anchor);
544 TextAnchor textAnchor = TextAnchor.TOP_RIGHT;
545 TextUtilities.drawRotatedString(label, g2, (float) coordinates.getX() + 2,
546 (float) coordinates.getY(), textAnchor,
547 -Math.PI / 2, textAnchor);
549 g2.setComposite(originalComposite);