stlFileLoader.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. import { SceneLoader, ISceneLoaderPlugin, ISceneLoaderPluginExtensions, Scene, Nullable, AbstractMesh, IParticleSystem, Skeleton, Mesh, Tools, AssetContainer, VertexBuffer } from "babylonjs";
  2. /**
  3. * STL file type loader.
  4. * This is a babylon scene loader plugin.
  5. */
  6. export class STLFileLoader implements ISceneLoaderPlugin {
  7. /** @hidden */
  8. public solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  9. /** @hidden */
  10. public facetsPattern = /facet([\s\S]*?)endfacet/g;
  11. /** @hidden */
  12. public normalPattern = /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;
  13. /** @hidden */
  14. public vertexPattern = /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;
  15. /**
  16. * Defines the name of the plugin.
  17. */
  18. public name = "stl";
  19. /**
  20. * Defines the extensions the stl loader is able to load.
  21. * force data to come in as an ArrayBuffer
  22. * we'll convert to string if it looks like it's an ASCII .stl
  23. */
  24. public extensions: ISceneLoaderPluginExtensions = {
  25. ".stl": { isBinary: true },
  26. };
  27. /**
  28. * Import meshes into a scene.
  29. * @param meshesNames An array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  30. * @param scene The scene to import into
  31. * @param data The data to import
  32. * @param rootUrl The root url for scene and resources
  33. * @param meshes The meshes array to import into
  34. * @param particleSystems The particle systems array to import into
  35. * @param skeletons The skeletons array to import into
  36. * @param onError The callback when import fails
  37. * @returns True if successful or false otherwise
  38. */
  39. public importMesh(meshesNames: any, scene: Scene, data: any, rootUrl: string, meshes: Nullable<AbstractMesh[]>, particleSystems: Nullable<IParticleSystem[]>, skeletons: Nullable<Skeleton[]>): boolean {
  40. var matches;
  41. if (typeof data !== "string") {
  42. if (this._isBinary(data)) {
  43. // binary .stl
  44. var babylonMesh = new Mesh("stlmesh", scene);
  45. this._parseBinary(babylonMesh, data);
  46. if (meshes) {
  47. meshes.push(babylonMesh);
  48. }
  49. return true;
  50. }
  51. // ASCII .stl
  52. // convert to string
  53. var array_buffer = new Uint8Array(data);
  54. var str = '';
  55. for (var i = 0; i < data.byteLength; i++) {
  56. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  57. }
  58. data = str;
  59. }
  60. //if arrived here, data is a string, containing the STLA data.
  61. while (matches = this.solidPattern.exec(data)) {
  62. var meshName = matches[1];
  63. var meshNameFromEnd = matches[3];
  64. if (meshName != meshNameFromEnd) {
  65. Tools.Error("Error in STL, solid name != endsolid name");
  66. return false;
  67. }
  68. // check meshesNames
  69. if (meshesNames && meshName) {
  70. if (meshesNames instanceof Array) {
  71. if (!meshesNames.indexOf(meshName)) {
  72. continue;
  73. }
  74. } else {
  75. if (meshName !== meshesNames) {
  76. continue;
  77. }
  78. }
  79. }
  80. // stl mesh name can be empty as well
  81. meshName = meshName || "stlmesh";
  82. var babylonMesh = new Mesh(meshName, scene);
  83. this._parseASCII(babylonMesh, matches[2]);
  84. if (meshes) {
  85. meshes.push(babylonMesh);
  86. }
  87. }
  88. return true;
  89. }
  90. /**
  91. * Load into a scene.
  92. * @param scene The scene to load into
  93. * @param data The data to import
  94. * @param rootUrl The root url for scene and resources
  95. * @param onError The callback when import fails
  96. * @returns true if successful or false otherwise
  97. */
  98. public load(scene: Scene, data: any, rootUrl: string): boolean {
  99. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  100. if (result) {
  101. scene.createDefaultCameraOrLight();
  102. }
  103. return result;
  104. }
  105. /**
  106. * Load into an asset container.
  107. * @param scene The scene to load into
  108. * @param data The data to import
  109. * @param rootUrl The root url for scene and resources
  110. * @param onError The callback when import fails
  111. * @returns The loaded asset container
  112. */
  113. public loadAssetContainer(scene: Scene, data: string, rootUrl: string, onError?: (message: string, exception?: any) => void): AssetContainer {
  114. var container = new AssetContainer(scene);
  115. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  116. container.removeAllFromScene();
  117. return container;
  118. }
  119. private _isBinary(data: any) {
  120. // check if file size is correct for binary stl
  121. var faceSize, nFaces, reader;
  122. reader = new DataView(data);
  123. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  124. nFaces = reader.getUint32(80, true);
  125. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  126. return true;
  127. }
  128. // check characters higher than ASCII to confirm binary
  129. var fileLength = reader.byteLength;
  130. for (var index = 0; index < fileLength; index++) {
  131. if (reader.getUint8(index) > 127) {
  132. return true;
  133. }
  134. }
  135. return false;
  136. }
  137. private _parseBinary(mesh: Mesh, data: ArrayBuffer) {
  138. var reader = new DataView(data);
  139. var faces = reader.getUint32(80, true);
  140. var dataOffset = 84;
  141. var faceLength = 12 * 4 + 2;
  142. var offset = 0;
  143. var positions = new Float32Array(faces * 3 * 3);
  144. var normals = new Float32Array(faces * 3 * 3);
  145. var indices = new Uint32Array(faces * 3);
  146. var indicesCount = 0;
  147. for (var face = 0; face < faces; face++) {
  148. var start = dataOffset + face * faceLength;
  149. var normalX = reader.getFloat32(start, true);
  150. var normalY = reader.getFloat32(start + 4, true);
  151. var normalZ = reader.getFloat32(start + 8, true);
  152. for (var i = 1; i <= 3; i++) {
  153. var vertexstart = start + i * 12;
  154. // ordering is intentional to match ascii import
  155. positions[offset] = reader.getFloat32(vertexstart, true);
  156. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  157. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  158. normals[offset] = normalX;
  159. normals[offset + 2] = normalY;
  160. normals[offset + 1] = normalZ;
  161. offset += 3;
  162. }
  163. indices[indicesCount] = indicesCount++;
  164. indices[indicesCount] = indicesCount++;
  165. indices[indicesCount] = indicesCount++;
  166. }
  167. mesh.setVerticesData(VertexBuffer.PositionKind, positions);
  168. mesh.setVerticesData(VertexBuffer.NormalKind, normals);
  169. mesh.setIndices(indices);
  170. mesh.computeWorldMatrix(true);
  171. }
  172. private _parseASCII(mesh: Mesh, solidData: string) {
  173. var positions = [];
  174. var normals = [];
  175. var indices = [];
  176. var indicesCount = 0;
  177. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  178. var matches;
  179. while (matches = this.facetsPattern.exec(solidData)) {
  180. var facet = matches[1];
  181. //one normal per face
  182. var normalMatches = this.normalPattern.exec(facet);
  183. this.normalPattern.lastIndex = 0;
  184. if (!normalMatches) {
  185. continue;
  186. }
  187. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  188. var vertexMatch;
  189. while (vertexMatch = this.vertexPattern.exec(facet)) {
  190. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  191. normals.push(normal[0], normal[1], normal[2]);
  192. }
  193. indices.push(indicesCount++, indicesCount++, indicesCount++);
  194. this.vertexPattern.lastIndex = 0;
  195. }
  196. this.facetsPattern.lastIndex = 0;
  197. mesh.setVerticesData(VertexBuffer.PositionKind, positions);
  198. mesh.setVerticesData(VertexBuffer.NormalKind, normals);
  199. mesh.setIndices(indices);
  200. mesh.computeWorldMatrix(true);
  201. }
  202. }
  203. if (SceneLoader) {
  204. SceneLoader.RegisterPlugin(new STLFileLoader());
  205. }