8743cca6af371eb1047bab9c5fee5d9264fcbd39
[anneal.git] / src / StlFileParser.java
1 import java.io.StreamTokenizer;
2 import java.io.Reader;
3 import java.io.IOException;
4
5 /**
6  * Title:        STL Loader
7  * Description:  STL files loader (Supports ASCII and binary files) for Java3D
8  *               Needs JDK 1.4 due to endian problems
9  * Copyright:    Copyright (c) 2001
10  * Company:      Universidad del Pais Vasco (UPV/EHU)
11  * @author:      Carlos Pedrinaci Godoy
12  * @version 1.0
13  *
14  * Contact : xenicp@yahoo.es
15  *
16  *   STL FILE PARSER:
17  *   Extends StreamTokenizer
18  *   For Ascii files
19  *   Each token returned is checked in StlFile.java
20  *   Format of an ASCII STL file:
21  *
22  *     solid /users/vis/dru/wedge.stl
23  *       facet normal -1 0 0
24  *         outer loop
25  *           vertex 0.005 1 0
26  *           vertex 0 0.543 0
27  *           vertex 0.453 1 1
28  *         endloop
29  *       endfacet
30  *            .
31  *            .
32  *            .
33  *     endsolid /users/vis/dru/wedge.stl
34  *
35  *  That Class is necessary because scientific numbers are not correctly readed by Tokenizer
36  *  we must then extend that class and define another getNumber
37  */
38
39 public class StlFileParser extends StreamTokenizer
40 {
41   /**
42    * Constructor: object creation and setup
43    *
44    * @param r The Reader instance
45    */
46   public StlFileParser(Reader r)
47   {
48     super(r);
49     setup();
50   }
51
52   /**
53    * Method that sets some params of the Tokenizer for reading the file correctly
54    */
55   public void setup()
56   {
57     resetSyntax();
58     eolIsSignificant(true);   // The End Of Line is important
59     lowerCaseMode(true);
60
61     // All printable ascii characters
62     wordChars('!', '~');
63
64     whitespaceChars(' ', ' ');
65     whitespaceChars('\n', '\n');
66     whitespaceChars('\r', '\r');
67     whitespaceChars('\t', '\t');
68   }// End setup
69
70   /**
71    * Gets a number from the stream.  Note that we don't recognize
72    * numbers in the tokenizer automatically because numbers might be in
73    * scientific notation, which isn't processed correctly by
74    * StreamTokenizer.  The number is returned in nval.
75    *
76    * @return boolean.
77    */
78   boolean getNumber()
79   {
80     int t;
81
82     try {
83         nextToken();
84         if (ttype != TT_WORD)
85           throw new IOException("Expected number on line " + lineno());
86         nval =  (Double.valueOf(sval)).doubleValue();
87     }
88     catch (IOException e) {
89       System.err.println(e.getMessage());
90       return false;
91     }
92     catch (NumberFormatException e) {
93       System.err.println(e.getMessage());
94       return false;
95     }
96     return true;
97   } // end of getNumber
98
99 }// End of StlFileParser