1 package net.sf.openrocket.file.openrocket;
3 import java.io.BufferedWriter;
4 import java.io.IOException;
5 import java.io.OutputStream;
6 import java.io.OutputStreamWriter;
8 import java.util.ArrayList;
9 import java.util.Iterator;
10 import java.util.List;
11 import java.util.Locale;
12 import java.util.zip.GZIPOutputStream;
14 import net.sf.openrocket.aerodynamics.Warning;
15 import net.sf.openrocket.document.OpenRocketDocument;
16 import net.sf.openrocket.document.Simulation;
17 import net.sf.openrocket.document.StorageOptions;
18 import net.sf.openrocket.file.RocketSaver;
19 import net.sf.openrocket.logging.LogHelper;
20 import net.sf.openrocket.rocketcomponent.FinSet;
21 import net.sf.openrocket.rocketcomponent.MotorMount;
22 import net.sf.openrocket.rocketcomponent.RecoveryDevice;
23 import net.sf.openrocket.rocketcomponent.RecoveryDevice.DeployEvent;
24 import net.sf.openrocket.rocketcomponent.Rocket;
25 import net.sf.openrocket.rocketcomponent.RocketComponent;
26 import net.sf.openrocket.rocketcomponent.TubeCoupler;
27 import net.sf.openrocket.simulation.customexpression.CustomExpression;
28 import net.sf.openrocket.simulation.FlightData;
29 import net.sf.openrocket.simulation.FlightDataBranch;
30 import net.sf.openrocket.simulation.FlightDataType;
31 import net.sf.openrocket.simulation.FlightEvent;
32 import net.sf.openrocket.simulation.SimulationOptions;
33 import net.sf.openrocket.startup.Application;
34 import net.sf.openrocket.util.BugException;
35 import net.sf.openrocket.util.BuildProperties;
36 import net.sf.openrocket.util.MathUtil;
37 import net.sf.openrocket.util.Reflection;
38 import net.sf.openrocket.util.TextUtil;
40 public class OpenRocketSaver extends RocketSaver {
41 private static final LogHelper log = Application.getLogger();
45 * Divisor used in converting an integer version to the point-represented version.
46 * The integer version divided by this value is the major version and the remainder is
47 * the minor version. For example 101 corresponds to file version "1.1".
49 public static final int FILE_VERSION_DIVISOR = 100;
52 private static final String OPENROCKET_CHARSET = "UTF-8";
54 private static final String METHOD_PACKAGE = "net.sf.openrocket.file.openrocket.savers";
55 private static final String METHOD_SUFFIX = "Saver";
58 // Estimated storage used by different portions
59 // These have been hand-estimated from saved files
60 private static final int BYTES_PER_COMPONENT_UNCOMPRESSED = 590;
61 private static final int BYTES_PER_COMPONENT_COMPRESSED = 80;
62 private static final int BYTES_PER_SIMULATION_UNCOMPRESSED = 1000;
63 private static final int BYTES_PER_SIMULATION_COMPRESSED = 100;
64 private static final int BYTES_PER_DATAPOINT_UNCOMPRESSED = 350;
65 private static final int BYTES_PER_DATAPOINT_COMPRESSED = 100;
72 public void save(OutputStream output, OpenRocketDocument document, StorageOptions options)
75 log.info("Saving .ork file");
77 if (options.isCompressionEnabled()) {
78 log.debug("Enabling compression");
79 output = new GZIPOutputStream(output);
82 dest = new BufferedWriter(new OutputStreamWriter(output, OPENROCKET_CHARSET));
84 // Select file version number
85 final int fileVersion = calculateNecessaryFileVersion(document, options);
86 final String fileVersionString =
87 (fileVersion / FILE_VERSION_DIVISOR) + "." + (fileVersion % FILE_VERSION_DIVISOR);
88 log.debug("Storing file version " + fileVersionString);
94 writeln("<?xml version='1.0' encoding='utf-8'?>");
95 writeln("<openrocket version=\"" + fileVersionString + "\" creator=\"OpenRocket "
96 + BuildProperties.getVersion() + "\">");
99 // Recursively save the rocket structure
100 saveComponent(document.getRocket());
104 // Save custom expressions;
105 saveCustomDatatypes(document);
107 // Save all simulations
108 writeln("<simulations>");
110 boolean first = true;
111 for (Simulation s : document.getSimulations()) {
115 saveSimulation(s, options.getSimulationTimeSkip());
118 writeln("</simulations>");
121 writeln("</openrocket>");
123 log.debug("Writing complete, flushing buffers");
125 if (options.isCompressionEnabled()) {
126 ((GZIPOutputStream) output).finish();
131 * Save all the custom expressions
133 private void saveCustomDatatypes(OpenRocketDocument doc) throws IOException {
135 if (doc.getCustomExpressions().isEmpty())
138 writeln("<datatypes>"); indent++;
140 for (CustomExpression exp : doc.getCustomExpressions()){
141 saveCustomExpressionDatatype(exp);
144 indent--; writeln("</datatypes>");
149 * Save one custom expression datatype
151 private void saveCustomExpressionDatatype(CustomExpression exp) throws IOException {
152 // Write out custom expression
154 writeln("<type source=\"customexpression\">"); indent++;
155 writeln("<name>" + exp.getName() + "</name>");
156 writeln("<symbol>" + exp.getSymbol() + "</symbol>");
157 writeln("<unit unittype=\"auto\">" + exp.getUnit() + "</unit>"); // auto unit type means it will be determined from string
158 writeln("<expression>" + exp.getExpressionString() + "</expression>");
159 indent--; writeln("</type>");
163 public long estimateFileSize(OpenRocketDocument doc, StorageOptions options) {
167 // Size per component
168 int componentCount = 0;
169 Rocket rocket = doc.getRocket();
170 Iterator<RocketComponent> iterator = rocket.iterator(true);
171 while (iterator.hasNext()) {
176 if (options.isCompressionEnabled())
177 size += componentCount * BYTES_PER_COMPONENT_COMPRESSED;
179 size += componentCount * BYTES_PER_COMPONENT_UNCOMPRESSED;
182 // Size per simulation
183 if (options.isCompressionEnabled())
184 size += doc.getSimulationCount() * BYTES_PER_SIMULATION_COMPRESSED;
186 size += doc.getSimulationCount() * BYTES_PER_SIMULATION_UNCOMPRESSED;
189 // Size per flight data point
191 double timeSkip = options.getSimulationTimeSkip();
192 if (timeSkip != StorageOptions.SIMULATION_DATA_NONE) {
193 for (Simulation s : doc.getSimulations()) {
194 FlightData data = s.getSimulatedData();
196 for (int i = 0; i < data.getBranchCount(); i++) {
197 pointCount += countFlightDataBranchPoints(data.getBranch(i), timeSkip);
203 if (options.isCompressionEnabled())
204 size += pointCount * BYTES_PER_DATAPOINT_COMPRESSED;
206 size += pointCount * BYTES_PER_DATAPOINT_UNCOMPRESSED;
213 * Determine which file version is required in order to store all the features of the
214 * current design. By default the oldest version that supports all the necessary features
217 * @param document the document to output.
218 * @param opts the storage options.
219 * @return the integer file version to use.
221 private int calculateNecessaryFileVersion(OpenRocketDocument document, StorageOptions opts) {
223 * File version 1.5 is requires for:
224 * - saving designs using ComponentPrests
225 * - recovery device deployment on lower stage separation
227 * File version 1.4 is required for:
228 * - saving simulation data
229 * - saving motor data
231 * File version 1.1 is required for:
233 * - components attached to tube coupler
235 * Otherwise use version 1.0.
238 // Search the rocket for any ComponentPresets (version 1.5)
239 for (RocketComponent c : document.getRocket()) {
240 if (c.getPresetComponent() != null) {
241 return FILE_VERSION_DIVISOR + 5;
245 // Search for recovery device deployment type LOWER_STAGE_SEPARATION (version 1.5)
246 for (RocketComponent c : document.getRocket()) {
247 if (c instanceof RecoveryDevice) {
248 if (((RecoveryDevice) c).getDeployEvent() == DeployEvent.LOWER_STAGE_SEPARATION) {
249 return FILE_VERSION_DIVISOR + 5;
254 // Check if design has simulations defined (version 1.4)
255 if (document.getSimulationCount() > 0) {
256 return FILE_VERSION_DIVISOR + 4;
259 // Check for motor definitions (version 1.4)
260 for (RocketComponent c : document.getRocket()) {
261 if (!(c instanceof MotorMount))
264 MotorMount mount = (MotorMount) c;
265 for (String id : document.getRocket().getMotorConfigurationIDs()) {
266 if (mount.getMotor(id) != null) {
267 return FILE_VERSION_DIVISOR + 4;
272 // Check for fin tabs (version 1.1)
273 for (RocketComponent c : document.getRocket()) {
274 // Check for fin tabs
275 if (c instanceof FinSet) {
276 FinSet fin = (FinSet) c;
277 if (!MathUtil.equals(fin.getTabHeight(), 0) &&
278 !MathUtil.equals(fin.getTabLength(), 0)) {
279 return FILE_VERSION_DIVISOR + 1;
283 // Check for components attached to tube coupler
284 if (c instanceof TubeCoupler) {
285 if (c.getChildCount() > 0) {
286 return FILE_VERSION_DIVISOR + 1;
291 // Default (version 1.0)
292 return FILE_VERSION_DIVISOR + 0;
297 @SuppressWarnings("unchecked")
298 private void saveComponent(RocketComponent component) throws IOException {
300 log.debug("Saving component " + component.getComponentName());
302 Reflection.Method m = Reflection.findMethod(METHOD_PACKAGE, component, METHOD_SUFFIX,
303 "getElements", RocketComponent.class);
305 throw new BugException("Unable to find saving class for component " +
306 component.getComponentName());
309 // Get the strings to save
310 List<String> list = (List<String>) m.invokeStatic(component);
311 int length = list.size();
313 if (length == 0) // Nothing to do
317 throw new RuntimeException("BUG, component data length less than two lines.");
321 writeln(list.get(0));
325 for (int i = 1; i < length - 1; i++) {
326 writeln(list.get(i));
329 // Recursively write subcomponents
330 if (component.getChildCount() > 0) {
332 writeln("<subcomponents>");
334 boolean emptyline = false;
335 for (RocketComponent subcomponent : component.getChildren()) {
339 saveComponent(subcomponent);
342 writeln("</subcomponents>");
347 writeln(list.get(length - 1));
351 private void saveSimulation(Simulation simulation, double timeSkip) throws IOException {
352 SimulationOptions cond = simulation.getOptions();
354 writeln("<simulation status=\"" + enumToXMLName(simulation.getStatus()) + "\">");
357 writeln("<name>" + escapeXML(simulation.getName()) + "</name>");
358 // TODO: MEDIUM: Other simulators/calculators
360 writeln("<simulator>RK4Simulator</simulator>");
361 writeln("<calculator>BarrowmanCalculator</calculator>");
363 writeln("<conditions>"); indent++;
365 writeElement("configid", cond.getMotorConfigurationID());
366 writeElement("launchrodlength", cond.getLaunchRodLength());
367 writeElement("launchrodangle", cond.getLaunchRodAngle() * 180.0 / Math.PI);
368 writeElement("launchroddirection", cond.getLaunchRodDirection() * 180.0 / Math.PI);
369 writeElement("windaverage", cond.getWindSpeedAverage());
370 writeElement("windturbulence", cond.getWindTurbulenceIntensity());
371 writeElement("launchaltitude", cond.getLaunchAltitude());
372 writeElement("launchlatitude", cond.getLaunchLatitude());
373 writeElement("launchlongitude", cond.getLaunchLongitude());
374 writeElement("geodeticmethod", cond.getGeodeticComputation().name().toLowerCase(Locale.ENGLISH));
376 if (cond.isISAAtmosphere()) {
377 writeln("<atmosphere model=\"isa\"/>");
379 writeln("<atmosphere model=\"extendedisa\">");
381 writeElement("basetemperature", cond.getLaunchTemperature());
382 writeElement("basepressure", cond.getLaunchPressure());
384 writeln("</atmosphere>");
387 writeElement("timestep", cond.getTimeStep());
390 writeln("</conditions>");
393 for (String s : simulation.getSimulationListeners()) {
394 writeElement("listener", escapeXML(s));
397 // Write basic simulation data
399 FlightData data = simulation.getSimulatedData();
401 String str = "<flightdata";
402 if (!Double.isNaN(data.getMaxAltitude()))
403 str += " maxaltitude=\"" + TextUtil.doubleToString(data.getMaxAltitude()) + "\"";
404 if (!Double.isNaN(data.getMaxVelocity()))
405 str += " maxvelocity=\"" + TextUtil.doubleToString(data.getMaxVelocity()) + "\"";
406 if (!Double.isNaN(data.getMaxAcceleration()))
407 str += " maxacceleration=\"" + TextUtil.doubleToString(data.getMaxAcceleration()) + "\"";
408 if (!Double.isNaN(data.getMaxMachNumber()))
409 str += " maxmach=\"" + TextUtil.doubleToString(data.getMaxMachNumber()) + "\"";
410 if (!Double.isNaN(data.getTimeToApogee()))
411 str += " timetoapogee=\"" + TextUtil.doubleToString(data.getTimeToApogee()) + "\"";
412 if (!Double.isNaN(data.getFlightTime()))
413 str += " flighttime=\"" + TextUtil.doubleToString(data.getFlightTime()) + "\"";
414 if (!Double.isNaN(data.getGroundHitVelocity()))
415 str += " groundhitvelocity=\"" + TextUtil.doubleToString(data.getGroundHitVelocity()) + "\"";
416 if (!Double.isNaN(data.getLaunchRodVelocity()))
417 str += " launchrodvelocity=\"" + TextUtil.doubleToString(data.getLaunchRodVelocity()) + "\"";
418 if (!Double.isNaN(data.getDeploymentVelocity()))
419 str += " deploymentvelocity=\"" + TextUtil.doubleToString(data.getDeploymentVelocity()) + "\"";
424 for (Warning w : data.getWarningSet()) {
425 writeElement("warning", escapeXML(w.toString()));
428 // Check whether to store data
429 if (simulation.getStatus() == Simulation.Status.EXTERNAL) // Always store external data
432 if (timeSkip != StorageOptions.SIMULATION_DATA_NONE) {
433 for (int i = 0; i < data.getBranchCount(); i++) {
434 FlightDataBranch branch = data.getBranch(i);
435 saveFlightDataBranch(branch, timeSkip);
440 writeln("</flightdata>");
444 writeln("</simulation>");
450 private void saveFlightDataBranch(FlightDataBranch branch, double timeSkip)
452 double previousTime = -100000;
457 // Retrieve the types from the branch
458 FlightDataType[] types = branch.getTypes();
460 if (types.length == 0)
463 // Retrieve the data from the branch
464 List<List<Double>> data = new ArrayList<List<Double>>(types.length);
465 for (int i = 0; i < types.length; i++) {
466 data.add(branch.get(types[i]));
468 List<Double> timeData = branch.get(FlightDataType.TYPE_TIME);
470 // Build the <databranch> tag
471 StringBuilder sb = new StringBuilder();
472 sb.append("<databranch name=\"");
473 sb.append(escapeXML(branch.getBranchName()));
475 // Kevins version where typekeys are used
477 sb.append("\" typekeys=\"");
478 for (int i = 0; i < types.length; i++) {
481 sb.append(escapeXML(types[i].getKey()));
485 sb.append("\" types=\"");
486 for (int i = 0; i < types.length; i++) {
489 sb.append(escapeXML(types[i].getName()));
492 writeln(sb.toString());
496 for (FlightEvent event : branch.getEvents()) {
497 writeln("<event time=\"" + TextUtil.doubleToString(event.getTime())
498 + "\" type=\"" + enumToXMLName(event.getType()) + "\"/>");
502 int length = branch.getLength();
504 writeDataPointString(data, 0, sb);
505 previousTime = timeData.get(0);
508 for (int i = 1; i < length - 1; i++) {
509 if (timeData != null) {
510 if (Math.abs(timeData.get(i) - previousTime - timeSkip) < Math.abs(timeData.get(i + 1) - previousTime - timeSkip)) {
511 writeDataPointString(data, i, sb);
512 previousTime = timeData.get(i);
515 // If time data is not available, write all points
516 writeDataPointString(data, i, sb);
521 writeDataPointString(data, length - 1, sb);
525 writeln("</databranch>");
530 /* TODO: LOW: This is largely duplicated from above! */
531 private int countFlightDataBranchPoints(FlightDataBranch branch, double timeSkip) {
534 double previousTime = -100000;
539 // Retrieve the types from the branch
540 FlightDataType[] types = branch.getTypes();
542 if (types.length == 0)
545 List<Double> timeData = branch.get(FlightDataType.TYPE_TIME);
546 if (timeData == null) {
547 // If time data not available, store all points
548 return branch.getLength();
552 int length = branch.getLength();
555 previousTime = timeData.get(0);
558 for (int i = 1; i < length - 1; i++) {
559 if (Math.abs(timeData.get(i) - previousTime - timeSkip) < Math.abs(timeData.get(i + 1) - previousTime - timeSkip)) {
561 previousTime = timeData.get(i);
574 private void writeDataPointString(List<List<Double>> data, int index, StringBuilder sb)
577 sb.append("<datapoint>");
578 for (int j = 0; j < data.size(); j++) {
581 sb.append(TextUtil.doubleToString(data.get(j).get(index)));
583 sb.append("</datapoint>");
584 writeln(sb.toString());
589 private void writeElement(String element, Object content) throws IOException {
592 writeln("<" + element + ">" + content + "</" + element + ">");
597 private void writeln(String str) throws IOException {
598 if (str.length() == 0) {
603 for (int i = 0; i < indent; i++)
613 * Return the XML equivalent of an enum name.
615 * @param e the enum to save.
616 * @return the corresponding XML name.
618 public static String enumToXMLName(Enum<?> e) {
619 return e.name().toLowerCase(Locale.ENGLISH).replace("_", "");