STLLoader.js 9.9 KB

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