STLLoader.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. /**
  2. * Description: A THREE loader for STL ASCII files, as created by Solidworks and other CAD programs.
  3. *
  4. * Supports both binary and ASCII encoded files, with automatic detection of type.
  5. *
  6. * The loader returns a non-indexed buffer geometry.
  7. *
  8. * Limitations:
  9. * Binary decoding supports "Magics" color format (http://en.wikipedia.org/wiki/STL_(file_format)#Color_in_binary_STL).
  10. * There is perhaps some question as to how valid it is to always assume little-endian-ness.
  11. * ASCII decoding assumes file is UTF-8.
  12. *
  13. * Usage:
  14. * var loader = new THREE.STLLoader();
  15. * loader.load( './models/stl/slotted_disk.stl', function ( geometry ) {
  16. * scene.add( new THREE.Mesh( geometry ) );
  17. * });
  18. *
  19. * For binary STLs geometry might contain colors for vertices. To use it:
  20. * // use the same code to load STL as above
  21. * if (geometry.hasColors) {
  22. * material = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: true });
  23. * } else { .... }
  24. * var mesh = new THREE.Mesh( geometry, material );
  25. *
  26. * For ASCII STLs containing multiple solids, each solid is assigned to a different group.
  27. * Groups can be used to assign a different color by defining an array of materials with the same length of
  28. * geometry.groups and passing it to the Mesh constructor:
  29. *
  30. * var mesh = new THREE.Mesh( geometry, material );
  31. *
  32. * For example:
  33. *
  34. * var materials = [];
  35. * var nGeometryGroups = geometry.groups.length;
  36. *
  37. * var colorMap = ...; // Some logic to index colors.
  38. *
  39. * for (var i = 0; i < nGeometryGroups; i++) {
  40. *
  41. * var material = new THREE.MeshPhongMaterial({
  42. * color: colorMap[i],
  43. * wireframe: false
  44. * });
  45. *
  46. * }
  47. *
  48. * materials.push(material);
  49. * var mesh = new THREE.Mesh(geometry, materials);
  50. */
  51. THREE.STLLoader = function ( manager ) {
  52. THREE.Loader.call( this, manager );
  53. };
  54. THREE.STLLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), {
  55. constructor: THREE.STLLoader,
  56. load: function ( url, onLoad, onProgress, onError ) {
  57. var scope = this;
  58. var loader = new THREE.FileLoader( this.manager );
  59. loader.setPath( this.path );
  60. loader.setResponseType( 'arraybuffer' );
  61. loader.setRequestHeader( this.requestHeader );
  62. loader.setWithCredentials( this.withCredentials );
  63. loader.load( url, function ( text ) {
  64. try {
  65. onLoad( scope.parse( text ) );
  66. } catch ( e ) {
  67. if ( onError ) {
  68. onError( e );
  69. } else {
  70. console.error( e );
  71. }
  72. scope.manager.itemError( url );
  73. }
  74. }, onProgress, onError );
  75. },
  76. parse: function ( data ) {
  77. function isBinary( data ) {
  78. var expect, face_size, n_faces, reader;
  79. reader = new DataView( data );
  80. face_size = ( 32 / 8 * 3 ) + ( ( 32 / 8 * 3 ) * 3 ) + ( 16 / 8 );
  81. n_faces = reader.getUint32( 80, true );
  82. expect = 80 + ( 32 / 8 ) + ( n_faces * face_size );
  83. if ( expect === reader.byteLength ) {
  84. return true;
  85. }
  86. // An ASCII STL data must begin with 'solid ' as the first six bytes.
  87. // However, ASCII STLs lacking the SPACE after the 'd' are known to be
  88. // plentiful. So, check the first 5 bytes for 'solid'.
  89. // Several encodings, such as UTF-8, precede the text with up to 5 bytes:
  90. // https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding
  91. // Search for "solid" to start anywhere after those prefixes.
  92. // US-ASCII ordinal values for 's', 'o', 'l', 'i', 'd'
  93. var solid = [ 115, 111, 108, 105, 100 ];
  94. for ( var off = 0; off < 5; off ++ ) {
  95. // If "solid" text is matched to the current offset, declare it to be an ASCII STL.
  96. if ( matchDataViewAt( solid, reader, off ) ) return false;
  97. }
  98. // Couldn't find "solid" text at the beginning; it is binary STL.
  99. return true;
  100. }
  101. function matchDataViewAt( query, reader, offset ) {
  102. // Check if each byte in query matches the corresponding byte from the current offset
  103. for ( var i = 0, il = query.length; i < il; i ++ ) {
  104. if ( query[ i ] !== reader.getUint8( offset + i, false ) ) return false;
  105. }
  106. return true;
  107. }
  108. function parseBinary( data ) {
  109. var reader = new DataView( data );
  110. var faces = reader.getUint32( 80, true );
  111. var r, g, b, hasColors = false, colors;
  112. var defaultR, defaultG, defaultB, alpha;
  113. // process STL header
  114. // check for default color in header ("COLOR=rgba" sequence).
  115. for ( var index = 0; index < 80 - 10; index ++ ) {
  116. if ( ( reader.getUint32( index, false ) == 0x434F4C4F /*COLO*/ ) &&
  117. ( reader.getUint8( index + 4 ) == 0x52 /*'R'*/ ) &&
  118. ( reader.getUint8( index + 5 ) == 0x3D /*'='*/ ) ) {
  119. hasColors = true;
  120. colors = new Float32Array( faces * 3 * 3 );
  121. defaultR = reader.getUint8( index + 6 ) / 255;
  122. defaultG = reader.getUint8( index + 7 ) / 255;
  123. defaultB = reader.getUint8( index + 8 ) / 255;
  124. alpha = reader.getUint8( index + 9 ) / 255;
  125. }
  126. }
  127. var dataOffset = 84;
  128. var faceLength = 12 * 4 + 2;
  129. var geometry = new THREE.BufferGeometry();
  130. var vertices = new Float32Array( faces * 3 * 3 );
  131. var normals = new Float32Array( faces * 3 * 3 );
  132. for ( var face = 0; face < faces; face ++ ) {
  133. var start = dataOffset + face * faceLength;
  134. var normalX = reader.getFloat32( start, true );
  135. var normalY = reader.getFloat32( start + 4, true );
  136. var normalZ = reader.getFloat32( start + 8, true );
  137. if ( hasColors ) {
  138. var packedColor = reader.getUint16( start + 48, true );
  139. if ( ( packedColor & 0x8000 ) === 0 ) {
  140. // facet has its own unique color
  141. r = ( packedColor & 0x1F ) / 31;
  142. g = ( ( packedColor >> 5 ) & 0x1F ) / 31;
  143. b = ( ( packedColor >> 10 ) & 0x1F ) / 31;
  144. } else {
  145. r = defaultR;
  146. g = defaultG;
  147. b = defaultB;
  148. }
  149. }
  150. for ( var i = 1; i <= 3; i ++ ) {
  151. var vertexstart = start + i * 12;
  152. var componentIdx = ( face * 3 * 3 ) + ( ( i - 1 ) * 3 );
  153. vertices[ componentIdx ] = reader.getFloat32( vertexstart, true );
  154. vertices[ componentIdx + 1 ] = reader.getFloat32( vertexstart + 4, true );
  155. vertices[ componentIdx + 2 ] = reader.getFloat32( vertexstart + 8, true );
  156. normals[ componentIdx ] = normalX;
  157. normals[ componentIdx + 1 ] = normalY;
  158. normals[ componentIdx + 2 ] = normalZ;
  159. if ( hasColors ) {
  160. colors[ componentIdx ] = r;
  161. colors[ componentIdx + 1 ] = g;
  162. colors[ componentIdx + 2 ] = b;
  163. }
  164. }
  165. }
  166. geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
  167. geometry.setAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
  168. if ( hasColors ) {
  169. geometry.setAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
  170. geometry.hasColors = true;
  171. geometry.alpha = alpha;
  172. }
  173. return geometry;
  174. }
  175. function parseASCII( data ) {
  176. var geometry = new THREE.BufferGeometry();
  177. var patternSolid = /solid([\s\S]*?)endsolid/g;
  178. var patternFace = /facet([\s\S]*?)endfacet/g;
  179. var faceCounter = 0;
  180. var patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source;
  181. var patternVertex = new RegExp( 'vertex' + patternFloat + patternFloat + patternFloat, 'g' );
  182. var patternNormal = new RegExp( 'normal' + patternFloat + patternFloat + patternFloat, 'g' );
  183. var vertices = [];
  184. var normals = [];
  185. var normal = new THREE.Vector3();
  186. var result;
  187. var groupCount = 0;
  188. var startVertex = 0;
  189. var endVertex = 0;
  190. while ( ( result = patternSolid.exec( data ) ) !== null ) {
  191. startVertex = endVertex;
  192. var solid = result[ 0 ];
  193. while ( ( result = patternFace.exec( solid ) ) !== null ) {
  194. var vertexCountPerFace = 0;
  195. var normalCountPerFace = 0;
  196. var text = result[ 0 ];
  197. while ( ( result = patternNormal.exec( text ) ) !== null ) {
  198. normal.x = parseFloat( result[ 1 ] );
  199. normal.y = parseFloat( result[ 2 ] );
  200. normal.z = parseFloat( result[ 3 ] );
  201. normalCountPerFace ++;
  202. }
  203. while ( ( result = patternVertex.exec( text ) ) !== null ) {
  204. vertices.push( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) );
  205. normals.push( normal.x, normal.y, normal.z );
  206. vertexCountPerFace ++;
  207. endVertex ++;
  208. }
  209. // every face have to own ONE valid normal
  210. if ( normalCountPerFace !== 1 ) {
  211. console.error( 'THREE.STLLoader: Something isn\'t right with the normal of face number ' + faceCounter );
  212. }
  213. // each face have to own THREE valid vertices
  214. if ( vertexCountPerFace !== 3 ) {
  215. console.error( 'THREE.STLLoader: Something isn\'t right with the vertices of face number ' + faceCounter );
  216. }
  217. faceCounter ++;
  218. }
  219. var start = startVertex;
  220. var count = endVertex - startVertex;
  221. geometry.addGroup( start, count, groupCount );
  222. groupCount ++;
  223. }
  224. geometry.setAttribute( 'position', new THREE.Float32BufferAttribute( vertices, 3 ) );
  225. geometry.setAttribute( 'normal', new THREE.Float32BufferAttribute( normals, 3 ) );
  226. return geometry;
  227. }
  228. function ensureString( buffer ) {
  229. if ( typeof buffer !== 'string' ) {
  230. return THREE.LoaderUtils.decodeText( new Uint8Array( buffer ) );
  231. }
  232. return buffer;
  233. }
  234. function ensureBinary( buffer ) {
  235. if ( typeof buffer === 'string' ) {
  236. var array_buffer = new Uint8Array( buffer.length );
  237. for ( var i = 0; i < buffer.length; i ++ ) {
  238. array_buffer[ i ] = buffer.charCodeAt( i ) & 0xff; // implicitly assumes little-endian
  239. }
  240. return array_buffer.buffer || array_buffer;
  241. } else {
  242. return buffer;
  243. }
  244. }
  245. // start
  246. var binData = ensureBinary( data );
  247. return isBinary( binData ) ? parseBinary( binData ) : parseASCII( ensureString( data ) );
  248. }
  249. } );