STLLoader.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /**
  2. * @author aleeper / http://adamleeper.com/
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author gero3 / https://github.com/gero3
  5. *
  6. * Description: A THREE loader for STL ASCII files, as created by Solidworks and other CAD programs.
  7. *
  8. * Supports both binary and ASCII encoded files, with automatic detection of type.
  9. *
  10. * Limitations: Binary decoding ignores header. There doesn't seem to be much of a use for it.
  11. * There is perhaps some question as to how valid it is to always assume little-endian-ness.
  12. * ASCII decoding assumes file is UTF-8. Seems to work for the examples...
  13. *
  14. * Usage:
  15. * var loader = new THREE.STLLoader();
  16. * loader.addEventListener( 'load', function ( event ) {
  17. *
  18. * var geometry = event.content;
  19. * scene.add( new THREE.Mesh( geometry ) );
  20. *
  21. * } );
  22. * loader.load( './models/stl/slotted_disk.stl' );
  23. */
  24. THREE.STLLoader = function () {};
  25. THREE.STLLoader.prototype = {
  26. constructor: THREE.STLLoader,
  27. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  28. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  29. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  30. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent
  31. };
  32. THREE.STLLoader.prototype.load = function (url, callback) {
  33. var scope = this;
  34. var xhr = new XMLHttpRequest();
  35. function onloaded( event ) {
  36. if ( event.target.status === 200 || event.target.status === 0 ) {
  37. var geometry = scope.parse( event.target.responseText );
  38. scope.dispatchEvent( { type: 'load', content: geometry } );
  39. if ( callback ) callback( geometry );
  40. } else {
  41. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']',
  42. response: event.target.responseText } );
  43. }
  44. }
  45. xhr.addEventListener( 'load', onloaded, false );
  46. xhr.addEventListener( 'progress', function ( event ) {
  47. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  48. }, false );
  49. xhr.addEventListener( 'error', function () {
  50. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  51. }, false );
  52. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  53. xhr.open( 'GET', url, true );
  54. xhr.send( null );
  55. };
  56. THREE.STLLoader.prototype.parse = function (data) {
  57. var isBinary = function (data) {
  58. var expect, face_size, n_faces, reader;
  59. reader = new THREE.STLLoader.BinaryReader(data);
  60. reader.seek(80);
  61. face_size = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  62. n_faces = reader.readUInt32();
  63. expect = 80 + (32 / 8) + (n_faces * face_size);
  64. return expect === reader.getSize();
  65. };
  66. if (isBinary(data)) {
  67. return this.parseBinary(data);
  68. } else {
  69. return this.parseASCII(data);
  70. }
  71. };
  72. THREE.STLLoader.prototype.parseBinary = function (data) {
  73. var face, geometry, n_faces, reader, length, normal, i;
  74. reader = new THREE.STLLoader.BinaryReader(data);
  75. reader.seek(80);
  76. n_faces = reader.readUInt32();
  77. geometry = new THREE.Geometry();
  78. for (face = 0; face < n_faces; face++) {
  79. normal = new THREE.Vector3(reader.readFloat(),reader.readFloat(),reader.readFloat());
  80. for (i = 1; i <= 3; i++) {
  81. geometry.vertices.push(new THREE.Vector3(reader.readFloat(),reader.readFloat(),reader.readFloat()));
  82. }
  83. reader.readUInt16(); // attr doesn't get used yet.
  84. length = geometry.vertices.length;
  85. geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
  86. }
  87. geometry.computeCentroids();
  88. geometry.computeBoundingBox();
  89. geometry.computeBoundingSphere();
  90. return geometry;
  91. };
  92. THREE.STLLoader.prototype.parseASCII = function (data) {
  93. var geometry, length, normal, patternFace, patternNormal, patternVertex, result, text;
  94. geometry = new THREE.Geometry();
  95. patternFace = /facet([\s\S]*?)endfacet/g;
  96. while (((result = patternFace.exec(data)) != null)) {
  97. text = result[0];
  98. patternNormal = /normal[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  99. while (((result = patternNormal.exec(text)) != null)) {
  100. normal = new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5]));
  101. }
  102. patternVertex = /vertex[\s]+([\-+]?[0-9]+\.?[0-9]*([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+[\s]+([\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?)+/g;
  103. while (((result = patternVertex.exec(text)) != null)) {
  104. geometry.vertices.push(new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])));
  105. }
  106. length = geometry.vertices.length;
  107. geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
  108. }
  109. geometry.computeCentroids();
  110. geometry.computeBoundingBox();
  111. geometry.computeBoundingSphere();
  112. return geometry;
  113. };
  114. THREE.STLLoader.BinaryReader = function (data) {
  115. this._buffer = data;
  116. this._pos = 0;
  117. };
  118. THREE.STLLoader.BinaryReader.prototype = {
  119. /* Public */
  120. readInt8: function (){ return this._decodeInt(8, true); },
  121. readUInt8: function (){ return this._decodeInt(8, false); },
  122. readInt16: function (){ return this._decodeInt(16, true); },
  123. readUInt16: function (){ return this._decodeInt(16, false); },
  124. readInt32: function (){ return this._decodeInt(32, true); },
  125. readUInt32: function (){ return this._decodeInt(32, false); },
  126. readFloat: function (){ return this._decodeFloat(23, 8); },
  127. readDouble: function (){ return this._decodeFloat(52, 11); },
  128. readChar: function () { return this.readString(1); },
  129. readString: function (length) {
  130. this._checkSize(length * 8);
  131. var result = this._buffer.substr(this._pos, length);
  132. this._pos += length;
  133. return result;
  134. },
  135. seek: function (pos) {
  136. this._pos = pos;
  137. this._checkSize(0);
  138. },
  139. getPosition: function () {
  140. return this._pos;
  141. },
  142. getSize: function () {
  143. return this._buffer.length;
  144. },
  145. /* Private */
  146. _decodeFloat: function(precisionBits, exponentBits){
  147. var length = precisionBits + exponentBits + 1;
  148. var size = length >> 3;
  149. this._checkSize(length);
  150. var bias = Math.pow(2, exponentBits - 1) - 1;
  151. var signal = this._readBits(precisionBits + exponentBits, 1, size);
  152. var exponent = this._readBits(precisionBits, exponentBits, size);
  153. var significand = 0;
  154. var divisor = 2;
  155. // var curByte = length + (-precisionBits >> 3) - 1;
  156. var curByte = 0;
  157. do {
  158. var byteValue = this._readByte(++curByte, size);
  159. var startBit = precisionBits % 8 || 8;
  160. var mask = 1 << startBit;
  161. while (mask >>= 1) {
  162. if (byteValue & mask) {
  163. significand += 1 / divisor;
  164. }
  165. divisor *= 2;
  166. }
  167. } while (precisionBits -= startBit);
  168. this._pos += size;
  169. return exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity
  170. : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand
  171. : Math.pow(2, exponent - bias) * (1 + significand) : 0);
  172. },
  173. _decodeInt: function(bits, signed){
  174. var x = this._readBits(0, bits, bits / 8), max = Math.pow(2, bits);
  175. var result = signed && x >= max / 2 ? x - max : x;
  176. this._pos += bits / 8;
  177. return result;
  178. },
  179. //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni)
  180. _shl: function (a, b){
  181. for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1);
  182. return a;
  183. },
  184. _readByte: function (i, size) {
  185. return this._buffer.charCodeAt(this._pos + size - i - 1) & 0xff;
  186. },
  187. _readBits: function (start, length, size) {
  188. var offsetLeft = (start + length) % 8;
  189. var offsetRight = start % 8;
  190. var curByte = size - (start >> 3) - 1;
  191. var lastByte = size + (-(start + length) >> 3);
  192. var diff = curByte - lastByte;
  193. var sum = (this._readByte(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1);
  194. if (diff && offsetLeft) {
  195. sum += (this._readByte(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight;
  196. }
  197. while (diff) {
  198. sum += this._shl(this._readByte(lastByte++, size), (diff-- << 3) - offsetRight);
  199. }
  200. return sum;
  201. },
  202. _checkSize: function (neededBits) {
  203. if (!(this._pos + Math.ceil(neededBits / 8) < this._buffer.length)) {
  204. throw new Error("Index out of bound");
  205. }
  206. }
  207. };