babylon.objFileLoader.js 38 KB

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