Persist the Velocity at launch rod clearance in ork file. Added to column in Simulat...
[debian/openrocket] / core / src / net / sf / openrocket / file / openrocket / OpenRocketSaver.java
1 package net.sf.openrocket.file.openrocket;
2
3 import java.io.BufferedWriter;
4 import java.io.IOException;
5 import java.io.OutputStream;
6 import java.io.OutputStreamWriter;
7 import java.io.Writer;
8 import java.util.ArrayList;
9 import java.util.Iterator;
10 import java.util.List;
11 import java.util.zip.GZIPOutputStream;
12
13 import net.sf.openrocket.aerodynamics.Warning;
14 import net.sf.openrocket.document.OpenRocketDocument;
15 import net.sf.openrocket.document.Simulation;
16 import net.sf.openrocket.document.StorageOptions;
17 import net.sf.openrocket.file.RocketSaver;
18 import net.sf.openrocket.logging.LogHelper;
19 import net.sf.openrocket.rocketcomponent.FinSet;
20 import net.sf.openrocket.rocketcomponent.MotorMount;
21 import net.sf.openrocket.rocketcomponent.Rocket;
22 import net.sf.openrocket.rocketcomponent.RocketComponent;
23 import net.sf.openrocket.rocketcomponent.TubeCoupler;
24 import net.sf.openrocket.simulation.FlightData;
25 import net.sf.openrocket.simulation.FlightDataBranch;
26 import net.sf.openrocket.simulation.FlightDataType;
27 import net.sf.openrocket.simulation.FlightEvent;
28 import net.sf.openrocket.simulation.SimulationOptions;
29 import net.sf.openrocket.startup.Application;
30 import net.sf.openrocket.util.BugException;
31 import net.sf.openrocket.util.BuildProperties;
32 import net.sf.openrocket.util.MathUtil;
33 import net.sf.openrocket.util.Reflection;
34 import net.sf.openrocket.util.TextUtil;
35
36 public class OpenRocketSaver extends RocketSaver {
37         private static final LogHelper log = Application.getLogger();
38         
39
40         /**
41          * Divisor used in converting an integer version to the point-represented version.
42          * The integer version divided by this value is the major version and the remainder is
43          * the minor version.  For example 101 corresponds to file version "1.1".
44          */
45         public static final int FILE_VERSION_DIVISOR = 100;
46         
47
48         private static final String OPENROCKET_CHARSET = "UTF-8";
49         
50         private static final String METHOD_PACKAGE = "net.sf.openrocket.file.openrocket.savers";
51         private static final String METHOD_SUFFIX = "Saver";
52         
53
54         // Estimated storage used by different portions
55         // These have been hand-estimated from saved files
56         private static final int BYTES_PER_COMPONENT_UNCOMPRESSED = 590;
57         private static final int BYTES_PER_COMPONENT_COMPRESSED = 80;
58         private static final int BYTES_PER_SIMULATION_UNCOMPRESSED = 1000;
59         private static final int BYTES_PER_SIMULATION_COMPRESSED = 100;
60         private static final int BYTES_PER_DATAPOINT_UNCOMPRESSED = 350;
61         private static final int BYTES_PER_DATAPOINT_COMPRESSED = 100;
62         
63
64         private int indent;
65         private Writer dest;
66         
67         @Override
68         public void save(OutputStream output, OpenRocketDocument document, StorageOptions options)
69                         throws IOException {
70                 
71                 log.info("Saving .ork file");
72                 
73                 if (options.isCompressionEnabled()) {
74                         log.debug("Enabling compression");
75                         output = new GZIPOutputStream(output);
76                 }
77                 
78                 dest = new BufferedWriter(new OutputStreamWriter(output, OPENROCKET_CHARSET));
79                 
80                 // Select file version number
81                 final int fileVersion = calculateNecessaryFileVersion(document, options);
82                 final String fileVersionString =
83                                 (fileVersion / FILE_VERSION_DIVISOR) + "." + (fileVersion % FILE_VERSION_DIVISOR);
84                 log.debug("Storing file version " + fileVersionString);
85                 
86
87                 this.indent = 0;
88                 
89
90                 writeln("<?xml version='1.0' encoding='utf-8'?>");
91                 writeln("<openrocket version=\"" + fileVersionString + "\" creator=\"OpenRocket "
92                                 + BuildProperties.getVersion() + "\">");
93                 indent++;
94                 
95                 // Recursively save the rocket structure
96                 saveComponent(document.getRocket());
97                 
98                 writeln("");
99                 
100                 // Save all simulations
101                 writeln("<simulations>");
102                 indent++;
103                 boolean first = true;
104                 for (Simulation s : document.getSimulations()) {
105                         if (!first)
106                                 writeln("");
107                         first = false;
108                         saveSimulation(s, options.getSimulationTimeSkip());
109                 }
110                 indent--;
111                 writeln("</simulations>");
112                 
113                 indent--;
114                 writeln("</openrocket>");
115                 
116                 log.debug("Writing complete, flushing buffers");
117                 dest.flush();
118                 if (options.isCompressionEnabled()) {
119                         ((GZIPOutputStream) output).finish();
120                 }
121         }
122         
123         
124
125         @Override
126         public long estimateFileSize(OpenRocketDocument doc, StorageOptions options) {
127                 
128                 long size = 0;
129                 
130                 // Size per component
131                 int componentCount = 0;
132                 Rocket rocket = doc.getRocket();
133                 Iterator<RocketComponent> iterator = rocket.iterator(true);
134                 while (iterator.hasNext()) {
135                         iterator.next();
136                         componentCount++;
137                 }
138                 
139                 if (options.isCompressionEnabled())
140                         size += componentCount * BYTES_PER_COMPONENT_COMPRESSED;
141                 else
142                         size += componentCount * BYTES_PER_COMPONENT_UNCOMPRESSED;
143                 
144
145                 // Size per simulation
146                 if (options.isCompressionEnabled())
147                         size += doc.getSimulationCount() * BYTES_PER_SIMULATION_COMPRESSED;
148                 else
149                         size += doc.getSimulationCount() * BYTES_PER_SIMULATION_UNCOMPRESSED;
150                 
151
152                 // Size per flight data point
153                 int pointCount = 0;
154                 double timeSkip = options.getSimulationTimeSkip();
155                 if (timeSkip != StorageOptions.SIMULATION_DATA_NONE) {
156                         for (Simulation s : doc.getSimulations()) {
157                                 FlightData data = s.getSimulatedData();
158                                 if (data != null) {
159                                         for (int i = 0; i < data.getBranchCount(); i++) {
160                                                 pointCount += countFlightDataBranchPoints(data.getBranch(i), timeSkip);
161                                         }
162                                 }
163                         }
164                 }
165                 
166                 if (options.isCompressionEnabled())
167                         size += pointCount * BYTES_PER_DATAPOINT_COMPRESSED;
168                 else
169                         size += pointCount * BYTES_PER_DATAPOINT_UNCOMPRESSED;
170                 
171                 return size;
172         }
173         
174         
175         /**
176          * Determine which file version is required in order to store all the features of the
177          * current design.  By default the oldest version that supports all the necessary features
178          * will be used.
179          * 
180          * @param document      the document to output.
181          * @param opts          the storage options.
182          * @return                      the integer file version to use.
183          */
184         private int calculateNecessaryFileVersion(OpenRocketDocument document, StorageOptions opts) {
185                 /*
186                  * File version 1.2 is required for:
187                  *  - saving motor data
188                  * 
189                  * File version 1.1 is required for:
190                  *  - fin tabs
191                  *  - components attached to tube coupler
192                  * 
193                  * Otherwise use version 1.0.
194                  */
195
196                 // Check if design has simulations defined (version 1.3)
197                 if (document.getSimulationCount() > 0) {
198                         return FILE_VERSION_DIVISOR + 3;
199                 }
200                 
201                 // Check for motor definitions (version 1.2)
202                 Iterator<RocketComponent> iterator = document.getRocket().iterator();
203                 while (iterator.hasNext()) {
204                         RocketComponent c = iterator.next();
205                         if (!(c instanceof MotorMount))
206                                 continue;
207                         
208                         MotorMount mount = (MotorMount) c;
209                         for (String id : document.getRocket().getMotorConfigurationIDs()) {
210                                 if (mount.getMotor(id) != null) {
211                                         return FILE_VERSION_DIVISOR + 2;
212                                 }
213                         }
214                 }
215                 
216                 // Check for fin tabs (version 1.1)
217                 iterator = document.getRocket().iterator();
218                 while (iterator.hasNext()) {
219                         RocketComponent c = iterator.next();
220                         
221                         // Check for fin tabs
222                         if (c instanceof FinSet) {
223                                 FinSet fin = (FinSet) c;
224                                 if (!MathUtil.equals(fin.getTabHeight(), 0) &&
225                                                 !MathUtil.equals(fin.getTabLength(), 0)) {
226                                         return FILE_VERSION_DIVISOR + 1;
227                                 }
228                         }
229                         
230                         // Check for components attached to tube coupler
231                         if (c instanceof TubeCoupler) {
232                                 if (c.getChildCount() > 0) {
233                                         return FILE_VERSION_DIVISOR + 1;
234                                 }
235                         }
236                 }
237                 
238                 // Default (version 1.0)
239                 return FILE_VERSION_DIVISOR + 0;
240         }
241         
242         
243
244         @SuppressWarnings("unchecked")
245         private void saveComponent(RocketComponent component) throws IOException {
246                 
247                 log.debug("Saving component " + component.getComponentName());
248                 
249                 Reflection.Method m = Reflection.findMethod(METHOD_PACKAGE, component, METHOD_SUFFIX,
250                                 "getElements", RocketComponent.class);
251                 if (m == null) {
252                         throw new BugException("Unable to find saving class for component " +
253                                         component.getComponentName());
254                 }
255                 
256                 // Get the strings to save
257                 List<String> list = (List<String>) m.invokeStatic(component);
258                 int length = list.size();
259                 
260                 if (length == 0) // Nothing to do
261                         return;
262                 
263                 if (length < 2) {
264                         throw new RuntimeException("BUG, component data length less than two lines.");
265                 }
266                 
267                 // Open element
268                 writeln(list.get(0));
269                 indent++;
270                 
271                 // Write parameters
272                 for (int i = 1; i < length - 1; i++) {
273                         writeln(list.get(i));
274                 }
275                 
276                 // Recursively write subcomponents
277                 if (component.getChildCount() > 0) {
278                         writeln("");
279                         writeln("<subcomponents>");
280                         indent++;
281                         boolean emptyline = false;
282                         for (RocketComponent subcomponent : component.getChildren()) {
283                                 if (emptyline)
284                                         writeln("");
285                                 emptyline = true;
286                                 saveComponent(subcomponent);
287                         }
288                         indent--;
289                         writeln("</subcomponents>");
290                 }
291                 
292                 // Close element
293                 indent--;
294                 writeln(list.get(length - 1));
295         }
296         
297         
298         private void saveSimulation(Simulation simulation, double timeSkip) throws IOException {
299                 SimulationOptions cond = simulation.getOptions();
300                 
301                 writeln("<simulation status=\"" + enumToXMLName(simulation.getStatus()) + "\">");
302                 indent++;
303                 
304                 writeln("<name>" + escapeXML(simulation.getName()) + "</name>");
305                 // TODO: MEDIUM: Other simulators/calculators
306                 writeln("<simulator>RK4Simulator</simulator>");
307                 writeln("<calculator>BarrowmanCalculator</calculator>");
308                 writeln("<conditions>");
309                 indent++;
310                 
311                 writeElement("configid", cond.getMotorConfigurationID());
312                 writeElement("launchrodlength", cond.getLaunchRodLength());
313                 writeElement("launchrodangle", cond.getLaunchRodAngle() * 180.0 / Math.PI);
314                 writeElement("launchroddirection", cond.getLaunchRodDirection() * 180.0 / Math.PI);
315                 writeElement("windaverage", cond.getWindSpeedAverage());
316                 writeElement("windturbulence", cond.getWindTurbulenceIntensity());
317                 writeElement("launchaltitude", cond.getLaunchAltitude());
318                 writeElement("launchlatitude", cond.getLaunchLatitude());
319                 writeElement("launchlongitude", cond.getLaunchLongitude());
320                 writeElement("geodeticmethod", cond.getGeodeticComputation().name().toLowerCase());
321                 
322                 if (cond.isISAAtmosphere()) {
323                         writeln("<atmosphere model=\"isa\"/>");
324                 } else {
325                         writeln("<atmosphere model=\"extendedisa\">");
326                         indent++;
327                         writeElement("basetemperature", cond.getLaunchTemperature());
328                         writeElement("basepressure", cond.getLaunchPressure());
329                         indent--;
330                         writeln("</atmosphere>");
331                 }
332                 
333                 writeElement("timestep", cond.getTimeStep());
334                 
335                 indent--;
336                 writeln("</conditions>");
337                 
338
339                 for (String s : simulation.getSimulationListeners()) {
340                         writeElement("listener", escapeXML(s));
341                 }
342                 
343
344                 // Write basic simulation data
345                 
346                 FlightData data = simulation.getSimulatedData();
347                 if (data != null) {
348                         String str = "<flightdata";
349                         if (!Double.isNaN(data.getMaxAltitude()))
350                                 str += " maxaltitude=\"" + TextUtil.doubleToString(data.getMaxAltitude()) + "\"";
351                         if (!Double.isNaN(data.getMaxVelocity()))
352                                 str += " maxvelocity=\"" + TextUtil.doubleToString(data.getMaxVelocity()) + "\"";
353                         if (!Double.isNaN(data.getMaxAcceleration()))
354                                 str += " maxacceleration=\"" + TextUtil.doubleToString(data.getMaxAcceleration()) + "\"";
355                         if (!Double.isNaN(data.getMaxMachNumber()))
356                                 str += " maxmach=\"" + TextUtil.doubleToString(data.getMaxMachNumber()) + "\"";
357                         if (!Double.isNaN(data.getTimeToApogee()))
358                                 str += " timetoapogee=\"" + TextUtil.doubleToString(data.getTimeToApogee()) + "\"";
359                         if (!Double.isNaN(data.getFlightTime()))
360                                 str += " flighttime=\"" + TextUtil.doubleToString(data.getFlightTime()) + "\"";
361                         if (!Double.isNaN(data.getGroundHitVelocity()))
362                                 str += " groundhitvelocity=\"" + TextUtil.doubleToString(data.getGroundHitVelocity()) + "\"";
363                         if (!Double.isNaN(data.getLaunchRodVelocity()))
364                                 str += " launchrodvelocity=\"" + TextUtil.doubleToString(data.getLaunchRodVelocity()) + "\"";
365                         if (!Double.isNaN(data.getDeploymentVelocity()))
366                                 str += " deploymentvelocity=\"" + TextUtil.doubleToString(data.getDeploymentVelocity()) + "\"";
367                         str += ">";
368                         writeln(str);
369                         indent++;
370                         
371                         for (Warning w : data.getWarningSet()) {
372                                 writeElement("warning", escapeXML(w.toString()));
373                         }
374                         
375                         // Check whether to store data
376                         if (simulation.getStatus() == Simulation.Status.EXTERNAL) // Always store external data
377                                 timeSkip = 0;
378                         
379                         if (timeSkip != StorageOptions.SIMULATION_DATA_NONE) {
380                                 for (int i = 0; i < data.getBranchCount(); i++) {
381                                         FlightDataBranch branch = data.getBranch(i);
382                                         saveFlightDataBranch(branch, timeSkip);
383                                 }
384                         }
385                         
386                         indent--;
387                         writeln("</flightdata>");
388                 }
389                 
390                 indent--;
391                 writeln("</simulation>");
392                 
393         }
394         
395         
396
397         private void saveFlightDataBranch(FlightDataBranch branch, double timeSkip)
398                         throws IOException {
399                 double previousTime = -100000;
400                 
401                 if (branch == null)
402                         return;
403                 
404                 // Retrieve the types from the branch
405                 FlightDataType[] types = branch.getTypes();
406                 
407                 if (types.length == 0)
408                         return;
409                 
410                 // Retrieve the data from the branch
411                 List<List<Double>> data = new ArrayList<List<Double>>(types.length);
412                 for (int i = 0; i < types.length; i++) {
413                         data.add(branch.get(types[i]));
414                 }
415                 List<Double> timeData = branch.get(FlightDataType.TYPE_TIME);
416                 
417                 // Build the <databranch> tag
418                 StringBuilder sb = new StringBuilder();
419                 sb.append("<databranch name=\"");
420                 sb.append(escapeXML(branch.getBranchName()));
421                 sb.append("\" types=\"");
422                 for (int i = 0; i < types.length; i++) {
423                         if (i > 0)
424                                 sb.append(",");
425                         sb.append(escapeXML(types[i].getName()));
426                 }
427                 sb.append("\">");
428                 writeln(sb.toString());
429                 indent++;
430                 
431                 // Write events
432                 for (FlightEvent event : branch.getEvents()) {
433                         writeln("<event time=\"" + TextUtil.doubleToString(event.getTime())
434                                         + "\" type=\"" + enumToXMLName(event.getType()) + "\"/>");
435                 }
436                 
437                 // Write the data
438                 int length = branch.getLength();
439                 if (length > 0) {
440                         writeDataPointString(data, 0, sb);
441                         previousTime = timeData.get(0);
442                 }
443                 
444                 for (int i = 1; i < length - 1; i++) {
445                         if (timeData != null) {
446                                 if (Math.abs(timeData.get(i) - previousTime - timeSkip) < Math.abs(timeData.get(i + 1) - previousTime - timeSkip)) {
447                                         writeDataPointString(data, i, sb);
448                                         previousTime = timeData.get(i);
449                                 }
450                         } else {
451                                 // If time data is not available, write all points
452                                 writeDataPointString(data, i, sb);
453                         }
454                 }
455                 
456                 if (length > 1) {
457                         writeDataPointString(data, length - 1, sb);
458                 }
459                 
460                 indent--;
461                 writeln("</databranch>");
462         }
463         
464         
465
466         /* TODO: LOW: This is largely duplicated from above! */
467         private int countFlightDataBranchPoints(FlightDataBranch branch, double timeSkip) {
468                 int count = 0;
469                 
470                 double previousTime = -100000;
471                 
472                 if (branch == null)
473                         return 0;
474                 
475                 // Retrieve the types from the branch
476                 FlightDataType[] types = branch.getTypes();
477                 
478                 if (types.length == 0)
479                         return 0;
480                 
481                 List<Double> timeData = branch.get(FlightDataType.TYPE_TIME);
482                 if (timeData == null) {
483                         // If time data not available, store all points
484                         return branch.getLength();
485                 }
486                 
487                 // Write the data
488                 int length = branch.getLength();
489                 if (length > 0) {
490                         count++;
491                         previousTime = timeData.get(0);
492                 }
493                 
494                 for (int i = 1; i < length - 1; i++) {
495                         if (Math.abs(timeData.get(i) - previousTime - timeSkip) < Math.abs(timeData.get(i + 1) - previousTime - timeSkip)) {
496                                 count++;
497                                 previousTime = timeData.get(i);
498                         }
499                 }
500                 
501                 if (length > 1) {
502                         count++;
503                 }
504                 
505                 return count;
506         }
507         
508         
509
510         private void writeDataPointString(List<List<Double>> data, int index, StringBuilder sb)
511                         throws IOException {
512                 sb.setLength(0);
513                 sb.append("<datapoint>");
514                 for (int j = 0; j < data.size(); j++) {
515                         if (j > 0)
516                                 sb.append(",");
517                         sb.append(TextUtil.doubleToString(data.get(j).get(index)));
518                 }
519                 sb.append("</datapoint>");
520                 writeln(sb.toString());
521         }
522         
523         
524
525         private void writeElement(String element, Object content) throws IOException {
526                 if (content == null)
527                         content = "";
528                 writeln("<" + element + ">" + content + "</" + element + ">");
529         }
530         
531         
532
533         private void writeln(String str) throws IOException {
534                 if (str.length() == 0) {
535                         dest.write("\n");
536                         return;
537                 }
538                 String s = "";
539                 for (int i = 0; i < indent; i++)
540                         s = s + "  ";
541                 s = s + str + "\n";
542                 dest.write(s);
543         }
544         
545         
546
547
548         /**
549          * Return the XML equivalent of an enum name.
550          * 
551          * @param e             the enum to save.
552          * @return              the corresponding XML name.
553          */
554         public static String enumToXMLName(Enum<?> e) {
555                 return e.name().toLowerCase().replace("_", "");
556         }
557         
558 }