STLLoader.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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) {
  33. var scope = this;
  34. console.log("Attempting to load URL: [" + url + "]");
  35. var xhr = new XMLHttpRequest();
  36. function onloaded( event ) {
  37. if ( event.target.status === 200 || event.target.status === 0 ) {
  38. var data = event.target.responseText;
  39. return scope.dispatchEvent({
  40. type: 'load',
  41. content: scope.parse(data)
  42. });
  43. } else {
  44. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']',
  45. response: event.target.responseText } );
  46. }
  47. }
  48. xhr.addEventListener( 'load', onloaded, false );
  49. xhr.addEventListener( 'progress', function ( event ) {
  50. scope.dispatchEvent( { type: 'progress', loaded: event.loaded, total: event.total } );
  51. }, false );
  52. xhr.addEventListener( 'error', function () {
  53. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  54. }, false );
  55. xhr.overrideMimeType('text/plain; charset=x-user-defined');
  56. xhr.open( 'GET', url, true );
  57. xhr.send( null );
  58. };
  59. THREE.STLLoader.prototype.parse = function (data) {
  60. var isBinary,
  61. _this = this;
  62. isBinary = function (data) {
  63. // TODO: Is this safer then the previous check which is checking
  64. // if solid is at the start of ASCII file???
  65. var expect, face_size, n_faces, reader;
  66. reader = new THREE.STLLoader.BinaryReader(data);
  67. reader.seek(80);
  68. face_size = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  69. n_faces = reader.readUInt32();
  70. expect = 80 + (32 / 8) + (n_faces * face_size);
  71. return expect === reader.getSize();
  72. };
  73. if (isBinary(data)) {
  74. return this.parseBinary(data);
  75. } else {
  76. return this.parseASCII(data);
  77. }
  78. };
  79. THREE.STLLoader.prototype.parseBinary = function (data) {
  80. var face, geometry, n_faces, readFloat3, reader, _fn, _i;
  81. reader = new THREE.STLLoader.BinaryReader(data);
  82. readFloat3 = function () {
  83. return [reader.readFloat(), reader.readFloat(), reader.readFloat()];
  84. };
  85. reader.seek(80);
  86. n_faces = reader.readUInt32();
  87. geometry = new THREE.Geometry();
  88. _fn = function (face) {
  89. var length, normal, v1, _j;
  90. v1 = readFloat3();
  91. normal = new THREE.Vector3(v1[0],v1[1],v1[2]);
  92. for (_j = 1; _j <= 3; _j++) {
  93. v1 = readFloat3();
  94. geometry.vertices.push(new THREE.Vector3(v1[0],v1[1],v1[2]));
  95. }
  96. reader.readUInt16();
  97. length = geometry.vertices.length;
  98. return geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
  99. };
  100. for (face = _i = 0; 0 <= n_faces ? _i < n_faces : _i > n_faces; face = 0 <= n_faces ? ++_i : --_i) {
  101. _fn(face);
  102. }
  103. geometry.computeCentroids();
  104. geometry.computeBoundingBox();
  105. geometry.computeBoundingSphere();
  106. return geometry;
  107. };
  108. THREE.STLLoader.prototype.parseASCII = function (data) {
  109. var geometry, length, normal, patternFace, patternNormal, patternVertex, result, text;
  110. geometry = new THREE.Geometry();
  111. patternFace = /facet([\s\S]*?)endfacet/g;
  112. while (((result = patternFace.exec(data)) != null)) {
  113. text = result[0];
  114. 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;
  115. while (((result = patternNormal.exec(text)) != null)) {
  116. normal = new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5]));
  117. }
  118. 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;
  119. while (((result = patternVertex.exec(text)) != null)) {
  120. geometry.vertices.push(new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])));
  121. }
  122. length = geometry.vertices.length;
  123. geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
  124. }
  125. geometry.computeCentroids();
  126. geometry.computeBoundingBox();
  127. geometry.computeBoundingSphere();
  128. return geometry;
  129. };
  130. // BinaryReader
  131. // Refactored by Vjeux <[email protected]>
  132. // http://blog.vjeux.com/2010/javascript/javascript-binary-reader.html
  133. // Original
  134. //+ Jonas Raoni Soares Silva
  135. //@ http://jsfromhell.com/classes/binary-parser [rev. #1]
  136. THREE.STLLoader.BinaryReader = function (data) {
  137. this._buffer = data;
  138. this._pos = 0;
  139. };
  140. THREE.STLLoader.BinaryReader.prototype = {
  141. /* Public */
  142. readInt8: function (){ return this._decodeInt(8, true); },
  143. readUInt8: function (){ return this._decodeInt(8, false); },
  144. readInt16: function (){ return this._decodeInt(16, true); },
  145. readUInt16: function (){ return this._decodeInt(16, false); },
  146. readInt32: function (){ return this._decodeInt(32, true); },
  147. readUInt32: function (){ return this._decodeInt(32, false); },
  148. readFloat: function (){ return this._decodeFloat(23, 8); },
  149. readDouble: function (){ return this._decodeFloat(52, 11); },
  150. readChar: function () { return this.readString(1); },
  151. readString: function (length) {
  152. this._checkSize(length * 8);
  153. var result = this._buffer.substr(this._pos, length);
  154. this._pos += length;
  155. return result;
  156. },
  157. seek: function (pos) {
  158. this._pos = pos;
  159. this._checkSize(0);
  160. },
  161. getPosition: function () {
  162. return this._pos;
  163. },
  164. getSize: function () {
  165. return this._buffer.length;
  166. },
  167. /* Private */
  168. _decodeFloat: function(precisionBits, exponentBits){
  169. var length = precisionBits + exponentBits + 1;
  170. var size = length >> 3;
  171. this._checkSize(length);
  172. var bias = Math.pow(2, exponentBits - 1) - 1;
  173. var signal = this._readBits(precisionBits + exponentBits, 1, size);
  174. var exponent = this._readBits(precisionBits, exponentBits, size);
  175. var significand = 0;
  176. var divisor = 2;
  177. // var curByte = length + (-precisionBits >> 3) - 1;
  178. var curByte = 0;
  179. do {
  180. var byteValue = this._readByte(++curByte, size);
  181. var startBit = precisionBits % 8 || 8;
  182. var mask = 1 << startBit;
  183. while (mask >>= 1) {
  184. if (byteValue & mask) {
  185. significand += 1 / divisor;
  186. }
  187. divisor *= 2;
  188. }
  189. } while (precisionBits -= startBit);
  190. this._pos += size;
  191. return exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity
  192. : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand
  193. : Math.pow(2, exponent - bias) * (1 + significand) : 0);
  194. },
  195. _decodeInt: function(bits, signed){
  196. var x = this._readBits(0, bits, bits / 8), max = Math.pow(2, bits);
  197. var result = signed && x >= max / 2 ? x - max : x;
  198. this._pos += bits / 8;
  199. return result;
  200. },
  201. //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni)
  202. _shl: function (a, b){
  203. for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1);
  204. return a;
  205. },
  206. _readByte: function (i, size) {
  207. return this._buffer.charCodeAt(this._pos + size - i - 1) & 0xff;
  208. },
  209. _readBits: function (start, length, size) {
  210. var offsetLeft = (start + length) % 8;
  211. var offsetRight = start % 8;
  212. var curByte = size - (start >> 3) - 1;
  213. var lastByte = size + (-(start + length) >> 3);
  214. var diff = curByte - lastByte;
  215. var sum = (this._readByte(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1);
  216. if (diff && offsetLeft) {
  217. sum += (this._readByte(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight;
  218. }
  219. while (diff) {
  220. sum += this._shl(this._readByte(lastByte++, size), (diff-- << 3) - offsetRight);
  221. }
  222. return sum;
  223. },
  224. _checkSize: function (neededBits) {
  225. if (!(this._pos + Math.ceil(neededBits / 8) < this._buffer.length)) {
  226. throw new Error("Index out of bound");
  227. }
  228. }
  229. };