babylon.objFileLoader.js 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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 = new BABYLON.Texture(rootUrl + value, scene);
  90. }
  91. else if (key === "map_kd") {
  92. // Diffuse texture map with a loaded image
  93. material.diffuseTexture = new BABYLON.Texture(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 = new BABYLON.Texture(rootUrl + value, scene);
  99. }
  100. else if (key === "map_ns") {
  101. }
  102. else if (key === "map_bump") {
  103. //The bump texture
  104. material.bumpTexture = new BABYLON.Texture(rootUrl + value, scene);
  105. }
  106. else if (key === "map_d") {
  107. // The dissolve of the material
  108. material.opacityTexture = new BABYLON.Texture(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. return MTLFileLoader;
  143. })();
  144. BABYLON.MTLFileLoader = MTLFileLoader;
  145. var OBJFileLoader = (function () {
  146. function OBJFileLoader() {
  147. this.extensions = ".obj";
  148. this.obj = /^o/;
  149. this.group = /^g/;
  150. this.mtllib = /^mtllib /;
  151. this.usemtl = /^usemtl /;
  152. this.smooth = /^s /;
  153. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  154. // vn float float float
  155. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  156. // vt float float
  157. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  158. // f vertex vertex vertex ...
  159. this.facePattern1 = /f\s(([\d]{1,}[\s]?){3,})+/;
  160. // f vertex/uvs vertex/uvs vertex/uvs ...
  161. this.facePattern2 = /f\s((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  162. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  163. this.facePattern3 = /f\s((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  164. // f vertex//normal vertex//normal vertex//normal ...
  165. this.facePattern4 = /f\s((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  166. }
  167. /**
  168. * Calls synchronously the MTL file attached to this obj.
  169. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  170. * Without this function materials are not displayed in the first frame (but displayed after).
  171. * In consequence it is impossible to get material information in your HTML file
  172. *
  173. * @param url The URL of the MTL file
  174. * @param rootUrl
  175. * @param onSuccess Callback function to be called when the MTL file is loaded
  176. * @private
  177. */
  178. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  179. //XMLHTTP object to load the file
  180. var request = new XMLHttpRequest();
  181. //The complete path to the mtl file
  182. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  183. //Get the file synchronously
  184. request.open('GET', pathOfFile, false);
  185. //Check the server status
  186. request.onreadystatechange = function () {
  187. if (request.readyState === 4) {
  188. if (request.status === 200 || BABYLON.Tools.ValidateXHRData(request, 1)) {
  189. //Data are loaded
  190. onSuccess(request.responseText);
  191. }
  192. else {
  193. //File not found
  194. console.warn("Error status: " + request.status + " - Unable to load " + pathOfFile);
  195. }
  196. }
  197. };
  198. request.send(null);
  199. };
  200. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  201. //get the meshes from OBJ file
  202. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  203. //Push meshes from OBJ file into the variable mesh of this function
  204. if (meshes) {
  205. loadedMeshes.forEach(function (mesh) {
  206. meshes.push(mesh);
  207. });
  208. }
  209. return true;
  210. };
  211. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  212. //Get the 3D model
  213. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  214. };
  215. /**
  216. * Read the OBJ file and create an Array of meshes.
  217. * Each mesh contains all information given by the OBJ and the MTL file.
  218. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  219. *
  220. * @param meshesNames
  221. * @param scene BABYLON.Scene The scene where are displayed the data
  222. * @param data String The content of the obj file
  223. * @param rootUrl String The path to the folder
  224. * @returns Array<AbstractMesh>
  225. * @private
  226. */
  227. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  228. var positions = []; //values for the positions of vertices
  229. var normals = []; //Values for the normals
  230. var uvs = []; //Values for the textures
  231. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  232. var handledMesh; //The current mesh of meshes array
  233. var indicesForBabylon = []; //The list of indices for VertexData
  234. var wrappedPositionForBabylon = []; //The list of position in vectors
  235. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  236. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  237. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  238. var curPositionInIndices = 0;
  239. var hasMeshes = false; //Meshes are defined in the file
  240. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  241. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  242. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  243. var triangles = []; //Indices from new triangles coming from polygons
  244. var materialNameFromObj = ""; //The name of the current material
  245. var fileToLoad = ""; //The name of the mtlFile to load
  246. var materialsFromMTLFile = new MTLFileLoader();
  247. var objMeshName = ""; //The name of the current obj mesh
  248. var increment = 1; //Id for meshes created by the multimaterial
  249. var isFirstMaterial = true;
  250. /**
  251. * Search for obj in the given array.
  252. * This function is called to check if a couple of data already exists in an array.
  253. *
  254. * If found, returns the index of the founded tuple index. Returns -1 if not found
  255. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  256. * @param obj Array<number>
  257. * @returns {boolean}
  258. */
  259. var isInArray = function (arr, obj) {
  260. if (!arr[obj[0]])
  261. arr[obj[0]] = { normals: [], idx: [] };
  262. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  263. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  264. };
  265. var isInArrayUV = function (arr, obj) {
  266. if (!arr[obj[0]])
  267. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  268. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  269. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  270. return arr[obj[0]].idx[idx];
  271. }
  272. return -1;
  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 indiceUvsFromObj Integer The index in uvs array
  282. * @param indiceNormalFromObj Integer The index in normals array
  283. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  284. * @param textureVectorFromOBJ Vector3 The value of uvs
  285. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  286. */
  287. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  288. //Check if this tuple already exists in the list of tuples
  289. var _index;
  290. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  291. _index = isInArrayUV(tuplePosNorm, [
  292. indicePositionFromObj,
  293. indiceNormalFromObj,
  294. indiceUvsFromObj
  295. ]);
  296. }
  297. else {
  298. _index = isInArray(tuplePosNorm, [
  299. indicePositionFromObj,
  300. indiceNormalFromObj
  301. ]);
  302. }
  303. //If it not exists
  304. if (_index == -1) {
  305. //Add an new indice.
  306. //The array of indices is only an array with his length equal to the number of triangles - 1.
  307. //We add vertices data in this order
  308. indicesForBabylon.push(wrappedPositionForBabylon.length);
  309. //Push the position of vertice for Babylon
  310. //Each element is a BABYLON.Vector3(x,y,z)
  311. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  312. //Push the uvs for Babylon
  313. //Each element is a BABYLON.Vector3(u,v)
  314. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  315. //Push the normals for Babylon
  316. //Each element is a BABYLON.Vector3(x,y,z)
  317. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  318. //Add the tuple in the comparison list
  319. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  320. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  321. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  322. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  323. }
  324. else {
  325. //The tuple already exists
  326. //Add the index of the already existing tuple
  327. //At this index we can get the value of position, normal and uvs of vertex
  328. indicesForBabylon.push(_index);
  329. }
  330. };
  331. /**
  332. * Transform BABYLON.Vector() object onto 3 digits in an array
  333. */
  334. var unwrapData = function () {
  335. //Every array has the same length
  336. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  337. //Push the x, y, z values of each element in the unwrapped array
  338. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  339. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  340. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  341. }
  342. };
  343. /**
  344. * Create triangles from polygons by recursion
  345. * The best to understand how it works is to draw it in the same time you get the recursion.
  346. * It is important to notice that a triangle is a polygon
  347. * We get 4 patterns of face defined in OBJ File :
  348. * facePattern1 = ["1","2","3","4","5","6"]
  349. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  350. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  351. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  352. * Each pattern is divided by the same method
  353. * @param face Array[String] The indices of elements
  354. * @param v Integer The variable to increment
  355. */
  356. var getTriangles = function (face, v) {
  357. //Work for each element of the array
  358. if (v + 1 < face.length) {
  359. //Add on the triangle variable the indexes to obtain triangles
  360. triangles.push(face[0], face[v], face[v + 1]);
  361. //Incrementation for recursion
  362. v += 1;
  363. //Recursion
  364. getTriangles(face, v);
  365. }
  366. //Result obtained after 2 iterations:
  367. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  368. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  369. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  370. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  371. };
  372. /**
  373. * Create triangles and push the data for each polygon for the pattern 1
  374. * In this pattern we get vertice positions
  375. * @param face
  376. * @param v
  377. */
  378. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  379. //Get the indices of triangles for each polygon
  380. getTriangles(face, v);
  381. //For each element in the triangles array.
  382. //This var could contains 1 to an infinity of triangles
  383. for (var k = 0; k < triangles.length; k++) {
  384. // Set position indice
  385. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  386. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  387. positions[indicePositionFromObj], //Get the vectors data
  388. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  389. );
  390. }
  391. //Reset variable for the next line
  392. triangles = [];
  393. };
  394. /**
  395. * Create triangles and push the data for each polygon for the pattern 2
  396. * In this pattern we get vertice positions and uvsu
  397. * @param face
  398. * @param v
  399. */
  400. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  401. //Get the indices of triangles for each polygon
  402. getTriangles(face, v);
  403. for (var k = 0; k < triangles.length; k++) {
  404. //triangle[k] = "1/1"
  405. //Split the data for getting position and uv
  406. var point = triangles[k].split("/"); // ["1", "1"]
  407. //Set position indice
  408. var indicePositionFromObj = parseInt(point[0]) - 1;
  409. //Set uv indice
  410. var indiceUvsFromObj = parseInt(point[1]) - 1;
  411. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  412. positions[indicePositionFromObj], //Get the values for each element
  413. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  414. );
  415. }
  416. //Reset variable for the next line
  417. triangles = [];
  418. };
  419. /**
  420. * Create triangles and push the data for each polygon for the pattern 3
  421. * In this pattern we get vertice positions, uvs and normals
  422. * @param face
  423. * @param v
  424. */
  425. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  426. //Get the indices of triangles for each polygon
  427. getTriangles(face, v);
  428. for (var k = 0; k < triangles.length; k++) {
  429. //triangle[k] = "1/1/1"
  430. //Split the data for getting position, uv, and normals
  431. var point = triangles[k].split("/"); // ["1", "1", "1"]
  432. // Set position indice
  433. var indicePositionFromObj = parseInt(point[0]) - 1;
  434. // Set uv indice
  435. var indiceUvsFromObj = parseInt(point[1]) - 1;
  436. // Set normal indice
  437. var indiceNormalFromObj = parseInt(point[2]) - 1;
  438. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  439. );
  440. }
  441. //Reset variable for the next line
  442. triangles = [];
  443. };
  444. /**
  445. * Create triangles and push the data for each polygon for the pattern 4
  446. * In this pattern we get vertice positions and normals
  447. * @param face
  448. * @param v
  449. */
  450. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  451. getTriangles(face, v);
  452. for (var k = 0; k < triangles.length; k++) {
  453. //triangle[k] = "1//1"
  454. //Split the data for getting position and normals
  455. var point = triangles[k].split("//"); // ["1", "1"]
  456. // We check indices, and normals
  457. var indicePositionFromObj = parseInt(point[0]) - 1;
  458. var indiceNormalFromObj = parseInt(point[1]) - 1;
  459. setData(indicePositionFromObj, 1, //Default value for uv
  460. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  461. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  462. }
  463. //Reset variable for the next line
  464. triangles = [];
  465. };
  466. var addPreviousObjMesh = function () {
  467. //Check if it is not the first mesh. Otherwise we don't have data.
  468. if (meshesFromObj.length > 0) {
  469. //Get the previous mesh for applying the data about the faces
  470. //=> in obj file, faces definition append after the name of the mesh
  471. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  472. //Set the data into Array for the mesh
  473. unwrapData();
  474. // Reverse tab. Otherwise face are displayed in the wrong sens
  475. indicesForBabylon.reverse();
  476. //Set the information for the mesh
  477. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  478. handledMesh.indices = indicesForBabylon.slice();
  479. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  480. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  481. handledMesh.uvs = unwrappedUVForBabylon.slice();
  482. //Reset the array for the next mesh
  483. indicesForBabylon = [];
  484. unwrappedPositionsForBabylon = [];
  485. unwrappedNormalsForBabylon = [];
  486. unwrappedUVForBabylon = [];
  487. }
  488. };
  489. //Main function
  490. //Split the file into lines
  491. var lines = data.split('\n');
  492. //Look at each line
  493. for (var i = 0; i < lines.length; i++) {
  494. var line = lines[i].trim();
  495. var result;
  496. //Comment or newLine
  497. if (line.length === 0 || line.charAt(0) === '#') {
  498. continue;
  499. }
  500. else if ((result = this.vertexPattern.exec(line)) !== null) {
  501. //Create a Vector3 with the position x, y, z
  502. //Value of result:
  503. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  504. //Add the Vector in the list of positions
  505. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  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. //Add the Vector in the list of normals
  512. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  513. }
  514. else if ((result = this.uvPattern.exec(line)) !== null) {
  515. //Create a Vector2 with the normals u, v
  516. //Value of result
  517. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  518. //Add the Vector in the list of uvs
  519. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  520. }
  521. else if ((result = this.facePattern3.exec(line)) !== null) {
  522. //Value of result:
  523. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  524. //Set the data for this face
  525. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  526. 1);
  527. }
  528. else if ((result = this.facePattern4.exec(line)) !== null) {
  529. //Value of result:
  530. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  531. //Set the data for this face
  532. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  533. 1);
  534. }
  535. else if ((result = this.facePattern2.exec(line)) !== null) {
  536. //Value of result:
  537. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  538. //Set the data for this face
  539. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  540. 1);
  541. }
  542. else if ((result = this.facePattern1.exec(line)) !== null) {
  543. //Value of result
  544. //["f 1 2 3", "1 2 3"...]
  545. //Set the data for this face
  546. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  547. 1);
  548. }
  549. else if (this.group.test(line) || this.obj.test(line)) {
  550. //Create a new mesh corresponding to the name of the group.
  551. //Definition of the mesh
  552. var objMesh =
  553. //Set the name of the current obj mesh
  554. {
  555. name: line.substring(2).trim(),
  556. indices: undefined,
  557. positions: undefined,
  558. normals: undefined,
  559. uvs: undefined,
  560. materialName: ""
  561. };
  562. addPreviousObjMesh();
  563. //Push the last mesh created with only the name
  564. meshesFromObj.push(objMesh);
  565. //Set this variable to indicate that now meshesFromObj has objects defined inside
  566. hasMeshes = true;
  567. isFirstMaterial = true;
  568. increment = 1;
  569. }
  570. else if (this.usemtl.test(line)) {
  571. //Get the name of the material
  572. materialNameFromObj = line.substring(7).trim();
  573. //If this new material is in the same mesh
  574. if (!isFirstMaterial) {
  575. //Set the data for the previous mesh
  576. addPreviousObjMesh();
  577. //Create a new mesh
  578. var objMesh =
  579. //Set the name of the current obj mesh
  580. {
  581. name: objMeshName + "_mm" + increment.toString(),
  582. indices: undefined,
  583. positions: undefined,
  584. normals: undefined,
  585. uvs: undefined,
  586. materialName: materialNameFromObj
  587. };
  588. increment++;
  589. //If meshes are already defined
  590. meshesFromObj.push(objMesh);
  591. }
  592. //Set the material name if the previous line define a mesh
  593. if (hasMeshes && isFirstMaterial) {
  594. //Set the material name to the previous mesh (1 material per mesh)
  595. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  596. isFirstMaterial = false;
  597. }
  598. }
  599. else if (this.mtllib.test(line)) {
  600. //Get the name of mtl file
  601. fileToLoad = line.substring(7).trim();
  602. }
  603. else if (this.smooth.test(line)) {
  604. }
  605. else {
  606. //If there is another possibility
  607. console.log("Unhandled expression at line : " + line);
  608. }
  609. }
  610. //At the end of the file, add the last mesh into the meshesFromObj array
  611. if (hasMeshes) {
  612. //Set the data for the last mesh
  613. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  614. //Reverse indices for displaying faces in the good sens
  615. indicesForBabylon.reverse();
  616. //Get the good array
  617. unwrapData();
  618. //Set array
  619. handledMesh.indices = indicesForBabylon;
  620. handledMesh.positions = unwrappedPositionsForBabylon;
  621. handledMesh.normals = unwrappedNormalsForBabylon;
  622. handledMesh.uvs = unwrappedUVForBabylon;
  623. }
  624. //If any o or g keyword found, create a mesj with a random id
  625. if (!hasMeshes) {
  626. // reverse tab of indices
  627. indicesForBabylon.reverse();
  628. //Get positions normals uvs
  629. unwrapData();
  630. //Set data for one mesh
  631. meshesFromObj.push({
  632. name: BABYLON.Geometry.RandomId(),
  633. indices: indicesForBabylon,
  634. positions: unwrappedPositionsForBabylon,
  635. normals: unwrappedNormalsForBabylon,
  636. uvs: unwrappedUVForBabylon,
  637. materialName: materialNameFromObj
  638. });
  639. }
  640. //Create a BABYLON.Mesh list
  641. var vertexData = new BABYLON.VertexData(); //The container for the values
  642. var babylonMeshesArray = []; //The mesh for babylon
  643. var materialToUse = [];
  644. //Set data for each mesh
  645. for (var j = 0; j < meshesFromObj.length; j++) {
  646. //check meshesNames (stlFileLoader)
  647. if (meshesNames && meshesFromObj[j].name) {
  648. if (meshesNames instanceof Array) {
  649. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  650. continue;
  651. }
  652. }
  653. else {
  654. if (meshesFromObj[j].name !== meshesNames) {
  655. continue;
  656. }
  657. }
  658. }
  659. //Get the current mesh
  660. //Set the data with VertexBuffer for each mesh
  661. handledMesh = meshesFromObj[j];
  662. //Create a BABYLON.Mesh with the name of the obj mesh
  663. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  664. //Push the name of the material to an array
  665. //This is indispensable for the importMesh function
  666. materialToUse.push(meshesFromObj[j].materialName);
  667. //Set the data for the babylonMesh
  668. vertexData.positions = handledMesh.positions;
  669. vertexData.normals = handledMesh.normals;
  670. vertexData.uvs = handledMesh.uvs;
  671. vertexData.indices = handledMesh.indices;
  672. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  673. vertexData.applyToMesh(babylonMesh);
  674. //Push the mesh into an array
  675. babylonMeshesArray.push(babylonMesh);
  676. }
  677. //load the materials
  678. //Check if we have a file to load
  679. if (fileToLoad !== "") {
  680. //Load the file synchronously
  681. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  682. //Create materials thanks MTLLoader function
  683. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  684. //Look at each material loaded in the mtl file
  685. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  686. //Three variables to get all meshes with the same material
  687. var startIndex = 0;
  688. var _indices = [];
  689. var _index;
  690. //The material from MTL file is used in the meshes loaded
  691. //Push the indice in an array
  692. //Check if the material is not used for another mesh
  693. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  694. _indices.push(_index);
  695. startIndex = _index + 1;
  696. }
  697. //If the material is not used dispose it
  698. if (_index == -1 && _indices.length == 0) {
  699. //If the material is not needed, remove it
  700. materialsFromMTLFile.materials[n].dispose();
  701. }
  702. else {
  703. for (var o = 0; o < _indices.length; o++) {
  704. //Apply the material to the BABYLON.Mesh for each mesh with the material
  705. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  706. }
  707. }
  708. }
  709. });
  710. }
  711. //Return an array with all BABYLON.Mesh
  712. return babylonMeshesArray;
  713. };
  714. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  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 = {}));