2
0

STLLoader.js 8.3 KB

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