0b8c4acd299df4aedc6e9af728aeb89514906a0a
[debian/openrocket] / src / net / sf / openrocket / gui / plot / PlotDialog.java
1 package net.sf.openrocket.gui.plot;
2
3 import java.awt.AlphaComposite;
4 import java.awt.Color;
5 import java.awt.Composite;
6 import java.awt.Font;
7 import java.awt.Graphics2D;
8 import java.awt.Image;
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;
22 import java.util.Map;
23
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;
30
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;
41
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;
61
62 public class PlotDialog extends JDialog {
63         
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>();
67         static {
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));
79         }
80
81         private static final Map<FlightEvent.Type, Image> EVENT_IMAGES =
82                 new HashMap<FlightEvent.Type, Image>();
83         static {
84                 loadImage(FlightEvent.Type.LAUNCH, "pix/spheres/red-16x16.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/spheres/green-16x16.png");
90                 loadImage(FlightEvent.Type.STAGE_SEPARATION, "pix/eventicons/event-stage-separation.png");
91                 loadImage(FlightEvent.Type.APOGEE, "pix/eventicons/event-apogee.png");
92                 loadImage(FlightEvent.Type.RECOVERY_DEVICE_DEPLOYMENT, "pix/spheres/blue-16x16.png");
93                 loadImage(FlightEvent.Type.GROUND_HIT, "pix/spheres/gray-16x16.png");
94                 loadImage(FlightEvent.Type.SIMULATION_END, "pix/eventicons/event-simulation-end.png");
95         }
96
97     private static void loadImage(FlightEvent.Type type, String file) {
98         InputStream is;
99  
100         is = ClassLoader.getSystemResourceAsStream(file);
101         if (is == null) {
102                 System.out.println("ERROR: File " + file + " not found!");
103                 return;
104         }
105         
106         try {
107                 Image image = ImageIO.read(is);
108                 EVENT_IMAGES.put(type, image);
109         } catch (IOException ignore) {
110                 ignore.printStackTrace();
111         }
112     }
113     
114     
115     
116     
117     private final List<ModifiedXYItemRenderer> renderers =
118         new ArrayList<ModifiedXYItemRenderer>();
119         
120         private PlotDialog(Window parent, Simulation simulation, PlotConfiguration config) {
121                 super(parent, "Flight data plot");
122                 this.setModalityType(ModalityType.DOCUMENT_MODAL);
123                 
124                 final boolean initialShowPoints = Prefs.getBoolean(Prefs.PLOT_SHOW_POINTS, false);
125                 
126                 
127                 // Fill the auto-selections
128                 FlightDataBranch branch = simulation.getSimulatedData().getBranch(0);
129                 PlotConfiguration filled = config.fillAutoAxes(branch);
130                 List<Axis> axes = filled.getAllAxes();
131
132
133                 // Create the data series for both axes
134                 XYSeriesCollection[] data = new XYSeriesCollection[2];
135                 data[0] = new XYSeriesCollection();
136                 data[1] = new XYSeriesCollection();
137                 
138                 
139                 // Get the domain axis type
140                 final FlightDataBranch.Type domainType = filled.getDomainAxisType();
141                 final Unit domainUnit = filled.getDomainAxisUnit();
142                 if (domainType == null) {
143                         throw new IllegalArgumentException("Domain axis type not specified.");
144                 }
145                 List<Double> x = branch.get(domainType);
146                 
147                 
148                 // Get plot length (ignore trailing NaN's)
149                 int typeCount = filled.getTypeCount();
150                 int dataLength = 0;
151                 for (int i=0; i<typeCount; i++) {
152                         FlightDataBranch.Type type = filled.getType(i);
153                         List<Double> y = branch.get(type);
154                         
155                         for (int j = dataLength; j < y.size(); j++) {
156                                 if (!Double.isNaN(y.get(j)) && !Double.isInfinite(y.get(j)))
157                                         dataLength = j;
158                         }
159                 }
160                 dataLength = Math.min(dataLength, x.size());
161                 
162                 
163                 // Create the XYSeries objects from the flight data and store into the collections
164                 String[] axisLabel = new String[2];
165                 for (int i = 0; i < typeCount; i++) {
166                         // Get info
167                         FlightDataBranch.Type type = filled.getType(i);
168                         Unit unit = filled.getUnit(i);
169                         int axis = filled.getAxis(i);
170                         String name = getLabel(type, unit);
171                         
172                         // Store data in provided units
173                         List<Double> y = branch.get(type);
174                         XYSeries series = new XYSeries(name, false, true);
175                         for (int j=0; j < dataLength; j++) {
176                                 series.add(domainUnit.toUnit(x.get(j)), unit.toUnit(y.get(j)));
177                         }
178                         data[axis].addSeries(series);
179
180                         // Update axis label
181                         if (axisLabel[axis] == null)
182                                 axisLabel[axis] = type.getName();
183                         else
184                                 axisLabel[axis] += "; " + type.getName();
185                 }
186                 
187                 
188                 // Create the chart using the factory to get all default settings
189         JFreeChart chart = ChartFactory.createXYLineChart(
190             "Simulated flight",
191             null, 
192             null, 
193             null,
194             PlotOrientation.VERTICAL,
195             true,
196             true,
197             false
198         );
199                 
200         chart.addSubtitle(new TextTitle(config.getName()));
201         
202                 // Add the data and formatting to the plot
203                 XYPlot plot = chart.getXYPlot();
204                 int axisno = 0;
205                 for (int i=0; i<2; i++) {
206                         // Check whether axis has any data
207                         if (data[i].getSeriesCount() > 0) {
208                                 // Create and set axis
209                                 double min = axes.get(i).getMinValue();
210                                 double max = axes.get(i).getMaxValue();
211                                 NumberAxis axis = new PresetNumberAxis(min, max);
212                                 axis.setLabel(axisLabel[i]);
213 //                              axis.setRange(axes.get(i).getMinValue(), axes.get(i).getMaxValue());
214                                 plot.setRangeAxis(axisno, axis);
215                                 
216                                 // Add data and map to the axis
217                                 plot.setDataset(axisno, data[i]);
218                                 ModifiedXYItemRenderer r = new ModifiedXYItemRenderer();
219                                 r.setBaseShapesVisible(initialShowPoints);
220                                 r.setBaseShapesFilled(true);
221                                 renderers.add(r);
222                                 plot.setRenderer(axisno, r);
223                                 plot.mapDatasetToRangeAxis(axisno, axisno);
224                                 axisno++;
225                         }
226                 }
227                 
228                 plot.getDomainAxis().setLabel(getLabel(domainType,domainUnit));
229                 plot.addDomainMarker(new ValueMarker(0));
230                 plot.addRangeMarker(new ValueMarker(0));
231                 
232                 
233                 
234                 // Create list of events to show (combine event too close to each other)
235                 ArrayList<Double> timeList = new ArrayList<Double>();
236                 ArrayList<String> eventList = new ArrayList<String>();
237                 ArrayList<Color> colorList = new ArrayList<Color>();
238                 ArrayList<Image> imageList = new ArrayList<Image>();
239                 
240                 HashSet<FlightEvent.Type> typeSet = new HashSet<FlightEvent.Type>();
241                 
242                 double prevTime = -100;
243                 String text = null;
244                 Color color = null;
245                 Image image = null;
246                 
247                 List<Pair<Double, FlightEvent>> events = branch.getEvents();
248                 for (int i=0; i < events.size(); i++) {
249                         Pair<Double, FlightEvent> event = events.get(i);
250                         double t = event.getU();
251                         FlightEvent.Type type = event.getV().getType();
252                         
253                         if (type != FlightEvent.Type.ALTITUDE && config.isEventActive(type)) {
254                                 if (Math.abs(t - prevTime) <= 0.01) {
255                                         
256                                         if (!typeSet.contains(type)) {
257                                                 text = text + ", " + event.getV().getType().toString();
258                                                 color = getEventColor(type);
259                                                 image = EVENT_IMAGES.get(type);
260                                                 typeSet.add(type);
261                                         }
262                                         
263                                 } else {
264                                         
265                                         if (text != null) {
266                                                 timeList.add(prevTime);
267                                                 eventList.add(text);
268                                                 colorList.add(color);
269                                                 imageList.add(image);
270                                         }
271                                         prevTime = t;
272                                         text = type.toString();
273                                         color = getEventColor(type);
274                                         image = EVENT_IMAGES.get(type);
275                                         typeSet.clear();
276                                         typeSet.add(type);
277                                         
278                                 }
279                         }
280                 }
281                 if (text != null) {
282                         timeList.add(prevTime);
283                         eventList.add(text);
284                         colorList.add(color);
285                         imageList.add(image);
286                 }
287                 
288                 
289                 // Create the event markers
290                 
291                 if (config.getDomainAxisType() == FlightDataBranch.TYPE_TIME) {
292                         
293                         // Domain time is plotted as vertical markers
294                         for (int i=0; i < eventList.size(); i++) {
295                                 double t = timeList.get(i);
296                                 String event = eventList.get(i);
297                                 color = colorList.get(i);
298                                 
299                                 ValueMarker m = new ValueMarker(t);
300                                 m.setLabel(event);
301                                 m.setPaint(color);
302                                 m.setLabelPaint(color);
303                                 m.setAlpha(0.7f);
304                                 plot.addDomainMarker(m);
305                         }
306                         
307                 } else {
308                         
309                         // Other domains are plotted as image annotations
310                         List<Double> time = branch.get(FlightDataBranch.TYPE_TIME);
311                         List<Double> domain = branch.get(config.getDomainAxisType());
312                         
313                         for (int i=0; i < eventList.size(); i++) {
314                                 final double t = timeList.get(i);
315                                 String event = eventList.get(i);
316                                 image = imageList.get(i);
317                                 
318                                 if (image == null)
319                                         continue;
320                                 
321                                 // Calculate index and interpolation position a
322                                 final double a;
323                                 int tindex = Collections.binarySearch(time, t);
324                                 if (tindex < 0) {
325                                         tindex = -tindex -1;
326                                 }
327                                 if (tindex >= time.size()) {
328                                         // index greater than largest value in time list
329                                         tindex = time.size()-1;
330                                         a = 0;
331                                 } else if (tindex <= 0) {
332                                         // index smaller than smallest value in time list
333                                         tindex = 0;
334                                         a = 0;
335                                 } else {
336                                         assert(tindex > 0);
337                                         tindex--;
338                                         double t1 = time.get(tindex);
339                                         double t2 = time.get(tindex+1);
340                                         
341                                         if ((t1 > t) || (t2 < t)) {
342                                                 throw new RuntimeException("BUG: t1="+t1+" t2="+t2+" t="+t);
343                                         }
344                                         
345                                         if (MathUtil.equals(t1, t2)) {
346                                                 a = 0;
347                                         } else {
348                                                 a = 1 - (t-t1) / (t2-t1);
349                                         }
350                                 }
351                                 
352                                 final double xcoord;
353                                 if (a == 0) {
354                                         xcoord = domain.get(tindex);
355                                 } else {
356                                         xcoord = a * domain.get(tindex) + (1-a) * domain.get(tindex+1);
357                                 }
358                                 
359                                 for (int index = 0; index < config.getTypeCount(); index++) {
360                                         FlightDataBranch.Type type = config.getType(index);
361                                         List<Double> range = branch.get(type);
362                                         
363                                         final double ycoord;
364                                         if (a == 0) {
365                                                 ycoord = range.get(tindex);
366                                         } else {
367                                                 ycoord = a * range.get(tindex) + (1-a) * range.get(tindex+1);
368                                         }
369                                         
370                                         XYImageAnnotation annotation = 
371                                                 new XYImageAnnotation(xcoord, ycoord, image, RectangleAnchor.CENTER);
372                                         annotation.setToolTipText(event);
373                                         plot.addAnnotation(annotation);
374                                 }
375                         }
376                 }
377                 
378                 
379                 // Create the dialog
380                 
381                 JPanel panel = new JPanel(new MigLayout("fill"));
382                 this.add(panel);
383                 
384                 ChartPanel chartPanel = new ChartPanel(chart,
385                                 false, // properties
386                                 true,  // save
387                                 false, // print
388                                 true,  // zoom
389                                 true); // tooltips
390                 chartPanel.setMouseWheelEnabled(true);
391                 chartPanel.setEnforceFileExtensions(true);
392                 chartPanel.setInitialDelay(500);
393                 
394                 chartPanel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
395                 
396                 panel.add(chartPanel, "grow, wrap 20lp");
397                 
398                 final JCheckBox check = new JCheckBox("Show points");
399                 check.setSelected(initialShowPoints);
400                 check.addActionListener(new ActionListener() {
401                         @Override
402                         public void actionPerformed(ActionEvent e) {
403                                 boolean show = check.isSelected();
404                                 Prefs.putBoolean(Prefs.PLOT_SHOW_POINTS, show);
405                                 for (ModifiedXYItemRenderer r: renderers) {
406                                         r.setBaseShapesVisible(show);
407                                 }
408                         }
409                 });
410                 panel.add(check, "split, left");
411                 
412                 panel.add(new JPanel(), "growx");
413
414                 JButton button = new JButton("Close");
415                 button.addActionListener(new ActionListener() {
416                         @Override
417                         public void actionPerformed(ActionEvent e) {
418                                 PlotDialog.this.dispose();
419                         }
420                 });
421                 panel.add(button, "right");
422
423                 this.setLocationByPlatform(true);
424                 this.pack();
425                 GUIUtil.installEscapeCloseOperation(this);
426                 GUIUtil.setDefaultButton(button);
427         }
428         
429         
430         private String getLabel(FlightDataBranch.Type type, Unit unit) {
431                 String name = type.getName();
432                 if (unit != null  &&  !UnitGroup.UNITS_NONE.contains(unit)  &&
433                                 !UnitGroup.UNITS_COEFFICIENT.contains(unit) && unit.getUnit().length() > 0)
434                         name += " ("+unit.getUnit() + ")";
435                 return name;
436         }
437         
438
439         
440         private class PresetNumberAxis extends NumberAxis {
441                 private final double min;
442                 private final double max;
443                 
444                 public PresetNumberAxis(double min, double max) {
445                         this.min = min;
446                         this.max = max;
447                         autoAdjustRange();
448                 }
449                 
450                 @Override
451                 protected void autoAdjustRange() {
452                         this.setRange(min, max);
453                 }
454         }
455         
456         
457         /**
458          * Static method that shows a plot with the specified parameters.
459          * 
460          * @param parent                the parent window, which will be blocked.
461          * @param simulation    the simulation to plot.
462          * @param config                the configuration of the plot.
463          */
464         public static void showPlot(Window parent, Simulation simulation, PlotConfiguration config) {
465                 new PlotDialog(parent, simulation, config).setVisible(true);
466         }
467         
468         
469         
470         private static Color getEventColor(FlightEvent.Type type) {
471                 Color c = EVENT_COLORS.get(type);
472                 if (c != null)
473                         return c;
474                 return DEFAULT_EVENT_COLOR;
475         }
476         
477         
478
479         
480         
481         /**
482          * A modification to the standard renderer that renders the domain marker
483          * labels vertically instead of horizontally.
484          */
485         private static class ModifiedXYItemRenderer extends StandardXYItemRenderer {
486
487                 @Override
488                 public void drawDomainMarker(Graphics2D g2, XYPlot plot, ValueAxis domainAxis,
489                                 Marker marker, Rectangle2D dataArea) {
490
491                         if (!(marker instanceof ValueMarker)) {
492                                 // Use parent for all others
493                                 super.drawDomainMarker(g2, plot, domainAxis, marker, dataArea);
494                                 return;
495                         }
496
497                         /*
498                          * Draw the normal marker, but with rotated text.
499                          * Copied from the overridden method.
500                          */
501                         ValueMarker vm = (ValueMarker) marker;
502                         double value = vm.getValue();
503                         Range range = domainAxis.getRange();
504                         if (!range.contains(value)) {
505                                 return;
506                         }
507
508                         double v = domainAxis.valueToJava2D(value, dataArea, plot.getDomainAxisEdge());
509
510                         PlotOrientation orientation = plot.getOrientation();
511                         Line2D line = null;
512                         if (orientation == PlotOrientation.HORIZONTAL) {
513                                 line = new Line2D.Double(dataArea.getMinX(), v, dataArea.getMaxX(), v);
514                         } else {
515                                 line = new Line2D.Double(v, dataArea.getMinY(), v, dataArea.getMaxY());
516                         }
517
518                         final Composite originalComposite = g2.getComposite();
519                         g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, marker
520                                         .getAlpha()));
521                         g2.setPaint(marker.getPaint());
522                         g2.setStroke(marker.getStroke());
523                         g2.draw(line);
524
525                         String label = marker.getLabel();
526                         RectangleAnchor anchor = marker.getLabelAnchor();
527                         if (label != null) {
528                                 Font labelFont = marker.getLabelFont();
529                                 g2.setFont(labelFont);
530                                 g2.setPaint(marker.getLabelPaint());
531                                 Point2D coordinates = calculateDomainMarkerTextAnchorPoint(g2,
532                                                 orientation, dataArea, line.getBounds2D(), marker
533                                                                 .getLabelOffset(), LengthAdjustmentType.EXPAND, anchor);
534                                 
535                                 // Changed:
536                                 TextAnchor textAnchor = TextAnchor.TOP_RIGHT;
537                                 TextUtilities.drawRotatedString(label, g2, (float) coordinates.getX()+2,
538                                                 (float) coordinates.getY(), textAnchor,
539                                                 -Math.PI/2, textAnchor);
540                         }
541                         g2.setComposite(originalComposite);
542                 }
543
544         }
545
546 }