babylon.objFileLoader.js 38 KB

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