create changelog entry
[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 import java.util.List;
10
11 import net.sf.openrocket.document.OpenRocketDocument;
12 import net.sf.openrocket.document.Simulation;
13 import net.sf.openrocket.gui.figureelements.FigureElement;
14 import net.sf.openrocket.gui.figureelements.RocketInfo;
15 import net.sf.openrocket.gui.scalefigure.RocketPanel;
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                 canvas.setFontAndSize(ITextHelper.getBaseFont(), PrintUtilities.NORMAL_FONT_SIZE);
176                 int figHeightPts = (int) (PrintUnit.METERS.toPoints(figure.getFigureHeight()) * 0.4 * (scale / PrintUnit.METERS
177                                 .toPoints(1)));
178                 final int diagramHeight = pageImageableHeight * 2 - 70 - (figHeightPts);
179                 canvas.moveText(document.leftMargin() + pageSize.getBorderWidthLeft(), diagramHeight);
180                 canvas.moveTextWithLeading(0, -16);
181
182                 float initialY = canvas.getYTLM();
183
184                 canvas.showText(rocketDocument.getRocket().getName());
185
186                 canvas.newlineShowText(STAGES);
187                 canvas.showText("" + rocket.getStageCount());
188
189
190                 if (configuration.hasMotors()) {
191                         if (configuration.getStageCount() > 1) {
192                                 canvas.newlineShowText(MASS_WITH_MOTORS);
193                         } else {
194                                 canvas.newlineShowText(MASS_WITH_MOTOR);
195                         }
196                 } else {
197                         canvas.newlineShowText(MASS_EMPTY);
198                 }
199                 canvas.showText(text.getMass(UnitGroup.UNITS_MASS.getDefaultUnit()));
200
201                 canvas.newlineShowText(STABILITY);
202                 canvas.showText(text.getStability());
203
204                 canvas.newlineShowText(CG);
205                 canvas.showText(text.getCg());
206
207                 canvas.newlineShowText(CP);
208                 canvas.showText(text.getCp());
209                 canvas.endText();
210
211                 try {
212                         //Move the internal pointer of the document below that of what was just written using the direct byte buffer.
213                         Paragraph paragraph = new Paragraph();
214                         float finalY = canvas.getYTLM();
215                         int heightOfDiagramAndText = (int) (pageSize.getHeight() - (finalY - initialY + diagramHeight));
216
217                         paragraph.setSpacingAfter(heightOfDiagramAndText);
218                         document.add(paragraph);
219
220                         String[] motorIds = rocket.getMotorConfigurationIDs();
221             List<Simulation> simulations = rocketDocument.getSimulations();
222
223                         for (int j = 0; j < motorIds.length; j++) {
224                                 String motorId = motorIds[j];
225                                 if (motorId != null) {
226                                         PdfPTable parent = new PdfPTable(2);
227                                         parent.setWidthPercentage(100);
228                                         parent.setHorizontalAlignment(Element.ALIGN_LEFT);
229                                         parent.setSpacingBefore(0);
230                                         parent.setWidths(new int[] { 1, 3 });
231                                         int leading = 0;
232                                         //The first motor config is always null.  Skip it and the top-most motor, then set the leading.
233                                         if (j > 1) {
234                                                 leading = 25;
235                                         }
236                     FlightData flight = findSimulation(motorId, simulations);
237                                         addFlightData(flight, rocket, motorId, parent, leading);
238                                         addMotorData(rocket, motorId, parent);
239                                         document.add(parent);
240                                 }
241                         }
242                 } catch (DocumentException e) {
243                         log.error("Could not modify document.", e);
244                 }
245         }
246
247
248         /**
249          * Paint a diagram of the rocket into the PDF document.
250          *
251          * @param thePageImageableWidth  the number of points in the width of the page available for drawing
252          * @param thePageImageableHeight the number of points in the height of the page available for drawing
253          * @param theCanvas              the direct byte writer
254          * @param theFigure              the print figure
255          * @param theCp                  the center of pressure figure element
256          * @param theCg                  the center of gravity figure element
257          *
258          * @return the scale of the diagram
259          */
260         private double paintRocketDiagram(final int thePageImageableWidth, final int thePageImageableHeight,
261                                                                                 final PdfContentByte theCanvas, final PrintFigure theFigure,
262                                                                                 final FigureElement theCp, final FigureElement theCg) {
263                 theFigure.clearAbsoluteExtra();
264                 theFigure.clearRelativeExtra();
265                 theFigure.addRelativeExtra(theCp);
266                 theFigure.addRelativeExtra(theCg);
267                 theFigure.updateFigure();
268
269                 double scale =
270                                 (thePageImageableWidth * 2.2) / theFigure.getFigureWidth();
271                 theFigure.setScale(scale);
272                 /*
273                  * page dimensions are in points-per-inch, which, in Java2D, are the same as pixels-per-inch; thus we don't need any conversion
274                  */
275                 theFigure.setSize(thePageImageableWidth, thePageImageableHeight);
276                 theFigure.updateFigure();
277
278                 final DefaultFontMapper mapper = new DefaultFontMapper();
279                 Graphics2D g2d = theCanvas.createGraphics(thePageImageableWidth, thePageImageableHeight * 2, mapper);
280         final double halfFigureHeight = SCALE_FUDGE_FACTOR * theFigure.getFigureHeightPx()/2;
281         int y = PrintUnit.POINTS_PER_INCH;
282         //If the y dimension is negative, then it will potentially be drawn off the top of the page.  Move the origin
283         //to allow for this.
284         if (theFigure.getDimensions().getY() < 0.0d) {
285             y += (int)halfFigureHeight;
286         }
287         g2d.translate(20, y);
288
289                 g2d.scale(SCALE_FUDGE_FACTOR, SCALE_FUDGE_FACTOR);
290                 theFigure.paint(g2d);
291                 g2d.dispose();
292                 return scale;
293         }
294
295         /**
296          * Add the motor data for a motor configuration to the table.
297          *
298          * @param rocket        the rocket
299          * @param motorId       the motor ID to output
300          * @param parent        the parent to which the motor data will be added
301          */
302         private void addMotorData(Rocket rocket, String motorId, final PdfPTable parent) {
303
304                 PdfPTable motorTable = new PdfPTable(8);
305                 motorTable.setWidthPercentage(68);
306                 motorTable.setHorizontalAlignment(Element.ALIGN_LEFT);
307
308                 final PdfPCell motorCell = ITextHelper.createCell(MOTOR, PdfPCell.BOTTOM, PrintUtilities.SMALL);
309                 final int mPad = 10;
310                 motorCell.setPaddingLeft(mPad);
311                 motorTable.addCell(motorCell);
312                 motorTable.addCell(ITextHelper.createCell(AVG_THRUST, PdfPCell.BOTTOM, PrintUtilities.SMALL));
313                 motorTable.addCell(ITextHelper.createCell(BURN_TIME, PdfPCell.BOTTOM, PrintUtilities.SMALL));
314                 motorTable.addCell(ITextHelper.createCell(MAX_THRUST, PdfPCell.BOTTOM, PrintUtilities.SMALL));
315                 motorTable.addCell(ITextHelper.createCell(TOTAL_IMPULSE, PdfPCell.BOTTOM, PrintUtilities.SMALL));
316                 motorTable.addCell(ITextHelper.createCell(THRUST_TO_WT, PdfPCell.BOTTOM, PrintUtilities.SMALL));
317                 motorTable.addCell(ITextHelper.createCell(PROPELLANT_WT, PdfPCell.BOTTOM, PrintUtilities.SMALL));
318                 motorTable.addCell(ITextHelper.createCell(SIZE, PdfPCell.BOTTOM, PrintUtilities.SMALL));
319
320                 DecimalFormat ttwFormat = new DecimalFormat("0.00");
321
322                 MassCalculator massCalc = new BasicMassCalculator();
323
324                 Configuration config = new Configuration(rocket);
325                 config.setMotorConfigurationID(motorId);
326
327                 int totalMotorCount = 0;
328                 double totalPropMass = 0;
329                 double totalImpulse = 0;
330                 double totalTTW = 0;
331
332                 int stage = 0;
333                 double stageMass = 0;
334
335                 boolean topBorder = false;
336                 for (RocketComponent c : rocket) {
337
338                         if (c instanceof Stage) {
339                                 config.setToStage(stage);
340                                 stage++;
341                                 stageMass = massCalc.getCG(config, MassCalcType.LAUNCH_MASS).weight;
342                                 // Calculate total thrust-to-weight from only lowest stage motors
343                                 totalTTW = 0;
344                                 topBorder = true;
345                         }
346
347                         if (c instanceof MotorMount && ((MotorMount) c).isMotorMount()) {
348                                 MotorMount mount = (MotorMount) c;
349
350                                 if (mount.isMotorMount() && mount.getMotor(motorId) != null) {
351                                         Motor motor = mount.getMotor(motorId);
352                                         int motorCount = c.toAbsolute(Coordinate.NUL).length;
353
354
355                                         int border = Rectangle.NO_BORDER;
356                                         if (topBorder) {
357                                                 border = Rectangle.TOP;
358                                                 topBorder = false;
359                                         }
360
361                                         String name = motor.getDesignation();
362                                         if (motorCount > 1) {
363                                                 name += " (" + Chars.TIMES + motorCount + ")";
364                                         }
365
366                                         final PdfPCell motorVCell = ITextHelper.createCell(name, border);
367                                         motorVCell.setPaddingLeft(mPad);
368                                         motorTable.addCell(motorVCell);
369                                         motorTable.addCell(ITextHelper.createCell(
370                                                         UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit(motor.getAverageThrustEstimate()), border));
371                                         motorTable.addCell(ITextHelper.createCell(
372                                                         UnitGroup.UNITS_FLIGHT_TIME.getDefaultUnit().toStringUnit(motor.getBurnTimeEstimate()), border));
373                                         motorTable.addCell(ITextHelper.createCell(
374                                                         UnitGroup.UNITS_FORCE.getDefaultUnit().toStringUnit(motor.getMaxThrustEstimate()), border));
375                                         motorTable.addCell(ITextHelper.createCell(
376                                                         UnitGroup.UNITS_IMPULSE.getDefaultUnit().toStringUnit(motor.getTotalImpulseEstimate()), border));
377
378                                         double ttw = motor.getAverageThrustEstimate() / (stageMass * GRAVITY_CONSTANT);
379                                         motorTable.addCell(ITextHelper.createCell(
380                                                         ttwFormat.format(ttw) + ":1", border));
381
382                                         double propMass = (motor.getLaunchCG().weight - motor.getEmptyCG().weight);
383                                         motorTable.addCell(ITextHelper.createCell(
384                                                         UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit(propMass), border));
385
386                                         final Unit motorUnit = UnitGroup.UNITS_MOTOR_DIMENSIONS.getDefaultUnit();
387                                         motorTable.addCell(ITextHelper.createCell(motorUnit.toString(motor.getDiameter()) +
388                                                                                                                                 "/" +
389                                                                                                                                 motorUnit.toString(motor.getLength()) + " " +
390                                                                                                                                 motorUnit.toString(), border));
391
392                                         // Sum up total count
393                                         totalMotorCount += motorCount;
394                                         totalPropMass += propMass * motorCount;
395                                         totalImpulse += motor.getTotalImpulseEstimate() * motorCount;
396                                         totalTTW += ttw * motorCount;
397                                 }
398                         }
399                 }
400
401                 if (totalMotorCount > 1) {
402                         int border = Rectangle.TOP;
403                         final PdfPCell motorVCell = ITextHelper.createCell("Total:", border);
404                         motorVCell.setPaddingLeft(mPad);
405                         motorTable.addCell(motorVCell);
406                         motorTable.addCell(ITextHelper.createCell("", border));
407                         motorTable.addCell(ITextHelper.createCell("", border));
408                         motorTable.addCell(ITextHelper.createCell("", border));
409                         motorTable.addCell(ITextHelper.createCell(
410                                                 UnitGroup.UNITS_IMPULSE.getDefaultUnit().toStringUnit(totalImpulse), border));
411                         motorTable.addCell(ITextHelper.createCell(
412                                         ttwFormat.format(totalTTW) + ":1", border));
413                         motorTable.addCell(ITextHelper.createCell(
414                                                 UnitGroup.UNITS_MASS.getDefaultUnit().toStringUnit(totalPropMass), border));
415                         motorTable.addCell(ITextHelper.createCell("", border));
416
417                 }
418
419                 PdfPCell c = new PdfPCell(motorTable);
420                 c.setBorder(PdfPCell.LEFT);
421                 c.setBorderWidthTop(0f);
422                 parent.addCell(c);
423         }
424
425
426         /**
427          * Add the flight data for a simulation configuration to the table.
428          *
429      * @param flight    the flight data for a single simulation
430          * @param theRocket the rocket
431          * @param motorId   a motor configuration id
432          * @param parent    the parent to which the simulation flight data will be added
433          * @param leading   the number of points for the leading
434          */
435         private void addFlightData(final FlightData flight, final Rocket theRocket, final String motorId, final PdfPTable parent, int leading) {
436
437         // Output the flight data
438                 if (flight != null) {
439                         try {
440                                 final Unit distanceUnit = UnitGroup.UNITS_DISTANCE.getDefaultUnit();
441                                 final Unit velocityUnit = UnitGroup.UNITS_VELOCITY.getDefaultUnit();
442                                 final Unit flightTimeUnit = UnitGroup.UNITS_FLIGHT_TIME.getDefaultUnit();
443
444                                 PdfPTable labelTable = new PdfPTable(2);
445                                 labelTable.setWidths(new int[] { 3, 2 });
446                                 final Paragraph chunk = ITextHelper.createParagraph(stripBrackets(
447                                                         theRocket.getMotorConfigurationNameOrDescription(motorId)), PrintUtilities.BOLD);
448                                 chunk.setLeading(leading);
449                                 chunk.setSpacingAfter(3f);
450
451                                 document.add(chunk);
452
453                                 final PdfPCell cell = ITextHelper.createCell(ALTITUDE, 2, 2);
454                                 cell.setUseBorderPadding(false);
455                                 cell.setBorderWidthTop(0f);
456                                 labelTable.addCell(cell);
457                                 labelTable.addCell(ITextHelper.createCell(distanceUnit.toStringUnit(flight.getMaxAltitude()), 2, 2));
458
459                                 labelTable.addCell(ITextHelper.createCell(FLIGHT_TIME, 2, 2));
460                                 labelTable.addCell(ITextHelper.createCell(flightTimeUnit.toStringUnit(flight.getFlightTime()), 2, 2));
461
462                                 labelTable.addCell(ITextHelper.createCell(TIME_TO_APOGEE, 2, 2));
463                                 labelTable.addCell(ITextHelper.createCell(flightTimeUnit.toStringUnit(flight.getTimeToApogee()), 2, 2));
464
465                                 labelTable.addCell(ITextHelper.createCell(VELOCITY_OFF_PAD, 2, 2));
466                                 labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getLaunchRodVelocity()), 2, 2));
467
468                                 labelTable.addCell(ITextHelper.createCell(MAX_VELOCITY, 2, 2));
469                                 labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getMaxVelocity()), 2, 2));
470
471                                 labelTable.addCell(ITextHelper.createCell(DEPLOYMENT_VELOCITY, 2,2));
472                                 labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getDeploymentVelocity()),2,2));
473
474                                 labelTable.addCell(ITextHelper.createCell(LANDING_VELOCITY, 2, 2));
475                                 labelTable.addCell(ITextHelper.createCell(velocityUnit.toStringUnit(flight.getGroundHitVelocity()), 2, 2));
476
477                                 //Add the table to the parent; have to wrap it in a cell
478                                 PdfPCell c = new PdfPCell(labelTable);
479                                 c.setBorder(PdfPCell.RIGHT);
480                                 c.setBorderWidthTop(0);
481                                 c.setTop(0);
482                                 parent.addCell(c);
483                         } catch (DocumentException e) {
484                                 log.error("Could not add flight data to document.", e);
485                         }
486                 }
487         }
488
489     /**
490      * Locate the simulation based on the motor id.  Copy the simulation and execute it, then return the resulting
491      * flight data.
492      *
493      * @param motorId     the motor id corresponding to the simulation to find
494      * @param simulations the list of simulations currently associated with the rocket
495      *
496      * @return the flight data from the simulation for the specified motor id, or null if not found
497      */
498     private FlightData findSimulation(final String motorId, List<Simulation> simulations) {
499         // Perform flight simulation
500         FlightData flight = null;
501         try {
502             for (int i = 0; i < simulations.size(); i++) {
503                 Simulation simulation =  simulations.get(i);
504                 if (simulation.getOptions().getMotorConfigurationID().equals(motorId)) {
505                     simulation = simulation.copy();
506                     simulation.simulate();
507                     flight = simulation.getSimulatedData();
508                     break;
509                 }
510             }
511         } catch (SimulationException e1) {
512             // Ignore
513         }
514         return flight;
515     }
516
517     /**
518          * Strip [] brackets from a string.
519          *
520          * @param target the original string
521          *
522          * @return target with [] removed
523          */
524         private String stripBrackets(String target) {
525                 return stripLeftBracket(stripRightBracket(target));
526         }
527
528         /**
529          * Strip [ from a string.
530          *
531          * @param target the original string
532          *
533          * @return target with [ removed
534          */
535         private String stripLeftBracket(String target) {
536                 return target.replace("[", "");
537         }
538
539         /**
540          * Strip ] from a string.
541          *
542          * @param target the original string
543          *
544          * @return target with ] removed
545          */
546         private String stripRightBracket(String target) {
547                 return target.replace("]", "");
548         }
549
550 }