babylon.objFileLoader.js 40 KB

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