DGP - design report figure honors rotation angle of main figure; added rocksim consta...
[debian/openrocket] / core / src / net / sf / openrocket / gui / print / DesignReport.java
1 /*
2  * DesignReport.java
3  */
4 package net.sf.openrocket.gui.print;
5
6 import java.awt.Graphics2D;
7 import java.io.IOException;
8 import java.text.DecimalFormat;
9
10 import net.sf.openrocket.document.OpenRocketDocument;
11 import net.sf.openrocket.document.Simulation;
12 import net.sf.openrocket.gui.figureelements.FigureElement;
13 import net.sf.openrocket.gui.figureelements.RocketInfo;
14 import net.sf.openrocket.gui.scalefigure.RocketPanel;
15 import net.sf.openrocket.gui.util.SwingPreferences;
16 import net.sf.openrocket.logging.LogHelper;
17 import net.sf.openrocket.masscalc.BasicMassCalculator;
18 import net.sf.openrocket.masscalc.MassCalculator;
19 import net.sf.openrocket.masscalc.MassCalculator.MassCalcType;
20 import net.sf.openrocket.motor.Motor;
21 import net.sf.openrocket.rocketcomponent.Configuration;
22 import net.sf.openrocket.rocketcomponent.MotorMount;
23 import net.sf.openrocket.rocketcomponent.Rocket;
24 import net.sf.openrocket.rocketcomponent.RocketComponent;
25 import net.sf.openrocket.rocketcomponent.Stage;
26 import net.sf.openrocket.simulation.FlightData;
27 import net.sf.openrocket.simulation.exception.SimulationException;
28 import net.sf.openrocket.startup.Application;
29 import net.sf.openrocket.unit.Unit;
30 import net.sf.openrocket.unit.UnitGroup;
31 import net.sf.openrocket.util.Chars;
32 import net.sf.openrocket.util.Coordinate;
33
34 import com.itextpdf.text.Document;
35 import com.itextpdf.text.DocumentException;
36 import com.itextpdf.text.Element;
37 import com.itextpdf.text.Paragraph;
38 import com.itextpdf.text.Rectangle;
39 import com.itextpdf.text.pdf.BaseFont;
40 import com.itextpdf.text.pdf.DefaultFontMapper;
41 import com.itextpdf.text.pdf.PdfContentByte;
42 import com.itextpdf.text.pdf.PdfPCell;
43 import com.itextpdf.text.pdf.PdfPTable;
44 import com.itextpdf.text.pdf.PdfWriter;
45
46 /**
47  * <pre>
48  * #  Title # Section describing the rocket in general without motors
49  * # Section describing the rocket in general without motors
50  * <p/>
51  * design name
52  * empty mass & CG
53  * CP position
54  * CP position at 5 degree AOA (or similar)
55  * number of stages
56  * parachute/streamer sizes
57  * max. diameter (caliber)
58  * velocity at exit of rail/rod
59  * minimum safe velocity reached in x inches/cm
60  * <p/>
61  * # Section for each motor configuration
62  * <p/>
63  * a summary of the motors, e.g. 3xC6-0; B4-6
64  * a list of the motors including the manufacturer, designation (maybe also info like burn time, grams of propellant,
65  * total impulse)
66  * total grams of propellant
67  * total impulse
68  * takeoff weight
69  * CG and CP position, stability margin
70  * predicted flight altitude, max. velocity and max. acceleration
71  * predicted velocity at chute deployment
72  * predicted descent rate
73  * Thrust to Weight Ratio of each stage
74  * <p/>
75  * </pre>
76  */
77 public class DesignReport {
78         
79         /**
80          * The logger.
81          */
82         private static final LogHelper log = Application.getLogger();
83     public static final double SCALE_FUDGE_FACTOR = 0.4d;
84
85     /**
86          * The OR Document.
87          */
88         private OpenRocketDocument rocketDocument;
89         
90         /**
91          * A panel used for rendering of the design diagram.
92          */
93         final RocketPanel panel;
94         
95         /**
96          * The iText document.
97          */
98         protected Document document;
99
100     /**
101      * The figure rotation.
102      */
103     private double rotation = 0d;
104
105         /** The displayed strings. */
106         private static final String STAGES = "Stages: ";
107         private static final String MASS_WITH_MOTORS = "Mass (with motors): ";
108         private static final String MASS_WITH_MOTOR = "Mass (with motor): ";
109         private static final String MASS_EMPTY = "Mass (Empty): ";
110         private static final String STABILITY = "Stability: ";
111         private static final String CG = "CG: ";
112         private static final String CP = "CP: ";
113         private static final String MOTOR = "Motor";
114         private static final String AVG_THRUST = "Avg Thrust";
115         private static final String BURN_TIME = "Burn Time";
116         private static final String MAX_THRUST = "Max Thrust";
117         private static final String TOTAL_IMPULSE = "Total Impulse";
118         private static final String THRUST_TO_WT = "Thrust to Wt";
119         private static final String PROPELLANT_WT = "Propellant Wt";
120         private static final String SIZE = "Size";
121         private static final String ALTITUDE = "Altitude";
122         private static final String FLIGHT_TIME = "Flight Time";
123         private static final String TIME_TO_APOGEE = "Time to Apogee";
124         private static final String VELOCITY_OFF_PAD = "Velocity off Pad";
125         private static final String MAX_VELOCITY = "Max Velocity";
126         private static final String DEPLOYMENT_VELOCITY = "Velocity at Deployment";
127         private static final String LANDING_VELOCITY = "Landing Velocity";
128         private static final String ROCKET_DESIGN = "Rocket Design";
129         private static final double GRAVITY_CONSTANT = 9.80665d;
130         
131         /**
132          * Constructor.
133          *
134          * @param theRocDoc the OR document
135          * @param theIDoc   the iText document
136      * @param figureRotation the angle the figure is rotated on the screen; printed report will mimic
137          */
138         public DesignReport(OpenRocketDocument theRocDoc, Document theIDoc, Double figureRotation) {
139                 document = theIDoc;
140                 rocketDocument = theRocDoc;
141                 panel = new RocketPanel(rocketDocument);
142         rotation = figureRotation;
143         }
144         
145         /**
146          * Main entry point.  Prints the rocket drawing and design data.
147          *
148          * @param writer a direct byte writer
149          */
150         public void writeToDocument(PdfWriter writer) {
151                 if (writer == null) {
152                         return;
153                 }
154                 com.itextpdf.text.Rectangle pageSize = document.getPageSize();
155                 int pageImageableWidth = (int) pageSize.getWidth() - (int) pageSize.getBorderWidth() * 2;
156                 int pageImageableHeight = (int) pageSize.getHeight() / 2 - (int) pageSize.getBorderWidthTop();
157                 
158                 PrintUtilities.addText(document, PrintUtilities.BIG_BOLD, ROCKET_DESIGN);
159                 
160                 Rocket rocket = rocketDocument.getRocket();
161                 final Configuration configuration = rocket.getDefaultConfiguration().clone();
162                 configuration.setAllStages();
163                 PdfContentByte canvas = writer.getDirectContent();
164                 
165                 final PrintFigure figure = new PrintFigure(configuration);
166         figure.setRotation(rotation);
167                 
168                 FigureElement cp = panel.getExtraCP();
169                 FigureElement cg = panel.getExtraCG();
170                 RocketInfo text = panel.getExtraText();
171                 
172                 double scale = paintRocketDiagram(pageImageableWidth, pageImageableHeight, canvas, figure, cp, cg);
173                 
174                 canvas.beginText();
175                 try {
176                         canvas.setFontAndSize(BaseFont.createFont(PrintUtilities.NORMAL.getFamilyname(), BaseFont.CP1252,
177                                                                                                                 BaseFont.EMBEDDED), PrintUtilities.NORMAL_FONT_SIZE);
178                 } catch (DocumentException e) {
179                         log.error("Could not set font.", e);
180                 } catch (IOException e) {
181                         log.error("Could not create font.", e);
182                 }
183                 int figHeightPts = (int) (PrintUnit.METERS.toPoints(figure.getFigureHeight()) * 0.4 * (scale / PrintUnit.METERS
184                                 .toPoints(1)));
185                 final int diagramHeight = pageImageableHeight * 2 - 70 - (figHeightPts);
186                 canvas.moveText(document.leftMargin() + pageSize.getBorderWidthLeft(), diagramHeight);
187                 canvas.moveTextWithLeading(0, -16);
188                 
189                 float initialY = canvas.getYTLM();
190                 
191                 canvas.showText(rocketDocument.getRocket().getName());
192                 
193                 canvas.newlineShowText(STAGES);
194                 canvas.showText("" + rocket.getStageCount());
195                 
196
197                 if (configuration.hasMotors()) {
198                         if (configuration.getStageCount() > 1) {
199                                 canvas.newlineShowText(MASS_WITH_MOTORS);
200                         } else {
201                                 canvas.newlineShowText(MASS_WITH_MOTOR);
202                         }
203                 } else {
204                         canvas.newlineShowText(MASS_EMPTY);
205                 }
206                 canvas.showText(text.getMass(UnitGroup.UNITS_MASS.getDefaultUnit()));
207                 
208                 canvas.newlineShowText(STABILITY);
209                 canvas.showText(text.getStability());
210                 
211                 canvas.newlineShowText(CG);
212                 canvas.showText(text.getCg());
213                 
214                 canvas.newlineShowText(CP);
215                 canvas.showText(text.getCp());
216                 canvas.endText();
217                 
218                 try {
219                         //Move the internal pointer of the document below that of what was just written using the direct byte buffer.
220                         Paragraph paragraph = new Paragraph();
221                         float finalY = canvas.getYTLM();
222                         int heightOfDiagramAndText = (int) (pageSize.getHeight() - (finalY - initialY + diagramHeight));
223                         
224                         paragraph.setSpacingAfter(heightOfDiagramAndText);
225                         document.add(paragraph);
226                         
227                         String[] motorIds = rocket.getMotorConfigurationIDs();
228                         
229                         for (int j = 0; j < motorIds.length; j++) {
230                                 String motorId = motorIds[j];
231                                 if (motorId != null) {
232                                         PdfPTable parent = new PdfPTable(2);
233                                         parent.setWidthPercentage(100);
234                                         parent.setHorizontalAlignment(Element.ALIGN_LEFT);
235                                         parent.setSpacingBefore(0);
236                                         parent.setWidths(new int[] { 1, 3 });
237                                         int leading = 0;
238                                         //The first motor config is always null.  Skip it and the top-most motor, then set the leading.
239                                         if (j > 1) {
240                                                 leading = 25;
241                                         }
242                                         addFlightData(rocket, motorId, parent, leading);
243                                         addMotorData(rocket, motorId, parent);
244                                         document.add(parent);
245                                 }
246                         }
247                 } catch (DocumentException e) {
248                         log.error("Could not modify document.", e);
249                 }
250         }
251         
252         
253         /**
254          * Paint a diagram of the rocket into the PDF document.
255          *
256          * @param thePageImageableWidth  the number of points in the width of the page available for drawing
257          * @param thePageImageableHeight the number of points in the height of the page available for drawing
258          * @param theCanvas              the direct byte writer
259          * @param theFigure              the print figure
260          * @param theCp                  the center of pressure figure element
261          * @param theCg                  the center of gravity figure element
262          *
263          * @return the scale of the diagram
264          */
265         private double paintRocketDiagram(final int thePageImageableWidth, final int thePageImageableHeight,
266                                                                                 final PdfContentByte theCanvas, final PrintFigure theFigure,
267                                                                                 final FigureElement theCp, final FigureElement theCg) {
268                 theFigure.clearAbsoluteExtra();
269                 theFigure.clearRelativeExtra();
270                 theFigure.addRelativeExtra(theCp);
271                 theFigure.addRelativeExtra(theCg);
272                 theFigure.updateFigure();
273                 
274                 double scale =
275                                 (thePageImageableWidth * 2.2) / theFigure.getFigureWidth();
276                 theFigure.setScale(scale);
277                 /*
278                  * page dimensions are in points-per-inch, which, in Java2D, are the same as pixels-per-inch; thus we don't need any conversion
279                  */
280                 theFigure.setSize(thePageImageableWidth, thePageImageableHeight);
281                 theFigure.updateFigure();
282
283                 final DefaultFontMapper mapper = new DefaultFontMapper();
284                 Graphics2D g2d = theCanvas.createGraphics(thePageImageableWidth, thePageImageableHeight * 2, mapper);
285         final double halfFigureHeight = SCALE_FUDGE_FACTOR * theFigure.getFigureHeightPx()/2;
286         int y = PrintUnit.POINTS_PER_INCH;
287         //If the y dimension is negative, then it will potentially be drawn off the top of the page.  Move the origin
288         //to allow for this.
289         if (theFigure.getDimensions().getY() < 0.0d) {
290             y += (int)halfFigureHeight;
291         }
292         g2d.translate(20, y);
293
294                 g2d.scale(SCALE_FUDGE_FACTOR, SCALE_FUDGE_FACTOR);
295                 theFigure.paint(g2d);
296                 g2d.dispose();
297                 return scale;
298         }
299         
300         /**
301          * Add the motor data for a motor configuration to the table.
302          *
303          * @param rocket        the rocket
304          * @param motorId       the motor ID to output
305          * @param parent        the parent to which the motor data will be added
306          */
307         private void addMotorData(Rocket rocket, String motorId, final PdfPTable parent) {
308                 
309                 PdfPTable motorTable = new PdfPTable(8);
310                 motorTable.setWidthPercentage(68);
311                 motorTable.setHorizontalAlignment(Element.ALIGN_LEFT);
312                 
313                 final PdfPCell motorCell = ITextHelper.createCell(MOTOR, PdfPCell.BOTTOM);
314                 final int mPad = 10;
315                 motorCell.setPaddingLeft(mPad);
316                 motorTable.addCell(motorCell);
317                 motorTable.addCell(ITextHelper.createCell(AVG_THRUST, PdfPCell.BOTTOM));
318                 motorTable.addCell(ITextHelper.createCell(BURN_TIME, PdfPCell.BOTTOM));
319                 motorTable.addCell(ITextHelper.createCell(MAX_THRUST, PdfPCell.BOTTOM));
320                 motorTable.addCell(ITextHelper.createCell(TOTAL_IMPULSE, PdfPCell.BOTTOM));
321                 motorTable.addCell(ITextHelper.createCell(THRUST_TO_WT, PdfPCell.BOTTOM));
322                 motorTable.addCell(ITextHelper.createCell(PROPELLANT_WT, PdfPCell.BOTTOM));
323                 motorTable.addCell(ITextHelper.createCell(SIZE, PdfPCell.BOTTOM));
324                 
325                 DecimalFormat ttwFormat = new DecimalFormat("0.00");
326                 
327                 MassCalculator massCalc = new BasicMassCalculator();
328                 
329                 Configuration config = new Configuration(rocket);
330                 config.setMotorConfigurationID(motorId);
331                 
332                 int totalMotorCount = 0;
333                 double totalPropMass = 0;
334                 double totalImpulse = 0;
335                 double totalTTW = 0;
336                 
337                 int stage = 0;
338                 double stageMass = 0;
339                 
340                 boolean topBorder = false;
341                 for (RocketComponent c : rocket) {
342                         
343                         if (c instanceof Stage) {
344                                 config.setToStage(stage);
345                                 stage++;
346                                 stageMass = massCalc.getCG(config, MassCalcType.LAUNCH_MASS).weight;
347                                 // Calculate total thrust-to-weight from only lowest stage motors
348                                 totalTTW = 0;
349                                 topBorder = true;
350                         }
351                         
352                         if (c instanceof MotorMount && ((MotorMount) c).isMotorMount()) {
353                                 MotorMount mount = (MotorMount) c;
354                                 
355                                 if (mount.isMotorMount() && mount.getMotor(motorId) != null) {
356                                         Motor motor = mount.getMotor(motorId);
357                                         int motorCount = c.toAbsolute(Coordinate.NUL).length;
358                                         
359
360                                         int border = Rectangle.NO_BORDER;
361                                         if (topBorder) {
362                                                 border = Rectangle.TOP;
363                                                 topBorder = false;
364                                         }
365                                         
366                                         String name = motor.getDesignation();
367                                         if (motorCount > 1) {
368                                                 name += " (" + Chars.TIMES + motorCount + ")";
369                                         }
370                                         
371                                         final PdfPCell motorVCell = ITextHelper.createCell(name, border);
372                                         motorVCell.setPaddingLeft(mPad);
373                                         motorTable.addCell(motorVCell);
374                                         motorTable.addCell(ITextHelper.createCell(
375                                                         UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit(motor.getAverageThrustEstimate()), border));
376                                         motorTable.addCell(ITextHelper.createCell(
377                                                         UnitGroup.UNITS_FLIGHT_TIME.getDefaultUnit().toStringUnit(motor.getBurnTimeEstimate()), border));
378                                         motorTable.addCell(ITextHelper.createCell(
379                                                         UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit(motor.getMaxThrustEstimate()), border));
380                                         motorTable.addCell(ITextHelper.createCell(
381                                                         UnitGroup.UNITS_IMPULSE.getDefaultUnit().toStringUnit(motor.getTotalImpulseEstimate()), border));
382                                         
383                                         double ttw = motor.getAverageThrustEstimate() / (stageMass * GRAVITY_CONSTANT);
384                                         motorTable.addCell(ITextHelper.createCell(
385                                                         ttwFormat.format(ttw) + ":1", border));
386                                         
387                                         double propMass = (motor.getLaunchCG().weight - motor.getEmptyCG().weight);
388                                         motorTable.addCell(ITextHelper.createCell(
389                                                         UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit(propMass), border));
390                                         
391                                         final Unit motorUnit = UnitGroup.UNITS_MOTOR_DIMENSIONS.getDefaultUnit();
392                                         motorTable.addCell(ITextHelper.createCell(motorUnit.toString(motor.getDiameter()) +
393                                                                                                                                 "/" +
394                                                                                                                                 motorUnit.toString(motor.getLength()) + " " +
395                                                                                                                                 motorUnit.toString(), border));
396                                         
397                                         // Sum up total count
398                                         totalMotorCount += motorCount;
399                                         totalPropMass += propMass * motorCount;
400                                         totalImpulse += motor.getTotalImpulseEstimate() * motorCount;
401                                         totalTTW += ttw * motorCount;
402                                 }
403                         }
404                 }
405                 
406                 if (totalMotorCount > 1) {
407                         int border = Rectangle.TOP;
408                         final PdfPCell motorVCell = ITextHelper.createCell("Total:", border);
409                         motorVCell.setPaddingLeft(mPad);
410                         motorTable.addCell(motorVCell);
411                         motorTable.addCell(ITextHelper.createCell("", border));
412                         motorTable.addCell(ITextHelper.createCell("", border));
413                         motorTable.addCell(ITextHelper.createCell("", border));
414                         motorTable.addCell(ITextHelper.createCell(
415                                                 UnitGroup.UNITS_IMPULSE.getDefaultUnit().toStringUnit(totalImpulse), border));
416                         motorTable.addCell(ITextHelper.createCell(
417                                         ttwFormat.format(totalTTW) + ":1", border));
418                         motorTable.addCell(ITextHelper.createCell(
419                                                 UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit(totalPropMass), border));
420                         motorTable.addCell(ITextHelper.createCell("", border));
421                         
422                 }
423                 
424                 PdfPCell c = new PdfPCell(motorTable);
425                 c.setBorder(PdfPCell.LEFT);
426                 c.setBorderWidthTop(0f);
427                 parent.addCell(c);
428         }
429         
430         
431         /**
432          * Add the motor data for a motor configuration to the table.
433          *
434          * @param theRocket the rocket
435          * @param motorId   a motor configuration id
436          * @param parent    the parent to which the motor data will be added
437          * @param leading   the number of points for the leading
438          */
439         private void addFlightData(final Rocket theRocket, final String motorId, final PdfPTable parent, int leading) {
440                 
441                 // Perform flight simulation
442                 Rocket duplicate = theRocket.copyWithOriginalID();
443                 FlightData flight = null;
444                 try {
445                         Simulation simulation = ((SwingPreferences)Application.getPreferences()).getBackgroundSimulation(duplicate);
446                         simulation.getOptions().setMotorConfigurationID(motorId);
447                         simulation.simulate();
448                         flight = simulation.getSimulatedData();
449                 } catch (SimulationException e1) {
450                         // Ignore
451                 }
452                 
453                 // Output the flight data
454                 if (flight != null) {
455                         try {
456                                 final Unit distanceUnit = UnitGroup.UNITS_DISTANCE.getDefaultUnit();
457                                 final Unit velocityUnit = UnitGroup.UNITS_VELOCITY.getDefaultUnit();
458                                 final Unit flightTimeUnit = UnitGroup.UNITS_FLIGHT_TIME.getDefaultUnit();
459                                 
460                                 PdfPTable labelTable = new PdfPTable(2);
461                                 labelTable.setWidths(new int[] { 3, 2 });
462                                 final Paragraph chunk = ITextHelper.createParagraph(stripBrackets(
463                                                         theRocket.getMotorConfigurationNameOrDescription(motorId)), PrintUtilities.BOLD);
464                                 chunk.setLeading(leading);
465                                 chunk.setSpacingAfter(3f);
466                                 
467                                 document.add(chunk);
468                                 
469                                 final PdfPCell cell = ITextHelper.createCell(ALTITUDE, 2, 2);
470                                 cell.setUseBorderPadding(false);
471                                 cell.setBorderWidthTop(0f);
472                                 labelTable.addCell(cell);
473                                 labelTable.addCell(ITextHelper.createCell(distanceUnit.toStringUnit(flight.getMaxAltitude()), 2, 2));
474                                 
475                                 labelTable.addCell(ITextHelper.createCell(FLIGHT_TIME, 2, 2));
476                                 labelTable.addCell(ITextHelper.createCell(flightTimeUnit.toStringUnit(flight.getFlightTime()), 2, 2));
477                                 
478                                 labelTable.addCell(ITextHelper.createCell(TIME_TO_APOGEE, 2, 2));
479                                 labelTable.addCell(ITextHelper.createCell(flightTimeUnit.toStringUnit(flight.getTimeToApogee()), 2, 2));
480                                 
481                                 labelTable.addCell(ITextHelper.createCell(VELOCITY_OFF_PAD, 2, 2));
482                                 labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getLaunchRodVelocity()), 2, 2));
483                                 
484                                 labelTable.addCell(ITextHelper.createCell(MAX_VELOCITY, 2, 2));
485                                 labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getMaxVelocity()), 2, 2));
486                                 
487                                 labelTable.addCell(ITextHelper.createCell(DEPLOYMENT_VELOCITY, 2,2));
488                                 labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getDeploymentVelocity()),2,2));
489                                 
490                                 labelTable.addCell(ITextHelper.createCell(LANDING_VELOCITY, 2, 2));
491                                 labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getGroundHitVelocity()), 2, 2));
492                                 
493                                 //Add the table to the parent; have to wrap it in a cell
494                                 PdfPCell c = new PdfPCell(labelTable);
495                                 c.setBorder(PdfPCell.RIGHT);
496                                 c.setBorderWidthTop(0);
497                                 c.setTop(0);
498                                 parent.addCell(c);
499                         } catch (DocumentException e) {
500                                 log.error("Could not add flight data to document.", e);
501                         }
502                 }
503         }
504         
505         /**
506          * Strip [] brackets from a string.
507          *
508          * @param target the original string
509          *
510          * @return target with [] removed
511          */
512         private String stripBrackets(String target) {
513                 return stripLeftBracket(stripRightBracket(target));
514         }
515         
516         /**
517          * Strip [ from a string.
518          *
519          * @param target the original string
520          *
521          * @return target with [ removed
522          */
523         private String stripLeftBracket(String target) {
524                 return target.replace("[", "");
525         }
526         
527         /**
528          * Strip ] from a string.
529          *
530          * @param target the original string
531          *
532          * @return target with ] removed
533          */
534         private String stripRightBracket(String target) {
535                 return target.replace("]", "");
536         }
537         
538 }