babylon.objFileLoader.js 39 KB

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