1
0

STLLoader.js 9.8 KB

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