babylon.objFileLoader.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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 materialNameFromObj = ""; //The name of the current material
  247. var fileToLoad = ""; //The name of the mtlFile to load
  248. var materialsFromMTLFile = new MTLFileLoader();
  249. var objMeshName = ""; //The name of the current obj mesh
  250. var increment = 1; //Id for meshes created by the multimaterial
  251. var isFirstMaterial = true;
  252. /**
  253. * Search for obj in the given array.
  254. * This function is called to check if a couple of data already exists in an array.
  255. *
  256. * If found, returns the index of the founded tuple index. Returns -1 if not found
  257. * @param arr Array<BABYLON.Vector2>
  258. * @param obj BABYLON.Vector2
  259. * @returns {number}
  260. */
  261. var isInArray = function (arr, obj) {
  262. //Default value : not found
  263. var res = -1;
  264. for (var i = 0; i < arr.length; i++) {
  265. var element = arr[i];
  266. //Comparison of each element of the tuple
  267. if (element.x === obj.x && element.y === obj.y) {
  268. res = i;
  269. }
  270. }
  271. //Return the indice of the founded element
  272. return res;
  273. };
  274. /**
  275. * This function set the data for each triangle.
  276. * Data are position, normals and uvs
  277. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  278. * If the tuple already exist, add only their indice
  279. *
  280. * @param indicePositionFromObj Integer The index in positions array
  281. * @param indiceNormalFromObj Integer The index in normals array
  282. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  283. * @param textureVectorFromOBJ Vector3 The value of uvs
  284. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  285. */
  286. var setData = function (indicePositionFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  287. //Create a new tuple composed with the indice of position and normal
  288. var tuple = new BABYLON.Vector2(indicePositionFromObj, indiceNormalFromObj);
  289. //Check if this tuple already exists in the list of tuples
  290. var _index = isInArray(tuplePosNorm, tuple);
  291. //If it not exists
  292. if (_index == -1) {
  293. //Add an new indice.
  294. //The array of indices is only an array with his length equal to the number of triangles - 1.
  295. //We add vertices data in this order
  296. indicesForBabylon.push(wrappedPositionForBabylon.length);
  297. //Push the position of vertice for Babylon
  298. //Each element is a BABYLON.Vector3(x,y,z)
  299. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  300. //Push the uvs for Babylon
  301. //Each element is a BABYLON.Vector3(u,v)
  302. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  303. //Push the normals for Babylon
  304. //Each element is a BABYLON.Vector3(x,y,z)
  305. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  306. //Add the tuple in the comparison list
  307. tuplePosNorm.push(tuple);
  308. }
  309. else {
  310. //The tuple already exists
  311. //Add the index of the already existing tuple
  312. //At this index we can get the value of position, normal and uvs of vertex
  313. indicesForBabylon.push(_index);
  314. }
  315. };
  316. /**
  317. * Transform BABYLON.Vector() object onto 3 digits in an array
  318. */
  319. var unwrapData = function () {
  320. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  321. //Push the x, y, z values of each element in the unwrapped array
  322. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  323. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  324. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  325. }
  326. };
  327. /**
  328. * Create triangles from polygons by recursion
  329. * The best to understand how it works is to draw it in the same time you get the recursion.
  330. * It is important to notice that a triangle is a polygon
  331. * We get 4 patterns of face defined in OBJ File :
  332. * facePattern1 = ["1","2","3","4","5","6"]
  333. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  334. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  335. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  336. * Each pattern is divided by the same method
  337. * @param face Array[String] The indices of elements
  338. * @param v Integer The variable to increment
  339. */
  340. var getTriangles = function (face, v) {
  341. //Work for each element of the array
  342. if (v + 1 < face.length) {
  343. //Add on the triangle variable the indexes to obtain triangles
  344. triangles.push(face[0], face[v], face[v + 1]);
  345. //Incrementation for recursion
  346. v += 1;
  347. //Recursion
  348. getTriangles(face, v);
  349. }
  350. //Result obtained after 2 iterations:
  351. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  352. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  353. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  354. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  355. };
  356. /**
  357. * Create triangles and push the data for each polygon for the pattern 1
  358. * In this pattern we get vertice positions
  359. * @param face
  360. * @param v
  361. */
  362. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  363. //Get the indices of triangles for each polygon
  364. getTriangles(face, v);
  365. for (var k = 0; k < triangles.length; k++) {
  366. // Set position indice
  367. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  368. //In the pattern 1, normals and uvs are not defined
  369. //Default values are set
  370. var indiceUvsFromObj = 0;
  371. var indiceNormalFromObj = 0;
  372. //Get the vectors data
  373. var positionVectorFromOBJ = positions[indicePositionFromObj];
  374. //Create default vectors
  375. var textureVectorFromOBJ = new BABYLON.Vector2(0, 0);
  376. var normalsVectorFromOBJ = new BABYLON.Vector3(0, 1, 0);
  377. setData(indicePositionFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ);
  378. }
  379. //Reset variable for the next line
  380. triangles = [];
  381. };
  382. /**
  383. * Create triangles and push the data for each polygon for the pattern 2
  384. * In this pattern we get vertice positions and uvs
  385. * @param face
  386. * @param v
  387. */
  388. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  389. //Get the indices of triangles for each polygon
  390. getTriangles(face, v);
  391. for (var k = 0; k < triangles.length; k++) {
  392. //triangle[k] = "1/1"
  393. //Split the data for getting position and uv
  394. var point = triangles[k].split("/"); // ["1", "1"]
  395. //Set position indice
  396. var indicePositionFromObj = parseInt(point[0]) - 1;
  397. //Set uv indice
  398. var indiceUvsFromObj = parseInt(point[1]) - 1;
  399. //Default value for normals
  400. var indiceNormalFromObj = 0;
  401. //Get the values for each element
  402. var positionVectorFromOBJ = positions[indicePositionFromObj];
  403. var textureVectorFromOBJ = uvs[indiceUvsFromObj];
  404. //Default value for normals
  405. var normalsVectorFromOBJ = new BABYLON.Vector3(0, 1, 0);
  406. setData(indicePositionFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ);
  407. }
  408. //Reset variable for the next line
  409. triangles = [];
  410. };
  411. /**
  412. * Create triangles and push the data for each polygon for the pattern 3
  413. * In this pattern we get vertice positions, uvs and normals
  414. * @param face
  415. * @param v
  416. */
  417. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  418. //Get the indices of triangles for each polygon
  419. getTriangles(face, v);
  420. for (var k = 0; k < triangles.length; k++) {
  421. //triangle[k] = "1/1/1"
  422. //Split the data for getting position, uv, and normals
  423. var point = triangles[k].split("/"); // ["1", "1", "1"]
  424. // Set position indice
  425. var indicePositionFromObj = parseInt(point[0]) - 1;
  426. // Set uv indice
  427. var indiceUvsFromObj = parseInt(point[1]) - 1;
  428. // Set normal indice
  429. var indiceNormalFromObj = parseInt(point[2]) - 1;
  430. //Set the vector for each component
  431. var positionVectorFromOBJ = positions[indicePositionFromObj];
  432. var textureVectorFromOBJ = uvs[indiceUvsFromObj];
  433. var normalsVectorFromOBJ = normals[indiceNormalFromObj];
  434. setData(indicePositionFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ);
  435. }
  436. //Reset variable for the next line
  437. triangles = [];
  438. };
  439. /**
  440. * Create triangles and push the data for each polygon for the pattern 4
  441. * In this pattern we get vertice positions and normals
  442. * @param face
  443. * @param v
  444. */
  445. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  446. getTriangles(face, v);
  447. for (var k = 0; k < triangles.length; k++) {
  448. //triangle[k] = "1//1"
  449. //Split the data for getting position and normals
  450. var point = triangles[k].split("//"); // ["1", "1"]
  451. // We check indices, and normals
  452. var indicePositionFromObj = parseInt(point[0]) - 1;
  453. var indiceNormalFromObj = parseInt(point[1]) - 1;
  454. //Default value for uv
  455. var indiceUvsFromObj = 1;
  456. //Get each vector of data
  457. var positionVectorFromOBJ = positions[indicePositionFromObj];
  458. var textureVectorFromOBJ = new BABYLON.Vector2(0, 0);
  459. var normalsVectorFromOBJ = normals[indiceNormalFromObj];
  460. setData(indicePositionFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ);
  461. }
  462. //Reset variable for the next line
  463. triangles = [];
  464. };
  465. var addPreviousObjMesh = function () {
  466. //Check if it is not the first mesh. Otherwise we don't have data.
  467. if (meshesFromObj.length > 0) {
  468. //Get the previous mesh for applying the data about the faces
  469. //=> in obj file, faces definition append after the name of the mesh
  470. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  471. //Set the data into Array for the mesh
  472. unwrapData();
  473. // Reverse tab. Otherwise face are displayed in the wrong sens
  474. indicesForBabylon.reverse();
  475. //Set the information for the mesh
  476. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  477. handledMesh.indices = indicesForBabylon.slice();
  478. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  479. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  480. handledMesh.uvs = unwrappedUVForBabylon.slice();
  481. //Reset the array for the next mesh
  482. indicesForBabylon = [];
  483. unwrappedPositionsForBabylon = [];
  484. unwrappedNormalsForBabylon = [];
  485. unwrappedUVForBabylon = [];
  486. }
  487. };
  488. //Main function
  489. //Split the file into lines
  490. var lines = data.split('\n');
  491. for (var i = 0; i < lines.length; i++) {
  492. var line = lines[i];
  493. line = line.trim();
  494. var result;
  495. //Comment or newLine
  496. if (line.length === 0 || line.charAt(0) === '#') {
  497. continue;
  498. }
  499. else if ((result = this.vertexPattern.exec(line)) !== null) {
  500. //Create a Vector3 with the position x, y, z
  501. //Value of result:
  502. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  503. var vectVertex = new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]));
  504. //Add the Vector in the list of positions
  505. positions.push(vectVertex);
  506. }
  507. else if ((result = this.normalPattern.exec(line)) !== null) {
  508. //Create a Vector3 with the normals x, y, z
  509. //Value of result
  510. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  511. var vectNormals = new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]));
  512. //Add the Vector in the list of normals
  513. normals.push(vectNormals);
  514. }
  515. else if ((result = this.uvPattern.exec(line)) !== null) {
  516. //Create a Vector2 with the normals u, v
  517. //Value of result
  518. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  519. var vectUV = new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2]));
  520. //Add the Vector in the list of uvs
  521. uvs.push(vectUV);
  522. }
  523. else if ((result = this.facePattern3.exec(line)) !== null) {
  524. //Value of result:
  525. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  526. result = result[1].trim();
  527. var face = result.split(" "); // ["1/1/1", "2/2/2", "3/3/3"]
  528. //Set the data for this face
  529. setDataForCurrentFaceWithPattern3(face, 1);
  530. }
  531. else if ((result = this.facePattern4.exec(line)) !== null) {
  532. //Value of result:
  533. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  534. result = result[1].trim();
  535. var face = result.split(" "); // ["1//1", "2//2", "3//3"]
  536. //Set the data for this face
  537. setDataForCurrentFaceWithPattern4(face, 1);
  538. }
  539. else if ((result = this.facePattern2.exec(line)) !== null) {
  540. //Value of result:
  541. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  542. result = result[1].trim();
  543. var face = result.split(" "); // ["1/1", "2/2", "3/3"]
  544. //Set the data for this face
  545. setDataForCurrentFaceWithPattern2(face, 1);
  546. }
  547. else if ((result = this.facePattern1.exec(line)) !== null) {
  548. //Value of result
  549. //["f 1 2 3", "1 2 3"...]
  550. result = result[1].trim();
  551. var face = result.split(" "); // ["1", "2", "3"]
  552. //Set the data for this face
  553. setDataForCurrentFaceWithPattern1(face, 1);
  554. }
  555. else if (this.group.test(line) || this.obj.test(line)) {
  556. //Create a new mesh corresponding to the name of the group.
  557. //Definition of the mesh
  558. var objMeshName = line.substring(2).trim();
  559. var objMesh = {
  560. name: objMeshName,
  561. indices: undefined,
  562. positions: undefined,
  563. normals: undefined,
  564. uvs: undefined,
  565. materialName: ""
  566. };
  567. addPreviousObjMesh();
  568. //Push the last mesh created with only the name
  569. meshesFromObj.push(objMesh);
  570. //Set this variable to indicate that now meshesFromObj has objects defined inside
  571. hasMeshes = true;
  572. isFirstMaterial = true;
  573. increment = 1;
  574. }
  575. else if (this.usemtl.test(line)) {
  576. //Get the name of the material
  577. materialNameFromObj = line.substring(7).trim();
  578. //If this new material is in the same mesh
  579. if (!isFirstMaterial) {
  580. //Set the data for the previous mesh
  581. addPreviousObjMesh();
  582. //Create a new mesh
  583. var objMesh = {
  584. name: objMeshName + "_mm" + increment.toString(),
  585. indices: undefined,
  586. positions: undefined,
  587. normals: undefined,
  588. uvs: undefined,
  589. materialName: materialNameFromObj
  590. };
  591. increment += 1;
  592. //If meshes are already defined
  593. meshesFromObj.push(objMesh);
  594. }
  595. //Set the material name if the previous line define a mesh
  596. if (hasMeshes && isFirstMaterial) {
  597. var m = meshesFromObj.length;
  598. //Set the material name to the previous mesh (1 material per mesh)
  599. meshesFromObj[m - 1].materialName = materialNameFromObj;
  600. isFirstMaterial = false;
  601. }
  602. }
  603. else if (this.mtllib.test(line)) {
  604. //Get the name of mtl file
  605. fileToLoad = line.substring(7).trim();
  606. }
  607. else if (this.smooth.test(line)) {
  608. }
  609. else {
  610. //If there is another possibility
  611. console.log("Unhandled expression at line : " + line);
  612. }
  613. }
  614. //At the end of the file, add the last mesh into the meshesFromObj array
  615. if (hasMeshes) {
  616. //Set the data for the last mesh
  617. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  618. //Reverse indices for displaying faces in the good sens
  619. indicesForBabylon.reverse();
  620. //Get the good array
  621. unwrapData();
  622. //Set array
  623. handledMesh.indices = indicesForBabylon;
  624. handledMesh.positions = unwrappedPositionsForBabylon;
  625. handledMesh.normals = unwrappedNormalsForBabylon;
  626. handledMesh.uvs = unwrappedUVForBabylon;
  627. }
  628. //If any o or g keyword found, create a mesj with a random id
  629. if (!hasMeshes) {
  630. //If there is no object name or no mesh name
  631. var myname = BABYLON.Geometry.RandomId();
  632. // reverse tab of indices
  633. indicesForBabylon.reverse();
  634. //Get positions normals uvs
  635. unwrapData();
  636. //Set data for one mesh
  637. meshesFromObj.push({
  638. name: myname,
  639. indices: indicesForBabylon,
  640. positions: unwrappedPositionsForBabylon,
  641. normals: unwrappedNormalsForBabylon,
  642. uvs: unwrappedUVForBabylon,
  643. materialName: materialNameFromObj
  644. });
  645. }
  646. //Create a BABYLON.Mesh list
  647. var vertexData = new BABYLON.VertexData(); //The container for the values
  648. var babylonMeshesArray = []; //The mesh for babylon
  649. var materialToUse = [];
  650. for (var j = 0; j < meshesFromObj.length; j++) {
  651. //check meshesNames (stlFileLoader)
  652. if (meshesNames && meshesFromObj[j].name) {
  653. if (meshesNames instanceof Array) {
  654. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  655. continue;
  656. }
  657. }
  658. else {
  659. if (meshesFromObj[j].name !== meshesNames) {
  660. continue;
  661. }
  662. }
  663. }
  664. //Get the current mesh
  665. //Set the data with VertexBuffer for each mesh
  666. handledMesh = meshesFromObj[j];
  667. //Create a BABYLON.Mesh with the name of the obj mesh
  668. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  669. //Push the name of the material to an array
  670. //This is indispensable for the importMesh function
  671. materialToUse.push(meshesFromObj[j].materialName);
  672. //Set the data for the babylonMesh
  673. vertexData.positions = handledMesh.positions;
  674. vertexData.normals = handledMesh.normals;
  675. vertexData.uvs = handledMesh.uvs;
  676. vertexData.indices = handledMesh.indices;
  677. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  678. vertexData.applyToMesh(babylonMesh);
  679. //Push the mesh into an array
  680. babylonMeshesArray.push(babylonMesh);
  681. }
  682. //load the materials
  683. //Check if we have a file to load
  684. if (fileToLoad !== "") {
  685. //Load the file synchronously
  686. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  687. //Create materials thanks MTLLoader function
  688. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  689. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  690. //Three variables to get all meshes with the same material
  691. var startIndex = 0;
  692. var _indices = [];
  693. var _index;
  694. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  695. _indices.push(_index);
  696. startIndex = _index + 1;
  697. }
  698. //If the material is not used dispose it
  699. if (_index == -1 && _indices.length == 0) {
  700. //If the material is not needed, remove it
  701. materialsFromMTLFile.materials[n].dispose();
  702. }
  703. else {
  704. for (var o = 0; o < _indices.length; o++) {
  705. //Apply the material to the BABYLON.Mesh for each mesh with the material
  706. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  707. }
  708. }
  709. }
  710. });
  711. }
  712. //Return an array with all BABYLON.Mesh
  713. return babylonMeshesArray;
  714. };
  715. return OBJFileLoader;
  716. })();
  717. BABYLON.OBJFileLoader = OBJFileLoader;
  718. //Add this loader into the register plugin
  719. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  720. })(BABYLON || (BABYLON = {}));