59fb05a3da739dbd1d7ec4086742d54998ef3657
[debian/openrocket] / core / src / net / sf / openrocket / file / rocksim / importt / BaseHandler.java
1 /*
2  * BaseHandler.java
3  */
4 package net.sf.openrocket.file.rocksim.importt;
5
6 import net.sf.openrocket.aerodynamics.WarningSet;
7 import net.sf.openrocket.file.simplesax.ElementHandler;
8 import net.sf.openrocket.material.Material;
9 import net.sf.openrocket.rocketcomponent.RocketComponent;
10 import org.xml.sax.SAXException;
11
12 import java.lang.reflect.InvocationTargetException;
13 import java.lang.reflect.Method;
14 import java.util.HashMap;
15
16 /**
17  * An abstract base class that handles common parsing.  All Rocksim component handlers are subclassed from here.
18  *
19  * @param <C>   the specific RocketComponent subtype for which the concrete handler can create
20  */
21 public abstract class BaseHandler<C extends RocketComponent> extends ElementHandler {
22
23     /**
24      * Prepend rocksim materials.
25      */
26     public static final String ROCKSIM_MATERIAL_PREFIX = "RS: ";
27     /**
28      * The overridden mass.
29      */
30     private Double mass = 0d;
31     /**
32      * The overridden Cg.
33      */
34     private Double cg = 0d;
35     /**
36      * The density of the material in the component.
37      */
38     private Double density = 0d;
39     /**
40      * The internal Rocksim density type.
41      */
42     private RocksimDensityType densityType = RocksimDensityType.ROCKSIM_BULK;
43
44     /**
45      * The material name.
46      */
47     private String materialName = "";
48
49     /**
50      * The SAX method called when the closing element tag is reached.
51      *
52      * @param element        the element name.
53      * @param attributes    attributes of the element.
54      * @param content        the textual content of the element.
55      * @param warnings        the warning set to store warnings in.
56      * @throws SAXException
57      */
58
59     @Override
60     public void closeElement(String element, HashMap<String, String> attributes, String content, WarningSet warnings)
61             throws SAXException {
62         final C component = getComponent();
63         try {
64             if ("Name".equals(element)) {
65                 component.setName(content);
66             }
67             if ("KnownMass".equals(element)) {
68                 mass = Math.max(0d, Double.parseDouble(content) / RocksimHandler.ROCKSIM_TO_OPENROCKET_MASS);
69             }
70             if ("Density".equals(element)) {
71                 density = Math.max(0d, Double.parseDouble(content) );
72             }
73             if ("KnownCG".equals(element)) {
74                 cg = Math.max(0d, Double.parseDouble(content) / RocksimHandler.ROCKSIM_TO_OPENROCKET_LENGTH);
75             }
76             if ("UseKnownCG".equals(element)) {  //Rocksim sets UseKnownCG to true to control the override of both cg and mass
77                 boolean override = "1".equals(content);
78                 setOverride(component, override, mass, cg);
79             }
80             if ("DensityType".equals(element)) {
81                 densityType = RocksimDensityType.fromCode(Integer.parseInt(content));
82             }
83         }
84         catch (NumberFormatException nfe) {
85             warnings.add("Could not convert " + element + " value of " + content + ".  It is expected to be a number.");
86         }
87     }
88
89     /**
90      * {@inheritDoc}
91      */
92     @Override
93     public void endHandler(String element, HashMap<String, String> attributes, String content, WarningSet warnings)
94             throws SAXException {
95         /* Because of the order of XML elements in Rocksim, not all information is known at the time it really needs
96            to be acted upon.  So we keep temporary instance variables to be used here at the end of the parsing.
97          */
98         density = computeDensity(densityType, density);
99         RocketComponent component = getComponent();
100         updateComponentMaterial(component, materialName, getMaterialType(), density);
101     }
102
103     /**
104      * Compute the density.  Rocksim does strange things with densities.  For some streamer material it's in cubic,
105      * rather than square, units.  In those cases it needs to be converted to an appropriate SURFACE material density.
106      * Some G10 fiberglass materials are in cubic units, other G10 fiberglass is in square units.  And due to a
107      * Rocksim bug, some densities are 0 when they clearly should not be.
108      *
109      * This may be overridden for specific component density computations.
110      *
111      * @param type       the rocksim density
112      * @param rawDensity the density as specified in the Rocksim design file
113      * @return a value in OpenRocket SURFACE density units
114      */
115     protected double computeDensity(RocksimDensityType type, double rawDensity) {
116         return rawDensity / type.asOpenRocket();
117     }
118
119     /**
120      * If the Rocksim component does not override the mass, then create a Material based upon the density defined
121      * for that component.  This *should* result in a consistent representation of Cg between Rocksim and OpenRocket.
122      *
123      * @param component       the component
124      * @param type            the type of the material
125      * @param density         the density in g/cm^3
126      * @param definedMaterial the material that is currently defined on the component; used only to get the name
127      *                        as it appears in Rocksim
128      */
129     public static void updateComponentMaterial(RocketComponent component, String definedMaterial, Material.Type type,
130                                                double density) {
131         if (definedMaterial != null) {
132             Material custom = createCustomMaterial(type, definedMaterial, density);
133             setMaterial(component, custom);
134         }
135     }
136
137     /**
138      * Override the mass and Cg of the component.
139      *
140      * @param component  the component
141      * @param override   true if any override should happen
142      * @param mass       the override mass
143      * @param cg         the override cg
144      */
145     public static void setOverride(RocketComponent component, boolean override, double mass, double cg) {
146         if (override) {
147             component.setCGOverridden(override);
148             component.setMassOverridden(override);
149             component.setOverrideSubcomponents(false); //Rocksim does not support this type of override
150             component.setOverrideMass(mass);
151             component.setOverrideCGX(cg);
152         }
153     }
154
155     /**
156      * Get the component this handler is working upon.
157      *
158      * @return a component
159      */
160     protected abstract C getComponent();
161
162     /**
163      * Get the required type of material for this component.
164      *
165      * @return the required material type
166      */
167     protected abstract Material.Type getMaterialType();
168
169     /**
170      * Some CG positions in Rocksim do not correspond to the CG position reference in OpenRocket.
171      *
172      * @param theCG  the CG value to really use when overriding CG on the OpenRocket component
173      */
174     protected void setCG(double theCG) {
175         cg = theCG;
176     }
177
178     /**
179      * Set the material name as specified in the Rocksim design file.
180      *
181      * @param content  the material name
182      */
183     protected void setMaterialName(String content) {
184         materialName = content;
185     }
186
187     /**
188      * Add child to parent only if the child is compatible.  Otherwise add to warning set.
189      * 
190      * @param parent  the parent component
191      * @param child   the child component
192      * @param warnings the warning set
193      * 
194      * @return true if the child is compatible with parent
195      */
196     protected static boolean isCompatible(RocketComponent parent, Class<? extends RocketComponent> child, WarningSet warnings) {
197         if (!parent.isCompatible(child)) {
198             warnings.add(child.getName() + " can not be attached to "
199                          + parent.getComponentName() + ", ignoring component.");
200             return false;
201         }
202         else {
203             return true;
204         }
205     }
206     
207     /**
208      * Create a custom material based on the density.  The name of the material is prepended with 'RS: ' to
209      * indicate it came from a RockSim material.
210      *
211      * @param type    the type of the material
212      * @param name    the name of the component
213      * @param density the density
214      *
215      * @return a Material instance
216      */
217     public static Material createCustomMaterial(Material.Type type, String name, double density) {
218         return Material.newMaterial(type, ROCKSIM_MATERIAL_PREFIX + name, density, true);
219     }
220
221     /**
222      * Set the material onto an instance of RocketComponent.  This is done because only some subtypes of RocketComponent
223      * have the setMaterial method.  Unfortunately the supertype cannot be used.
224      *
225      * @param component  the component who's material is to be set
226      * @param material the material to be set on the component (defined by getComponent())
227      */
228     private static void setMaterial(RocketComponent component, Material material) {
229         try {
230             final Method method = getMethod(component, "setMaterial", new Class[]{Material.class});
231             if (method != null) {
232                 method.invoke(component, material);
233             }
234         }
235         catch (IllegalAccessException ignored) {
236         }
237         catch (InvocationTargetException ignored) {
238         }
239     }
240
241     /**
242      * Find a method by name and argument list.
243      *
244      * @param component  the component who's material is to be seta
245      * @param name the method name
246      * @param args the class types of the parameters
247      *
248      * @return the Method instance, or null
249      */
250     private static Method getMethod(RocketComponent component, String name, Class[] args) {
251         Method method = null;
252         try {
253             method = component.getClass().getMethod(name, args);
254         }
255         catch (NoSuchMethodException ignored) {
256         }
257         return method;
258     }
259
260 }