babylon.objFileLoader.js 37 KB

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