STLLoader.js 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  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. var expect, face_size, n_faces, reader;
  64. reader = new THREE.STLLoader.BinaryReader(data);
  65. reader.seek(80);
  66. face_size = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  67. n_faces = reader.readUInt32();
  68. expect = 80 + (32 / 8) + (n_faces * face_size);
  69. return expect === reader.getSize();
  70. };
  71. if (isBinary(data)) {
  72. return this.parseBinary(data);
  73. } else {
  74. return this.parseASCII(data);
  75. }
  76. };
  77. THREE.STLLoader.prototype.parseBinary = function (data) {
  78. var face, geometry, n_faces, reader, length, normal, i;
  79. reader = new THREE.STLLoader.BinaryReader(data);
  80. reader.seek(80);
  81. n_faces = reader.readUInt32();
  82. geometry = new THREE.Geometry();
  83. for (face = 0; face < n_faces; face++) {
  84. normal = new THREE.Vector3(reader.readFloat(),reader.readFloat(),reader.readFloat());
  85. for (i = 1; i <= 3; i++) {
  86. geometry.vertices.push(new THREE.Vector3(reader.readFloat(),reader.readFloat(),reader.readFloat()));
  87. }
  88. reader.readUInt16(); // attr doesn't get used yet.
  89. length = geometry.vertices.length;
  90. geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
  91. }
  92. geometry.computeCentroids();
  93. geometry.computeBoundingBox();
  94. geometry.computeBoundingSphere();
  95. return geometry;
  96. };
  97. THREE.STLLoader.prototype.parseASCII = function (data) {
  98. var geometry, length, normal, patternFace, patternNormal, patternVertex, result, text;
  99. geometry = new THREE.Geometry();
  100. patternFace = /facet([\s\S]*?)endfacet/g;
  101. while (((result = patternFace.exec(data)) != null)) {
  102. text = result[0];
  103. 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;
  104. while (((result = patternNormal.exec(text)) != null)) {
  105. normal = new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5]));
  106. }
  107. 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;
  108. while (((result = patternVertex.exec(text)) != null)) {
  109. geometry.vertices.push(new THREE.Vector3(parseFloat(result[1]), parseFloat(result[3]), parseFloat(result[5])));
  110. }
  111. length = geometry.vertices.length;
  112. geometry.faces.push(new THREE.Face3(length - 3, length - 2, length - 1, normal));
  113. }
  114. geometry.computeCentroids();
  115. geometry.computeBoundingBox();
  116. geometry.computeBoundingSphere();
  117. return geometry;
  118. };
  119. THREE.STLLoader.BinaryReader = function (data) {
  120. this._buffer = data;
  121. this._pos = 0;
  122. };
  123. THREE.STLLoader.BinaryReader.prototype = {
  124. /* Public */
  125. readInt8: function (){ return this._decodeInt(8, true); },
  126. readUInt8: function (){ return this._decodeInt(8, false); },
  127. readInt16: function (){ return this._decodeInt(16, true); },
  128. readUInt16: function (){ return this._decodeInt(16, false); },
  129. readInt32: function (){ return this._decodeInt(32, true); },
  130. readUInt32: function (){ return this._decodeInt(32, false); },
  131. readFloat: function (){ return this._decodeFloat(23, 8); },
  132. readDouble: function (){ return this._decodeFloat(52, 11); },
  133. readChar: function () { return this.readString(1); },
  134. readString: function (length) {
  135. this._checkSize(length * 8);
  136. var result = this._buffer.substr(this._pos, length);
  137. this._pos += length;
  138. return result;
  139. },
  140. seek: function (pos) {
  141. this._pos = pos;
  142. this._checkSize(0);
  143. },
  144. getPosition: function () {
  145. return this._pos;
  146. },
  147. getSize: function () {
  148. return this._buffer.length;
  149. },
  150. /* Private */
  151. _decodeFloat: function(precisionBits, exponentBits){
  152. var length = precisionBits + exponentBits + 1;
  153. var size = length >> 3;
  154. this._checkSize(length);
  155. var bias = Math.pow(2, exponentBits - 1) - 1;
  156. var signal = this._readBits(precisionBits + exponentBits, 1, size);
  157. var exponent = this._readBits(precisionBits, exponentBits, size);
  158. var significand = 0;
  159. var divisor = 2;
  160. // var curByte = length + (-precisionBits >> 3) - 1;
  161. var curByte = 0;
  162. do {
  163. var byteValue = this._readByte(++curByte, size);
  164. var startBit = precisionBits % 8 || 8;
  165. var mask = 1 << startBit;
  166. while (mask >>= 1) {
  167. if (byteValue & mask) {
  168. significand += 1 / divisor;
  169. }
  170. divisor *= 2;
  171. }
  172. } while (precisionBits -= startBit);
  173. this._pos += size;
  174. return exponent == (bias << 1) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity
  175. : (1 + signal * -2) * (exponent || significand ? !exponent ? Math.pow(2, -bias + 1) * significand
  176. : Math.pow(2, exponent - bias) * (1 + significand) : 0);
  177. },
  178. _decodeInt: function(bits, signed){
  179. var x = this._readBits(0, bits, bits / 8), max = Math.pow(2, bits);
  180. var result = signed && x >= max / 2 ? x - max : x;
  181. this._pos += bits / 8;
  182. return result;
  183. },
  184. //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni)
  185. _shl: function (a, b){
  186. for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1);
  187. return a;
  188. },
  189. _readByte: function (i, size) {
  190. return this._buffer.charCodeAt(this._pos + size - i - 1) & 0xff;
  191. },
  192. _readBits: function (start, length, size) {
  193. var offsetLeft = (start + length) % 8;
  194. var offsetRight = start % 8;
  195. var curByte = size - (start >> 3) - 1;
  196. var lastByte = size + (-(start + length) >> 3);
  197. var diff = curByte - lastByte;
  198. var sum = (this._readByte(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1);
  199. if (diff && offsetLeft) {
  200. sum += (this._readByte(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight;
  201. }
  202. while (diff) {
  203. sum += this._shl(this._readByte(lastByte++, size), (diff-- << 3) - offsetRight);
  204. }
  205. return sum;
  206. },
  207. _checkSize: function (neededBits) {
  208. if (!(this._pos + Math.ceil(neededBits / 8) < this._buffer.length)) {
  209. throw new Error("Index out of bound");
  210. }
  211. }
  212. };