babylon.objFileLoader.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. /// <reference path="../References/babylon.2.1.d.ts"/>
  2. /// <reference path="../References/waa.d.ts"/>
  3. var BABYLON;
  4. (function (BABYLON) {
  5. /**
  6. * Class reading and parsing the MTL file bundled with the obj file.
  7. */
  8. var MTLFileLoader = (function () {
  9. function MTLFileLoader() {
  10. // All material loaded from the mtl will be set here
  11. this.materials = [];
  12. /**
  13. * This function will read the mtl file and create each material described inside
  14. * This function could be improve by adding :
  15. * -some component missing (Ni, Tf...)
  16. * -including the specific options available
  17. *
  18. * @param scene
  19. * @param data
  20. * @param rootUrl
  21. */
  22. this.parseMTL = function (scene, data, rootUrl) {
  23. //Split the lines from the file
  24. var lines = data.split('\n');
  25. //Space char
  26. var delimiter_pattern = /\s+/;
  27. //Array with RGB colors
  28. var color;
  29. //New material
  30. var material;
  31. for (var i = 0; i < lines.length; i++) {
  32. var line = lines[i];
  33. line = line.trim();
  34. // Blank line or comment
  35. if (line.length === 0 || line.charAt(0) === '#') {
  36. continue;
  37. }
  38. //Get the first parameter (keyword)
  39. var pos = line.indexOf(' ');
  40. var key = (pos >= 0) ? line.substring(0, pos) : line;
  41. key = key.toLowerCase();
  42. //Get the data following the key
  43. var value = (pos >= 0) ? line.substring(pos + 1) : "";
  44. value = value.trim();
  45. //This mtl keyword will create the new material
  46. if (key === "newmtl") {
  47. //Check if it is the first material.
  48. // Materials specifications are described after this keyword.
  49. if (material) {
  50. //Add the previous material in the material array.
  51. this.materials.push(material);
  52. }
  53. //Create a new material.
  54. // value is the name of the material read in the mtl file
  55. material = new BABYLON.StandardMaterial(value, scene);
  56. }
  57. else if (key === "kd") {
  58. // Diffuse color (color under white light) using RGB values
  59. //value = "r g b"
  60. color = value.split(delimiter_pattern, 3);
  61. //color = [r,g,b]
  62. //Set tghe color into the material
  63. material.diffuseColor = BABYLON.Color3.FromArray(color);
  64. }
  65. else if (key === "ka") {
  66. // Ambient color (color under shadow) using RGB values
  67. //value = "r g b"
  68. color = value.split(delimiter_pattern, 3);
  69. //color = [r,g,b]
  70. //Set tghe color into the material
  71. material.ambientColor = BABYLON.Color3.FromArray(color);
  72. }
  73. else if (key === "ks") {
  74. // Specular color (color when light is reflected from shiny surface) using RGB values
  75. //value = "r g b"
  76. color = value.split(delimiter_pattern, 3);
  77. //color = [r,g,b]
  78. //Set the color into the material
  79. material.specularColor = BABYLON.Color3.FromArray(color);
  80. }
  81. else if (key === "ns") {
  82. //value = "Integer"
  83. material.specularPower = value;
  84. }
  85. else if (key === "d") {
  86. //d is dissolve for current material. It mean alpha for BABYLON
  87. material.alpha = value;
  88. }
  89. else if (key === "map_ka") {
  90. // ambient texture map with a loaded image
  91. //We must first get the folder of the image
  92. material.ambientTexture = new BABYLON.Texture(rootUrl + value, scene);
  93. }
  94. else if (key === "map_kd") {
  95. // Diffuse texture map with a loaded image
  96. material.diffuseTexture = new BABYLON.Texture(rootUrl + value, scene);
  97. }
  98. else if (key === "map_ks") {
  99. // Specular texture map with a loaded image
  100. //We must first get the folder of the image
  101. material.specularTexture = new BABYLON.Texture(rootUrl + value, scene);
  102. }
  103. else if (key === "map_ns") {
  104. }
  105. else if (key === "map_bump") {
  106. //The bump texture
  107. material.bumpTexture = new BABYLON.Texture(rootUrl + value, scene);
  108. }
  109. else if (key === "map_d") {
  110. // The dissolve of the material
  111. material.opacityTexture = new BABYLON.Texture(rootUrl + value, scene);
  112. }
  113. else if (key === "illum") {
  114. //Illumination
  115. if (value === "0") {
  116. }
  117. else if (value === "1") {
  118. }
  119. else if (value === "2") {
  120. }
  121. else if (value === "3") {
  122. }
  123. else if (value === "4") {
  124. }
  125. else if (value === "5") {
  126. }
  127. else if (value === "6") {
  128. }
  129. else if (value === "7") {
  130. }
  131. else if (value === "8") {
  132. }
  133. else if (value === "9") {
  134. }
  135. else if (value === "10") {
  136. }
  137. }
  138. else {
  139. }
  140. }
  141. //At the end of the file, add the last material
  142. this.materials.push(material);
  143. };
  144. }
  145. return MTLFileLoader;
  146. })();
  147. BABYLON.MTLFileLoader = MTLFileLoader;
  148. var OBJFileLoader = (function () {
  149. function OBJFileLoader() {
  150. this.extensions = ".obj";
  151. this.obj = /^o/;
  152. this.group = /^g/;
  153. this.mtllib = /^mtllib /;
  154. this.usemtl = /^usemtl /;
  155. this.smooth = /^s /;
  156. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  157. // vn float float float
  158. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  159. // vt float float
  160. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  161. // f vertex vertex vertex ...
  162. this.facePattern1 = /f\s(([\d]{1,}[\s]?){3,})+/;
  163. // f vertex/uvs vertex/uvs vertex/uvs ...
  164. this.facePattern2 = /f\s((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  165. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  166. this.facePattern3 = /f\s((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  167. // f vertex//normal vertex//normal vertex//normal ...
  168. this.facePattern4 = /f\s((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  169. }
  170. /**
  171. * Calls synchronously the MTL file attached to this obj.
  172. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  173. * Without this function materials are not displayed in the first frame (but displayed after).
  174. * In consequence it is impossible to get material information in your HTML file
  175. *
  176. * @param url The URL of the MTL file
  177. * @param rootUrl
  178. * @param onSuccess Callback function to be called when the MTL file is loaded
  179. * @private
  180. */
  181. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  182. //XMLHTTP object to load the file
  183. var request = new XMLHttpRequest();
  184. //The complete path to the mtl file
  185. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  186. //Get the file synchronously
  187. request.open('GET', pathOfFile, false);
  188. //Check the server status
  189. request.onreadystatechange = function () {
  190. if (request.readyState === 4) {
  191. if (request.status === 200 || BABYLON.Tools.ValidateXHRData(request, 1)) {
  192. //Data are loaded
  193. onSuccess(request.responseText);
  194. }
  195. else {
  196. //File not found
  197. console.warn("Error status: " + request.status + " - Unable to load " + pathOfFile);
  198. }
  199. }
  200. };
  201. request.send(null);
  202. };
  203. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  204. //get the meshes from OBJ file
  205. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  206. //Push each mesh from OBJ file into the variable mesh of this function
  207. if (meshes) {
  208. loadedMeshes.forEach(function (mesh) {
  209. meshes.push(mesh);
  210. });
  211. }
  212. return true;
  213. };
  214. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  215. //Get the 3D model
  216. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  217. };
  218. /**
  219. * Read the OBJ file and create an Array of meshes.
  220. * Each mesh contains all information given by the OBJ and the MTL file.
  221. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  222. *
  223. * @param meshesNames
  224. * @param scene BABYLON.Scene The scene where are displayed the data
  225. * @param data String The content of the obj file
  226. * @param rootUrl String The path to the folder
  227. * @returns Array<AbstractMesh>
  228. * @private
  229. */
  230. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  231. var positions = []; //values for the positions of vertices
  232. var normals = []; //Values for the normals
  233. var uvs = []; //Values for the textures
  234. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  235. var handledMesh; //The current mesh of meshes array
  236. var indicesForBabylon = []; //The list of indices for VertexData
  237. var wrappedPositionForBabylon = []; //The list of position in vectors
  238. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  239. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  240. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  241. var hasMeshes = false; //Meshes are defined in the file
  242. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  243. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  244. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  245. var triangles = []; //Indices from new triangles coming from polygons
  246. var materialName = ""; //The name of the current material
  247. var fileToLoad = ""; //The name of the mtlFile to load
  248. var materialsFromMTLFile = new MTLFileLoader();
  249. /**
  250. * Search for obj in the given array.
  251. * This function is called to check if a couple of data already exists in an array.
  252. *
  253. * If found, returns the index of the founded tuple index. Returns -1 if not found
  254. * @param arr Array<BABYLON.Vector2>
  255. * @param obj BABYLON.Vector2
  256. * @returns {number}
  257. */
  258. var isInArray = function (arr, obj) {
  259. //Default value : not found
  260. var res = -1;
  261. for (var i = 0; i < arr.length; i++) {
  262. var element = arr[i];
  263. //Comparison of each element of the tuple
  264. if (element.x === obj.x && element.y === obj.y) {
  265. res = i;
  266. }
  267. }
  268. //Return the indice of the founded element
  269. return res;
  270. };
  271. /**
  272. * This function set the data for each triangle.
  273. * Data are position, normals and uvs
  274. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  275. * If the tuple already exist, add only their indice
  276. *
  277. * @param indicePositionFromObj Integer The index in positions array
  278. * @param indiceNormalFromObj Integer The index in normals array
  279. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  280. * @param textureVectorFromOBJ Vector3 The value of uvs
  281. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  282. */
  283. var setData = function (indicePositionFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  284. //Create a new tuple composed with the indice of position and normal
  285. var tuple = new BABYLON.Vector2(indicePositionFromObj, indiceNormalFromObj);
  286. //Check if this tuple already exists in the list of tuples
  287. var _index = isInArray(tuplePosNorm, tuple);
  288. //If it not exists
  289. if (_index == -1) {
  290. //Add an new indice.
  291. //The array of indices is only an array with his length equal to the number of triangles - 1.
  292. //We add vertices data in this order
  293. indicesForBabylon.push(wrappedPositionForBabylon.length);
  294. //Push the position of vertice for Babylon
  295. //Each element is a BABYLON.Vector3(x,y,z)
  296. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  297. //Push the uvs for Babylon
  298. //Each element is a BABYLON.Vector3(u,v)
  299. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  300. //Push the normals for Babylon
  301. //Each element is a BABYLON.Vector3(x,y,z)
  302. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  303. //Add the tuple in the comparison list
  304. tuplePosNorm.push(tuple);
  305. }
  306. else {
  307. //The tuple already exists
  308. //Add the index of the already existing tuple
  309. //At this index we can get the value of position, normal and uvs of vertex
  310. indicesForBabylon.push(_index);
  311. }
  312. };
  313. /**
  314. * Transform BABYLON.Vector() object onto 3 digits in an array
  315. */
  316. var unwrapData = function () {
  317. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  318. //Push the x, y, z values of each element in the unwrapped array
  319. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  320. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  321. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  322. }
  323. };
  324. /**
  325. * Create triangles from polygons by recursion
  326. * The best to understand how it works is to draw it in the same time you get the recursion.
  327. * It is important to notice that a triangle is a polygon
  328. * We get 4 patterns of face defined in OBJ File :
  329. * facePattern1 = ["1","2","3","4","5","6"]
  330. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  331. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  332. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  333. * Each pattern is divided by the same method
  334. * @param face Array[String] The indices of elements
  335. * @param v Integer The variable to increment
  336. */
  337. var getTriangles = function (face, v) {
  338. //Work for each element of the array
  339. if (v + 1 < face.length) {
  340. //Add on the triangle variable the indexes to obtain triangles
  341. triangles.push(face[0], face[v], face[v + 1]);
  342. //Incrementation for recursion
  343. v += 1;
  344. //Recursion
  345. getTriangles(face, v);
  346. }
  347. //Result obtained after 2 iterations:
  348. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  349. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  350. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  351. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  352. };
  353. /**
  354. * Create triangles and push the data for each polygon for the pattern 1
  355. * In this pattern we get vertice positions
  356. * @param face
  357. * @param v
  358. */
  359. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  360. //Get the indices of triangles for each polygon
  361. getTriangles(face, v);
  362. for (var k = 0; k < triangles.length; k++) {
  363. // Set position indice
  364. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  365. //In the pattern 1, normals and uvs are not defined
  366. //Default values are set
  367. var indiceUvsFromObj = 0;
  368. var indiceNormalFromObj = 0;
  369. //Get the vectors data
  370. var positionVectorFromOBJ = positions[indicePositionFromObj];
  371. //Create default vectors
  372. var textureVectorFromOBJ = new BABYLON.Vector2(0, 0);
  373. var normalsVectorFromOBJ = new BABYLON.Vector3(0, 1, 0);
  374. setData(indicePositionFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ);
  375. }
  376. //Reset variable for the next line
  377. triangles = [];
  378. };
  379. /**
  380. * Create triangles and push the data for each polygon for the pattern 2
  381. * In this pattern we get vertice positions and uvs
  382. * @param face
  383. * @param v
  384. */
  385. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  386. //Get the indices of triangles for each polygon
  387. getTriangles(face, v);
  388. for (var k = 0; k < triangles.length; k++) {
  389. //triangle[k] = "1/1"
  390. //Split the data for getting position and uv
  391. var point = triangles[k].split("/"); // ["1", "1"]
  392. //Set position indice
  393. var indicePositionFromObj = parseInt(point[0]) - 1;
  394. //Set uv indice
  395. var indiceUvsFromObj = parseInt(point[1]) - 1;
  396. //Default value for normals
  397. var indiceNormalFromObj = 0;
  398. //Get the values for each element
  399. var positionVectorFromOBJ = positions[indicePositionFromObj];
  400. var textureVectorFromOBJ = uvs[indiceUvsFromObj];
  401. //Default value for normals
  402. var normalsVectorFromOBJ = new BABYLON.Vector3(0, 1, 0);
  403. setData(indicePositionFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ);
  404. }
  405. //Reset variable for the next line
  406. triangles = [];
  407. };
  408. /**
  409. * Create triangles and push the data for each polygon for the pattern 3
  410. * In this pattern we get vertice positions, uvs and normals
  411. * @param face
  412. * @param v
  413. */
  414. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  415. //Get the indices of triangles for each polygon
  416. getTriangles(face, v);
  417. for (var k = 0; k < triangles.length; k++) {
  418. //triangle[k] = "1/1/1"
  419. //Split the data for getting position, uv, and normals
  420. var point = triangles[k].split("/"); // ["1", "1", "1"]
  421. // Set position indice
  422. var indicePositionFromObj = parseInt(point[0]) - 1;
  423. // Set uv indice
  424. var indiceUvsFromObj = parseInt(point[1]) - 1;
  425. // Set normal indice
  426. var indiceNormalFromObj = parseInt(point[2]) - 1;
  427. //Set the vector for each component
  428. var positionVectorFromOBJ = positions[indicePositionFromObj];
  429. var textureVectorFromOBJ = uvs[indiceUvsFromObj];
  430. var normalsVectorFromOBJ = normals[indiceNormalFromObj];
  431. setData(indicePositionFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ);
  432. }
  433. //Reset variable for the next line
  434. triangles = [];
  435. };
  436. /**
  437. * Create triangles and push the data for each polygon for the pattern 4
  438. * In this pattern we get vertice positions and normals
  439. * @param face
  440. * @param v
  441. */
  442. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  443. getTriangles(face, v);
  444. for (var k = 0; k < triangles.length; k++) {
  445. //triangle[k] = "1//1"
  446. //Split the data for getting position and normals
  447. var point = triangles[k].split("//"); // ["1", "1"]
  448. // We check indices, and normals
  449. var indicePositionFromObj = parseInt(point[0]) - 1;
  450. var indiceNormalFromObj = parseInt(point[1]) - 1;
  451. //Default value for uv
  452. var indiceUvsFromObj = 1;
  453. //Get each vector of data
  454. var positionVectorFromOBJ = positions[indicePositionFromObj];
  455. var textureVectorFromOBJ = new BABYLON.Vector2(0, 0);
  456. var normalsVectorFromOBJ = normals[indiceNormalFromObj];
  457. setData(indicePositionFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ);
  458. }
  459. //Reset variable for the next line
  460. triangles = [];
  461. };
  462. //Main function
  463. //Split the file into lines
  464. var lines = data.split('\n');
  465. for (var i = 0; i < lines.length; i++) {
  466. var line = lines[i];
  467. line = line.trim();
  468. var result;
  469. //Comment or newLine
  470. if (line.length === 0 || line.charAt(0) === '#') {
  471. continue;
  472. }
  473. else if ((result = this.vertexPattern.exec(line)) !== null) {
  474. //Create a Vector3 with the position x, y, z
  475. //Value of result:
  476. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  477. var vectVertex = new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]));
  478. //Add the Vector in the list of positions
  479. positions.push(vectVertex);
  480. }
  481. else if ((result = this.normalPattern.exec(line)) !== null) {
  482. //Create a Vector3 with the normals x, y, z
  483. //Value of result
  484. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  485. var vectNormals = new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]));
  486. //Add the Vector in the list of normals
  487. normals.push(vectNormals);
  488. }
  489. else if ((result = this.uvPattern.exec(line)) !== null) {
  490. //Create a Vector2 with the normals u, v
  491. //Value of result
  492. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  493. var vectUV = new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2]));
  494. //Add the Vector in the list of uvs
  495. uvs.push(vectUV);
  496. }
  497. else if ((result = this.facePattern3.exec(line)) !== null) {
  498. //Value of result:
  499. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  500. result = result[1].trim();
  501. var face = result.split(" "); // ["1/1/1", "2/2/2", "3/3/3"]
  502. //Set the data for this face
  503. setDataForCurrentFaceWithPattern3(face, 1);
  504. }
  505. else if ((result = this.facePattern4.exec(line)) !== null) {
  506. //Value of result:
  507. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  508. result = result[1].trim();
  509. var face = result.split(" "); // ["1//1", "2//2", "3//3"]
  510. //Set the data for this face
  511. setDataForCurrentFaceWithPattern4(face, 1);
  512. }
  513. else if ((result = this.facePattern2.exec(line)) !== null) {
  514. //Value of result:
  515. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  516. result = result[1].trim();
  517. var face = result.split(" "); // ["1/1", "2/2", "3/3"]
  518. //Set the data for this face
  519. setDataForCurrentFaceWithPattern2(face, 1);
  520. }
  521. else if ((result = this.facePattern1.exec(line)) !== null) {
  522. //Value of result
  523. //["f 1 2 3", "1 2 3"...]
  524. result = result[1].trim();
  525. var face = result.split(" "); // ["1", "2", "3"]
  526. //Set the data for this face
  527. setDataForCurrentFaceWithPattern1(face, 1);
  528. }
  529. else if (this.group.test(line) || this.obj.test(line)) {
  530. //Create a new mesh corresponding to the name of the group.
  531. //Definition of the mesh
  532. var objMesh = {
  533. name: line.substring(2).trim(),
  534. indices: undefined,
  535. positions: undefined,
  536. normals: undefined,
  537. uvs: undefined,
  538. materialName: ""
  539. };
  540. //Check if it is not the first mesh. Otherwise we don't have data.
  541. if (meshesFromObj.length > 0) {
  542. //Get the previous mesh for applying the data about the faces
  543. //=> in obj file, faces definition append after the name of the mesh
  544. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  545. //Set the data into Array for the mesh
  546. unwrapData();
  547. // Reverse tab. Otherwise face are displayed in the wrong sens
  548. indicesForBabylon.reverse();
  549. //Set the information for the mesh
  550. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  551. handledMesh.indices = indicesForBabylon.slice();
  552. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  553. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  554. handledMesh.uvs = unwrappedUVForBabylon.slice();
  555. //Reset the array for the next mesh
  556. indicesForBabylon = [];
  557. unwrappedPositionsForBabylon = [];
  558. unwrappedNormalsForBabylon = [];
  559. unwrappedUVForBabylon = [];
  560. }
  561. //Push the last mesh created with only the name
  562. meshesFromObj.push(objMesh);
  563. //Set this variable to indicate that now meshesFromObj has objects defined inside
  564. hasMeshes = true;
  565. }
  566. else if (this.usemtl.test(line)) {
  567. //Get the name of the material
  568. materialName = line.substring(7).trim();
  569. //If meshes are already defined
  570. if (hasMeshes) {
  571. var m = meshesFromObj.length;
  572. //Set the material name to the previous mesh (1 material per mesh)
  573. meshesFromObj[m - 1].materialName = materialName;
  574. }
  575. }
  576. else if (this.mtllib.test(line)) {
  577. //Get the name of mtl file
  578. fileToLoad = line.substring(7).trim();
  579. }
  580. else if (this.smooth.test(line)) {
  581. }
  582. else {
  583. //If there is another possibility
  584. console.log("Unhandled expression at line : " + line);
  585. }
  586. }
  587. //At the end of the file, add the last mesh into the meshesFromObj array
  588. if (hasMeshes) {
  589. //Set the data for the last mesh
  590. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  591. //Reverse indices for displaying faces in the good sens
  592. indicesForBabylon.reverse();
  593. //Get the good array
  594. unwrapData();
  595. //Set array
  596. handledMesh.indices = indicesForBabylon;
  597. handledMesh.positions = unwrappedPositionsForBabylon;
  598. handledMesh.normals = unwrappedNormalsForBabylon;
  599. handledMesh.uvs = unwrappedUVForBabylon;
  600. }
  601. //If any o or g keyword found, create a mesj with a random id
  602. if (!hasMeshes) {
  603. //If there is no object name or no mesh name
  604. var myname = BABYLON.Geometry.RandomId();
  605. // reverse tab of indices
  606. indicesForBabylon.reverse();
  607. //Get positions normals uvs
  608. unwrapData();
  609. //Set data for one mesh
  610. meshesFromObj.push({
  611. name: myname,
  612. indices: indicesForBabylon,
  613. positions: unwrappedPositionsForBabylon,
  614. normals: unwrappedNormalsForBabylon,
  615. uvs: unwrappedUVForBabylon,
  616. materialName: materialName
  617. });
  618. }
  619. //Create a BABYLON.Mesh list
  620. var vertexData = new BABYLON.VertexData(); //The container for the values
  621. var babylonMeshesArray = []; //The mesh for babylon
  622. var materialToUse = [];
  623. for (var j = 0; j < meshesFromObj.length; j++) {
  624. //check meshesNames (stlFileLoader)
  625. if (meshesNames && meshesFromObj[j].name) {
  626. if (meshesNames instanceof Array) {
  627. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  628. continue;
  629. }
  630. }
  631. else {
  632. if (meshesFromObj[j].name !== meshesNames) {
  633. continue;
  634. }
  635. }
  636. }
  637. //Get the current mesh
  638. //Set the data with VertexBuffer for each mesh
  639. handledMesh = meshesFromObj[j];
  640. //Create a BABYLON.Mesh with the name of the obj mesh
  641. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  642. //Push the name of the material to an array
  643. //This is indispensable for the importMesh function
  644. materialToUse.push(meshesFromObj[j].materialName);
  645. //Set the data for the babylonMesh
  646. vertexData.positions = handledMesh.positions;
  647. vertexData.normals = handledMesh.normals;
  648. vertexData.uvs = handledMesh.uvs;
  649. vertexData.indices = handledMesh.indices;
  650. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  651. vertexData.applyToMesh(babylonMesh);
  652. //Push the mesh into an array
  653. babylonMeshesArray.push(babylonMesh);
  654. }
  655. //load the materials
  656. //Check if we have a file to load
  657. if (fileToLoad !== "") {
  658. //Load the file synchronously
  659. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  660. //Create materials thanks MTLLoader function
  661. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  662. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  663. //Get the index of the MTL material corresponding with the BABYLON.Mesh material
  664. var _index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name);
  665. if (_index == -1) {
  666. //If the material is not needed, remove it
  667. materialsFromMTLFile.materials[n].dispose();
  668. }
  669. else {
  670. //Apply the material to the BABYLON.Mesh
  671. babylonMeshesArray[_index].material = materialsFromMTLFile.materials[n];
  672. }
  673. }
  674. });
  675. }
  676. //Return an array with all BABYLON.Mesh
  677. return babylonMeshesArray;
  678. };
  679. return OBJFileLoader;
  680. })();
  681. BABYLON.OBJFileLoader = OBJFileLoader;
  682. //Add this loader into the register plugin
  683. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  684. })(BABYLON || (BABYLON = {}));