STLBinaryExporter.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * @author kovacsv / http://kovacsv.hu/
  3. * @author mrdoob / http://mrdoob.com/
  4. * @author mudcube / http://mudcu.be/
  5. */
  6. THREE.STLBinaryExporter = function () {};
  7. THREE.STLBinaryExporter.prototype = {
  8. constructor: THREE.STLBinaryExporter,
  9. parse: ( function () {
  10. var vector = new THREE.Vector3();
  11. var normalMatrixWorld = new THREE.Matrix3();
  12. return function parse( scene ) {
  13. // We collect objects first, as we may need to convert from BufferGeometry to Geometry
  14. var objects = [];
  15. var triangles = 0;
  16. scene.traverse( function ( object ) {
  17. if ( ! ( object instanceof THREE.Mesh ) ) return;
  18. var geometry = object.geometry;
  19. if ( geometry instanceof THREE.BufferGeometry ) {
  20. geometry = new THREE.Geometry().fromBufferGeometry( geometry );
  21. }
  22. if ( ! ( geometry instanceof THREE.Geometry ) ) return;
  23. triangles += geometry.faces.length;
  24. objects.push( {
  25. geometry: geometry,
  26. matrix: object.matrixWorld
  27. } );
  28. } );
  29. var offset = 80; // skip header
  30. var bufferLength = triangles * 2 + triangles * 3 * 4 * 4 + 80 + 4;
  31. var arrayBuffer = new ArrayBuffer( bufferLength );
  32. var output = new DataView( arrayBuffer );
  33. output.setUint32( offset, triangles, true ); offset += 4;
  34. // Traversing our collected objects
  35. objects.forEach( function ( object ) {
  36. var vertices = object.geometry.vertices;
  37. var faces = object.geometry.faces;
  38. normalMatrixWorld.getNormalMatrix( object.matrix );
  39. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  40. var face = faces[ i ];
  41. vector.copy( face.normal ).applyMatrix3( normalMatrixWorld ).normalize();
  42. output.setFloat32( offset, vector.x, true ); offset += 4; // normal
  43. output.setFloat32( offset, vector.y, true ); offset += 4;
  44. output.setFloat32( offset, vector.z, true ); offset += 4;
  45. var indices = [ face.a, face.b, face.c ];
  46. for ( var j = 0; j < 3; j ++ ) {
  47. vector.copy( vertices[ indices[ j ] ] ).applyMatrix4( object.matrix );
  48. output.setFloat32( offset, vector.x, true ); offset += 4; // vertices
  49. output.setFloat32( offset, vector.y, true ); offset += 4;
  50. output.setFloat32( offset, vector.z, true ); offset += 4;
  51. }
  52. output.setUint16( offset, 0, true ); offset += 2; // attribute byte count
  53. }
  54. } );
  55. return output;
  56. };
  57. }() )
  58. };