1 package tim.prune.save;
3 import java.awt.BorderLayout;
4 import java.awt.Component;
5 import java.awt.FlowLayout;
6 import java.awt.GridLayout;
7 import java.awt.event.ActionEvent;
8 import java.awt.event.ActionListener;
10 import java.io.FileWriter;
11 import java.io.IOException;
12 import java.util.ArrayList;
13 import java.util.Iterator;
15 import javax.imageio.ImageIO;
16 import javax.swing.BorderFactory;
17 import javax.swing.Box;
18 import javax.swing.BoxLayout;
19 import javax.swing.ButtonGroup;
20 import javax.swing.JButton;
21 import javax.swing.JDialog;
22 import javax.swing.JFileChooser;
23 import javax.swing.JLabel;
24 import javax.swing.JOptionPane;
25 import javax.swing.JPanel;
26 import javax.swing.JRadioButton;
27 import javax.swing.JTextField;
28 import javax.swing.SwingConstants;
31 import tim.prune.FunctionLibrary;
32 import tim.prune.I18nManager;
33 import tim.prune.UpdateMessageBroker;
34 import tim.prune.config.Config;
35 import tim.prune.data.NumberUtils;
36 import tim.prune.data.Track;
37 import tim.prune.function.Export3dFunction;
38 import tim.prune.function.srtm.LookupSrtmFunction;
39 import tim.prune.gui.BaseImageDefinitionPanel;
40 import tim.prune.gui.DialogCloser;
41 import tim.prune.gui.TerrainDefinitionPanel;
42 import tim.prune.gui.map.MapSource;
43 import tim.prune.gui.map.MapSourceLibrary;
44 import tim.prune.load.GenericFileFilter;
45 import tim.prune.threedee.ImageDefinition;
46 import tim.prune.threedee.TerrainCache;
47 import tim.prune.threedee.TerrainDefinition;
48 import tim.prune.threedee.TerrainHelper;
49 import tim.prune.threedee.ThreeDModel;
52 * Class to export a 3d scene of the track to a specified Pov file
54 public class PovExporter extends Export3dFunction
56 private Track _track = null;
57 private JDialog _dialog = null;
58 private JFileChooser _fileChooser = null;
59 private String _cameraX = null, _cameraY = null, _cameraZ = null;
60 private JTextField _cameraXField = null, _cameraYField = null, _cameraZField = null;
61 private JTextField _fontName = null, _altitudeFactorField = null;
62 private JRadioButton _ballsAndSticksButton = null;
63 /** Panel for defining the base image */
64 private BaseImageDefinitionPanel _baseImagePanel = null;
65 /** Component for defining the terrain */
66 private TerrainDefinitionPanel _terrainPanel = null;
69 private static final double DEFAULT_CAMERA_DISTANCE = 30.0;
70 private static final double MODEL_SCALE_FACTOR = 20.0;
71 private static final String DEFAULT_FONT_FILE = "crystal.ttf";
76 * @param inApp App object
78 public PovExporter(App inApp)
81 _track = inApp.getTrackInfo().getTrack();
82 // Set default camera coordinates
83 _cameraX = "17"; _cameraY = "13"; _cameraZ = "-20";
86 /** Get the name key */
87 public String getNameKey() {
88 return "function.exportpov";
92 * Set the coordinates for the camera (can be any scale)
93 * @param inX X coordinate of camera
94 * @param inY Y coordinate of camera
95 * @param inZ Z coordinate of camera
97 public void setCameraCoordinates(double inX, double inY, double inZ)
99 // calculate distance from origin
100 double cameraDist = Math.sqrt(inX*inX + inY*inY + inZ*inZ);
101 if (cameraDist > 0.0)
103 _cameraX = NumberUtils.formatNumberUk(inX / cameraDist * DEFAULT_CAMERA_DISTANCE, 5);
104 _cameraY = NumberUtils.formatNumberUk(inY / cameraDist * DEFAULT_CAMERA_DISTANCE, 5);
105 // Careful! Need to convert from java3d (right-handed) to povray (left-handed) coordinate system!
106 _cameraZ = NumberUtils.formatNumberUk(-inZ / cameraDist * DEFAULT_CAMERA_DISTANCE, 5);
112 * Show the dialog to select options and export file
116 // Make dialog window to select inputs
119 _dialog = new JDialog(_parentFrame, I18nManager.getText(getNameKey()), true);
120 _dialog.setLocationRelativeTo(_parentFrame);
121 _dialog.getContentPane().add(makeDialogComponents());
123 // Get exaggeration factor from config
124 final int exaggFactor = Config.getConfigInt(Config.KEY_HEIGHT_EXAGGERATION);
125 if (exaggFactor > 0) {
126 _altFactor = exaggFactor / 100.0;
130 _cameraXField.setText(_cameraX);
131 _cameraYField.setText(_cameraY);
132 _cameraZField.setText(_cameraZ);
133 _altitudeFactorField.setText("" + _altFactor);
134 // Pass terrain and image def parameters (if any) to the panels
135 if (_terrainDef != null) {
136 _terrainPanel.initTerrainParameters(_terrainDef);
138 if (_imageDef != null) {
139 _baseImagePanel.initImageParameters(_imageDef);
141 _baseImagePanel.updateBaseImageDetails();
144 _dialog.setVisible(true);
149 * Make the dialog components to select the export options
150 * @return Component holding gui elements
152 private Component makeDialogComponents()
154 JPanel panel = new JPanel();
155 panel.setLayout(new BorderLayout(4, 4));
156 JLabel introLabel = new JLabel(I18nManager.getText("dialog.exportpov.text"));
157 introLabel.setBorder(BorderFactory.createEmptyBorder(4, 4, 6, 4));
158 panel.add(introLabel, BorderLayout.NORTH);
159 // OK, Cancel buttons
160 JPanel buttonPanel = new JPanel();
161 buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
162 JButton okButton = new JButton(I18nManager.getText("button.ok"));
163 okButton.addActionListener(new ActionListener() {
164 public void actionPerformed(ActionEvent e)
166 // Need to launch export in new thread
167 new Thread(new Runnable() {
171 _baseImagePanel.getGrouter().clearMapImage();
177 buttonPanel.add(okButton);
178 JButton cancelButton = new JButton(I18nManager.getText("button.cancel"));
179 cancelButton.addActionListener(new ActionListener() {
180 public void actionPerformed(ActionEvent e)
182 _baseImagePanel.getGrouter().clearMapImage();
186 buttonPanel.add(cancelButton);
187 panel.add(buttonPanel, BorderLayout.SOUTH);
190 JPanel centralPanel = new JPanel();
191 centralPanel.setLayout(new GridLayout(0, 2, 10, 4));
193 JLabel fontLabel = new JLabel(I18nManager.getText("dialog.exportpov.font"));
194 fontLabel.setHorizontalAlignment(SwingConstants.TRAILING);
195 centralPanel.add(fontLabel);
196 String defaultFont = Config.getConfigString(Config.KEY_POVRAY_FONT);
197 if (defaultFont == null || defaultFont.equals("")) {
198 defaultFont = DEFAULT_FONT_FILE;
200 _fontName = new JTextField(defaultFont, 12);
201 _fontName.setAlignmentX(Component.LEFT_ALIGNMENT);
202 _fontName.addKeyListener(new DialogCloser(_dialog));
203 centralPanel.add(_fontName);
204 //coordinates of camera
205 JLabel cameraXLabel = new JLabel(I18nManager.getText("dialog.exportpov.camerax"));
206 cameraXLabel.setHorizontalAlignment(SwingConstants.TRAILING);
207 centralPanel.add(cameraXLabel);
208 _cameraXField = new JTextField("" + _cameraX);
209 centralPanel.add(_cameraXField);
210 JLabel cameraYLabel = new JLabel(I18nManager.getText("dialog.exportpov.cameray"));
211 cameraYLabel.setHorizontalAlignment(SwingConstants.TRAILING);
212 centralPanel.add(cameraYLabel);
213 _cameraYField = new JTextField("" + _cameraY);
214 centralPanel.add(_cameraYField);
215 JLabel cameraZLabel = new JLabel(I18nManager.getText("dialog.exportpov.cameraz"));
216 cameraZLabel.setHorizontalAlignment(SwingConstants.TRAILING);
217 centralPanel.add(cameraZLabel);
218 _cameraZField = new JTextField("" + _cameraZ);
219 centralPanel.add(_cameraZField);
220 // Altitude exaggeration
221 JLabel altitudeCapLabel = new JLabel(I18nManager.getText("dialog.3d.altitudefactor"));
222 altitudeCapLabel.setHorizontalAlignment(SwingConstants.TRAILING);
223 centralPanel.add(altitudeCapLabel);
224 _altitudeFactorField = new JTextField("1.0");
225 centralPanel.add(_altitudeFactorField);
227 // Radio buttons for style - balls on sticks or tubes
228 JPanel stylePanel = new JPanel();
229 stylePanel.setLayout(new GridLayout(0, 2, 10, 4));
230 JLabel styleLabel = new JLabel(I18nManager.getText("dialog.exportpov.modelstyle"));
231 styleLabel.setHorizontalAlignment(SwingConstants.TRAILING);
232 stylePanel.add(styleLabel);
233 JPanel radioPanel = new JPanel();
234 radioPanel.setLayout(new BoxLayout(radioPanel, BoxLayout.Y_AXIS));
235 _ballsAndSticksButton = new JRadioButton(I18nManager.getText("dialog.exportpov.ballsandsticks"));
236 _ballsAndSticksButton.setSelected(false);
237 radioPanel.add(_ballsAndSticksButton);
238 JRadioButton tubesButton = new JRadioButton(I18nManager.getText("dialog.exportpov.tubesandwalls"));
239 tubesButton.setSelected(true);
240 radioPanel.add(tubesButton);
241 ButtonGroup group = new ButtonGroup();
242 group.add(_ballsAndSticksButton); group.add(tubesButton);
243 stylePanel.add(radioPanel);
245 // Panel for the base image (parent is null because we don't need callback)
246 _baseImagePanel = new BaseImageDefinitionPanel(null, _dialog, _track);
247 // Panel for the terrain definition
248 _terrainPanel = new TerrainDefinitionPanel();
250 // add these panels to the holder panel
251 JPanel holderPanel = new JPanel();
252 holderPanel.setLayout(new BorderLayout(5, 5));
253 JPanel boxPanel = new JPanel();
254 boxPanel.setLayout(new BoxLayout(boxPanel, BoxLayout.Y_AXIS));
255 boxPanel.add(centralPanel);
256 boxPanel.add(Box.createVerticalStrut(4));
257 boxPanel.add(stylePanel);
258 boxPanel.add(Box.createVerticalStrut(4));
259 boxPanel.add(_terrainPanel);
260 boxPanel.add(Box.createVerticalStrut(4));
261 boxPanel.add(_baseImagePanel);
262 holderPanel.add(boxPanel, BorderLayout.CENTER);
264 panel.add(holderPanel, BorderLayout.CENTER);
270 * Select the file and export data to it
272 private void doExport()
274 // Copy camera coordinates
275 _cameraX = checkCoordinate(_cameraXField.getText());
276 _cameraY = checkCoordinate(_cameraYField.getText());
277 _cameraZ = checkCoordinate(_cameraZField.getText());
279 // OK pressed, so choose output file
280 if (_fileChooser == null)
282 _fileChooser = new JFileChooser();
283 _fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
284 _fileChooser.setFileFilter(new GenericFileFilter("filetype.pov", new String[] {"pov"}));
285 _fileChooser.setAcceptAllFileFilterUsed(false);
286 // start from directory in config which should be set
287 final String configDir = Config.getConfigString(Config.KEY_TRACK_DIR);
288 if (configDir != null) {_fileChooser.setCurrentDirectory(new File(configDir));}
291 // Allow choose again if an existing file is selected
292 boolean chooseAgain = false;
296 if (_fileChooser.showSaveDialog(_parentFrame) == JFileChooser.APPROVE_OPTION)
298 // OK pressed and file chosen
299 File povFile = _fileChooser.getSelectedFile();
300 if (!povFile.getName().toLowerCase().endsWith(".pov"))
302 povFile = new File(povFile.getAbsolutePath() + ".pov");
304 final int nameLen = povFile.getName().length() - 4;
305 final File imageFile = new File(povFile.getParentFile(), povFile.getName().substring(0, nameLen) + "_base.png");
306 final File terrainFile = new File(povFile.getParentFile(), povFile.getName().substring(0, nameLen) + "_terrain.png");
307 final boolean imageExists = _baseImagePanel.getImageDefinition().getUseImage() && imageFile.exists();
308 final boolean terrainFileExists = _terrainPanel.getUseTerrain() && terrainFile.exists();
310 // Check if files exist and if necessary prompt for overwrite
311 Object[] buttonTexts = {I18nManager.getText("button.overwrite"), I18nManager.getText("button.cancel")};
312 if ((!povFile.exists() && !imageExists && !terrainFileExists)
313 || JOptionPane.showOptionDialog(_parentFrame,
314 I18nManager.getText("dialog.save.overwrite.text"),
315 I18nManager.getText("dialog.save.overwrite.title"), JOptionPane.YES_NO_OPTION,
316 JOptionPane.WARNING_MESSAGE, null, buttonTexts, buttonTexts[1])
317 == JOptionPane.YES_OPTION)
319 // Export the file(s)
320 if (exportFiles(povFile, imageFile, terrainFile))
322 // file saved - store directory in config for later
323 Config.setConfigString(Config.KEY_TRACK_DIR, povFile.getParentFile().getAbsolutePath());
324 // also store exaggeration
325 Config.setConfigInt(Config.KEY_HEIGHT_EXAGGERATION, (int) (_altFactor * 100));
329 // export failed so need to choose again
335 // overwrite cancelled so need to choose again
339 } while (chooseAgain);
344 * Export the data to the specified file(s)
345 * @param inPovFile File object to save pov file to
346 * @param inImageFile file object to save image to
347 * @param inTerrainFile file object to save terrain to
348 * @return true if successful
350 private boolean exportFiles(File inPovFile, File inImageFile, File inTerrainFile)
352 FileWriter writer = null;
353 // find out the line separator for this system
354 final String lineSeparator = System.getProperty("line.separator");
357 // create and scale model
358 ThreeDModel model = new ThreeDModel(_track);
359 model.setModelSize(MODEL_SCALE_FACTOR);
362 // try to use given altitude cap
363 double givenFactor = Double.parseDouble(_altitudeFactorField.getText());
364 if (givenFactor > 0.0) _altFactor = givenFactor;
366 catch (NumberFormatException nfe) { // parse failed, reset
367 _altitudeFactorField.setText("" + _altFactor);
369 model.setAltitudeFactor(_altFactor);
371 // Write base image if necessary
372 ImageDefinition imageDef = _baseImagePanel.getImageDefinition();
373 boolean useImage = imageDef.getUseImage();
376 // Get base image from grouter
377 MapSource mapSource = MapSourceLibrary.getSource(imageDef.getSourceIndex());
378 MapGrouter grouter = _baseImagePanel.getGrouter();
379 GroutedImage baseImage = grouter.getMapImage(_track, mapSource, imageDef.getZoom());
382 useImage = ImageIO.write(baseImage.getImage(), "png", inImageFile);
384 catch (IOException ioe) {
385 System.err.println("Can't write image: " + ioe.getClass().getName());
389 _app.showErrorMessage(getNameKey(), "dialog.exportpov.cannotmakebaseimage");
393 boolean useTerrain = _terrainPanel.getUseTerrain();
396 TerrainHelper terrainHelper = new TerrainHelper(_terrainPanel.getGridSize());
397 // See if there's a previously saved terrain track we can reuse
398 TerrainDefinition terrainDef = new TerrainDefinition(_terrainPanel.getUseTerrain(), _terrainPanel.getGridSize());
399 Track terrainTrack = TerrainCache.getTerrainTrack(_app.getCurrentDataStatus(), terrainDef);
400 if (terrainTrack == null)
402 // Construct the terrain track according to these extents and the grid size
403 terrainTrack = terrainHelper.createGridTrack(_track);
404 // Get the altitudes from SRTM for all the points in the track
405 LookupSrtmFunction srtmLookup = (LookupSrtmFunction) FunctionLibrary.FUNCTION_LOOKUP_SRTM;
406 srtmLookup.begin(terrainTrack);
407 while (srtmLookup.isRunning())
410 Thread.sleep(750); // just polling in a wait loop isn't ideal but simple
412 catch (InterruptedException e) {}
415 terrainHelper.fixVoids(terrainTrack);
417 // Store this back in the cache, maybe we'll need it again
418 TerrainCache.storeTerrainTrack(terrainTrack, _app.getCurrentDataStatus(), terrainDef);
421 model.setTerrain(terrainTrack);
424 // Call TerrainHelper to write out the data from the model
425 terrainHelper.writeHeightMap(model, inTerrainFile);
429 // No terrain required, so just scale the model as it is
433 // Create file and write basics
434 writer = new FileWriter(inPovFile);
435 writeStartOfFile(writer, lineSeparator, useImage ? inImageFile : null, useTerrain ? inTerrainFile : null);
438 if (_ballsAndSticksButton.isSelected()) {
439 writeDataPointsBallsAndSticks(writer, model, lineSeparator);
442 writeDataPointsTubesAndWalls(writer, model, lineSeparator);
446 UpdateMessageBroker.informSubscribers(I18nManager.getText("confirm.save.ok1")
447 + " " + _track.getNumPoints() + " " + I18nManager.getText("confirm.save.ok2")
448 + " " + inPovFile.getAbsolutePath());
451 catch (IOException ioe)
453 JOptionPane.showMessageDialog(_parentFrame, I18nManager.getText("error.save.failed") + " : " + ioe.getMessage(),
454 I18nManager.getText("error.save.dialogtitle"), JOptionPane.ERROR_MESSAGE);
458 // close file ignoring exceptions
463 catch (Exception e) {}
470 * Write the start of the Pov file, including base plane and lights
471 * @param inWriter Writer to use for writing file
472 * @param inLineSeparator line separator to use
473 * @param inImageFile image file to reference (or null if none)
474 * @param inTerrainFile terrain file to reference (or null if none)
475 * @throws IOException on file writing error
477 private void writeStartOfFile(FileWriter inWriter, String inLineSeparator, File inImageFile, File inTerrainFile)
480 inWriter.write("// Pov file produced by GpsPrune - see http://gpsprune.activityworkshop.net/");
481 inWriter.write(inLineSeparator);
482 inWriter.write("#version 3.6;");
483 inWriter.write(inLineSeparator);
484 inWriter.write(inLineSeparator);
485 // Select font based on user input
486 String fontPath = _fontName.getText();
487 if (fontPath == null || fontPath.equals(""))
489 fontPath = DEFAULT_FONT_FILE;
492 Config.setConfigString(Config.KEY_POVRAY_FONT, fontPath);
495 // Make the definition of the base plane depending on whether there's an image or not
496 final boolean useImage = (inImageFile != null);
497 final boolean useImageOnBox = useImage && (inTerrainFile == null);
498 final String boxDefinition = (useImageOnBox ?
499 " <0, 0, 0>, <1, 1, 0.001>" + inLineSeparator
500 + " pigment {image_map { png \"" + inImageFile.getName() + "\" map_type 0 interpolate 2 once } }" + inLineSeparator
501 + " scale 20.0 rotate <90, 0, 0>" + inLineSeparator
502 + " translate <-10.0, 0, -10.0>"
503 : " <-10.0, -0.15, -10.0>," + inLineSeparator
504 + " <10.0, 0.0, 10.0>" + inLineSeparator
505 + " pigment { color rgb <0.5 0.75 0.8> }");
506 // TODO: Maybe could use the same geometry for the imageless case, would simplify code a bit
508 // Definition of terrain shape if any
509 final String terrainDefinition = makeTerrainString(inTerrainFile, inImageFile, inLineSeparator);
512 String[] outputLines = {
513 "global_settings { ambient_light rgb <4, 4, 4> }", "",
514 "// Background and camera",
515 "background { color rgb <0, 0, 0> }",
518 " location <" + _cameraX + ", " + _cameraY + ", " + _cameraZ + ">",
519 " look_at <0, 0, 0>",
522 "// Global declares",
523 "#declare point_rod =",
530 " pigment { color rgb <0.5 0.5 0.5> }",
531 useImage ? " } no_shadow" : " }",
533 // MAYBE: Export rods to POV? How to store in data?
534 "#declare waypoint_sphere =",
538 " pigment {color rgb <0.1 0.1 1.0>}",
539 " finish { phong 1 }",
540 useImage ? " } no_shadow" : " }",
542 "#declare track_sphere0 =",
544 " <0, 0, 0>, 0.3", // size should depend on model size
546 " pigment {color rgb <0.1 0.6 0.1>}", // dark green
547 " finish { phong 1 }",
550 "#declare track_sphere1 =",
552 " <0, 0, 0>, 0.3", // size should depend on model size
554 " pigment {color rgb <0.4 0.9 0.2>}", // green
555 " finish { phong 1 }",
558 "#declare track_sphere2 =",
560 " <0, 0, 0>, 0.3", // size should depend on model size
562 " pigment {color rgb <0.7 0.8 0.2>}", // yellow
563 " finish { phong 1 }",
566 "#declare track_sphere3 =",
568 " <0, 0, 0>, 0.3", // size should depend on model size
570 " pigment {color rgb <0.5 0.8 0.6>}", // greeny
571 " finish { phong 1 }",
574 "#declare track_sphere4 =",
576 " <0, 0, 0>, 0.3", // size should depend on model size
578 " pigment {color rgb <0.2 0.9 0.9>}", // cyan
579 " finish { phong 1 }",
582 "#declare track_sphere5 =",
584 " <0, 0, 0>, 0.3", // size should depend on model size
586 " pigment {color rgb <1.0 1.0 1.0>}", // white
587 " finish { phong 1 }",
590 "#declare track_sphere_t =",
592 " <0, 0, 0>, 0.25", // size should depend on model size
594 " pigment {color rgb <0.6 1.0 0.2>}",
595 " finish { phong 1 }",
598 "#declare wall_colour = rgbt <0.5, 0.5, 0.5, 0.3>;", "",
606 "// Cardinal letters N,S,E,W",
608 " ttf \"" + fontPath + "\" \"" + I18nManager.getText("cardinal.n") + "\" 0.3, 0",
609 " pigment { color rgb <1 1 1> }",
610 " translate <0, 0.2, 10.0>",
613 " ttf \"" + fontPath + "\" \"" + I18nManager.getText("cardinal.s") + "\" 0.3, 0",
614 " pigment { color rgb <1 1 1> }",
615 " translate <0, 0.2, -10.0>",
618 " ttf \"" + fontPath + "\" \"" + I18nManager.getText("cardinal.e") + "\" 0.3, 0",
619 " pigment { color rgb <1 1 1> }",
620 " translate <9.7, 0.2, 0>",
623 " ttf \"" + fontPath + "\" \"" + I18nManager.getText("cardinal.w") + "\" 0.3, 0",
624 " pigment { color rgb <1 1 1> }",
625 " translate <-10.3, 0.2, 0>",
627 // MAYBE: Light positions should relate to model size
629 "light_source { <-1, 9, -4> color rgb <0.5 0.5 0.5>}",
630 "light_source { <1, 6, -14> color rgb <0.6 0.6 0.6>}",
631 "light_source { <11, 12, 8> color rgb <0.3 0.3 0.3>}",
634 // write strings to file
635 int numLines = outputLines.length;
636 for (int i=0; i<numLines; i++)
638 inWriter.write(outputLines[i]);
639 inWriter.write(inLineSeparator);
644 * Make a description of the height_field object for the terrain, depending on terrain and image
645 * @param inTerrainFile terrain file, or null if none
646 * @param inImageFile image file, or null if none
647 * @param inLineSeparator line separator
648 * @return String for inserting into pov file
650 private static String makeTerrainString(File inTerrainFile, File inImageFile, String inLineSeparator)
652 if (inTerrainFile == null) {return "";}
653 StringBuilder sb = new StringBuilder();
654 sb.append("//Terrain").append(inLineSeparator)
655 .append("height_field {").append(inLineSeparator)
656 .append("\tpng \"").append(inTerrainFile.getName()).append("\" smooth").append(inLineSeparator)
657 .append("\tfinish {diffuse 0.7 phong 0.2}").append(inLineSeparator);
658 if (inImageFile != null) {
659 sb.append("\tpigment {image_map { png \"").append(inImageFile.getName()).append("\" } rotate x*90}").append(inLineSeparator);
662 sb.append("\tpigment {color rgb <0.55 0.7 0.55> }").append(inLineSeparator);
664 sb.append("\tscale 20.0").append(inLineSeparator)
665 .append("\ttranslate <-10.0, 0, -10.0>").append(inLineSeparator).append("}");
666 return sb.toString();
670 * Write out all the data points to the file in the balls-and-sticks style
671 * @param inWriter Writer to use for writing file
672 * @param inModel model object for getting data points
673 * @param inLineSeparator line separator to use
674 * @throws IOException on file writing error
676 private static void writeDataPointsBallsAndSticks(FileWriter inWriter, ThreeDModel inModel, String inLineSeparator)
679 inWriter.write("// Data points:");
680 inWriter.write(inLineSeparator);
681 int numPoints = inModel.getNumPoints();
682 for (int i=0; i<numPoints; i++)
684 // ball (different according to type)
685 if (inModel.getPointType(i) == ThreeDModel.POINT_TYPE_WAYPOINT)
688 inWriter.write("object { waypoint_sphere translate <" + inModel.getScaledHorizValue(i)
689 + "," + inModel.getScaledAltValue(i) + "," + inModel.getScaledVertValue(i) + "> }");
693 // normal track point ball
694 inWriter.write("object { track_sphere" + checkHeightCode(inModel.getPointHeightCode(i))
695 + " translate <" + inModel.getScaledHorizValue(i) + "," + inModel.getScaledAltValue(i)
696 + "," + inModel.getScaledVertValue(i) + "> }");
698 inWriter.write(inLineSeparator);
699 // vertical rod (if altitude positive)
700 if (inModel.getScaledAltValue(i) > 0.0)
702 inWriter.write("object { point_rod translate <" + inModel.getScaledHorizValue(i) + ",0,"
703 + inModel.getScaledVertValue(i) + "> scale <1," + inModel.getScaledAltValue(i) + ",1> }");
704 inWriter.write(inLineSeparator);
707 inWriter.write(inLineSeparator);
712 * Write out all the data points to the file in the tubes-and-walls style
713 * @param inWriter Writer to use for writing file
714 * @param inModel model object for getting data points
715 * @param inLineSeparator line separator to use
716 * @throws IOException on file writing error
718 private static void writeDataPointsTubesAndWalls(FileWriter inWriter, ThreeDModel inModel, String inLineSeparator)
721 inWriter.write("// Data points:");
722 inWriter.write(inLineSeparator);
723 int numPoints = inModel.getNumPoints();
724 // Loop over all points and write out waypoints as balls
725 for (int i=0; i<numPoints; i++)
727 if (inModel.getPointType(i) == ThreeDModel.POINT_TYPE_WAYPOINT)
730 inWriter.write("object { waypoint_sphere translate <" + inModel.getScaledHorizValue(i)
731 + "," + inModel.getScaledAltValue(i) + "," + inModel.getScaledVertValue(i) + "> }");
732 // vertical rod (if altitude positive)
733 if (inModel.getScaledAltValue(i) > 0.0)
735 inWriter.write(inLineSeparator);
736 inWriter.write("object { point_rod translate <" + inModel.getScaledHorizValue(i) + ",0,"
737 + inModel.getScaledVertValue(i) + "> scale <1," + inModel.getScaledAltValue(i) + ",1> }");
739 inWriter.write(inLineSeparator);
742 inWriter.write(inLineSeparator);
744 // Loop over all the track segments
745 ArrayList<ModelSegment> segmentList = getSegmentList(inModel);
746 Iterator<ModelSegment> segmentIterator = segmentList.iterator();
747 while (segmentIterator.hasNext())
749 ModelSegment segment = segmentIterator.next();
750 int segLength = segment.getNumTrackPoints();
752 // if the track segment is long enough, do a cubic spline sphere sweep
755 // single point in segment - just draw sphere
756 int index = segment.getStartIndex();
757 inWriter.write("object { track_sphere_t"
758 + " translate <" + inModel.getScaledHorizValue(index) + "," + inModel.getScaledAltValue(index)
759 + "," + inModel.getScaledVertValue(index) + "> }");
760 // maybe draw some kind of polygon too or rod?
764 writeSphereSweep(inWriter, inModel, segment, inLineSeparator);
767 // Write wall underneath segment
770 writePolygonWall(inWriter, inModel, segment, inLineSeparator);
777 * Write out a single sphere sweep using either cubic spline or linear spline
778 * @param inWriter Writer to use for writing file
779 * @param inModel model object for getting data points
780 * @param inSegment model segment to draw
781 * @param inLineSeparator line separator to use
782 * @throws IOException on file writing error
784 private static void writeSphereSweep(FileWriter inWriter, ThreeDModel inModel, ModelSegment inSegment, String inLineSeparator)
788 inWriter.write("// Sphere sweep:");
789 inWriter.write(inLineSeparator);
790 String splineType = inSegment.getNumTrackPoints() < 5?"linear_spline":"cubic_spline";
791 inWriter.write("sphere_sweep { "); inWriter.write(splineType);
792 inWriter.write(" " + inSegment.getNumTrackPoints() + ",");
793 inWriter.write(inLineSeparator);
794 // Loop over all points in this segment and write out sphere sweep
795 for (int i=inSegment.getStartIndex(); i<=inSegment.getEndIndex(); i++)
797 if (inModel.getPointType(i) != ThreeDModel.POINT_TYPE_WAYPOINT)
799 inWriter.write(" <" + inModel.getScaledHorizValue(i) + "," + inModel.getScaledAltValue(i)
800 + "," + inModel.getScaledVertValue(i) + ">, 0.25");
801 inWriter.write(inLineSeparator);
804 inWriter.write(" tolerance 0.1");
805 inWriter.write(inLineSeparator);
806 inWriter.write(" texture { pigment {color rgb <0.6 1.0 0.2>} finish {phong 1} }");
807 inWriter.write(inLineSeparator);
808 inWriter.write(" no_shadow");
809 inWriter.write(inLineSeparator);
811 inWriter.write(inLineSeparator);
816 * Write out a single polygon-based wall for the tubes-and-walls style
817 * @param inWriter Writer to use for writing file
818 * @param inModel model object for getting data points
819 * @param inSegment model segment to draw
820 * @param inLineSeparator line separator to use
821 * @throws IOException on file writing error
823 private static void writePolygonWall(FileWriter inWriter, ThreeDModel inModel, ModelSegment inSegment, String inLineSeparator)
827 inWriter.write(inLineSeparator);
828 inWriter.write("// wall between sweep and floor:");
829 inWriter.write(inLineSeparator);
830 // Loop over all points in this segment again and write out polygons
832 for (int i=inSegment.getStartIndex(); i<=inSegment.getEndIndex(); i++)
834 if (inModel.getPointType(i) != ThreeDModel.POINT_TYPE_WAYPOINT)
838 double xDiff = inModel.getScaledHorizValue(i) - inModel.getScaledHorizValue(prevIndex);
839 double yDiff = inModel.getScaledVertValue(i) - inModel.getScaledVertValue(prevIndex);
840 double dist = Math.sqrt(xDiff * xDiff + yDiff * yDiff);
843 inWriter.write("polygon {");
844 inWriter.write(" 5, <" + inModel.getScaledHorizValue(prevIndex) + ", 0.0, " + inModel.getScaledVertValue(prevIndex) + ">,");
845 inWriter.write(" <" + inModel.getScaledHorizValue(prevIndex) + ", " + inModel.getScaledAltValue(prevIndex) + ", "
846 + inModel.getScaledVertValue(prevIndex) + ">,");
847 inWriter.write(" <" + inModel.getScaledHorizValue(i) + ", " + inModel.getScaledAltValue(i) + ", "
848 + inModel.getScaledVertValue(i) + ">,");
849 inWriter.write(" <" + inModel.getScaledHorizValue(i) + ", 0.0, " + inModel.getScaledVertValue(i) + ">,");
850 inWriter.write(" <" + inModel.getScaledHorizValue(prevIndex) + ", 0.0, " + inModel.getScaledVertValue(prevIndex) + ">");
851 inWriter.write(" pigment { color wall_colour } no_shadow");
853 inWriter.write(inLineSeparator);
863 * @param inCode height code to check
864 * @return validated height code within range 0 to max
866 private static byte checkHeightCode(byte inCode)
868 final byte maxHeightCode = 5;
869 if (inCode < 0) return 0;
870 if (inCode > maxHeightCode) return maxHeightCode;
876 * Check the given coordinate
877 * @param inString String entered by user
878 * @return validated String value
880 private static String checkCoordinate(String inString)
885 value = Double.parseDouble(inString);
887 catch (Exception e) {} // ignore parse failures
892 * Go through the points making a list of the segment starts and the number of track points in each segment
893 * @param inModel model containing data
894 * @return list of ModelSegment objects
896 private static ArrayList<ModelSegment> getSegmentList(ThreeDModel inModel)
898 ArrayList<ModelSegment> segmentList = new ArrayList<ModelSegment>();
899 if (inModel != null && inModel.getNumPoints() > 0)
901 ModelSegment currSegment = null;
902 int numTrackPoints = 0;
903 for (int i=0; i<inModel.getNumPoints(); i++)
905 if (inModel.getPointType(i) != ThreeDModel.POINT_TYPE_WAYPOINT)
907 if (inModel.getPointType(i) == ThreeDModel.POINT_TYPE_SEGMENT_START || currSegment == null)
910 if (currSegment != null)
912 currSegment.setEndIndex(i-1);
913 currSegment.setNumTrackPoints(numTrackPoints);
914 segmentList.add(currSegment);
917 currSegment = new ModelSegment(i);
922 // Add last segment to list
923 if (currSegment != null && numTrackPoints > 0)
925 currSegment.setEndIndex(inModel.getNumPoints()-1);
926 currSegment.setNumTrackPoints(numTrackPoints);
927 segmentList.add(currSegment);