babylon.objFileLoader.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798
  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.loadAssets = function (scene, data, rootUrl, onError) {
  264. var container = new BABYLON.AssetContainer(scene);
  265. var result = this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  266. if (result) {
  267. container.removeAllFromScene();
  268. return container;
  269. }
  270. return null;
  271. };
  272. /**
  273. * Read the OBJ file and create an Array of meshes.
  274. * Each mesh contains all information given by the OBJ and the MTL file.
  275. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  276. *
  277. * @param meshesNames
  278. * @param scene BABYLON.Scene The scene where are displayed the data
  279. * @param data String The content of the obj file
  280. * @param rootUrl String The path to the folder
  281. * @returns Array<AbstractMesh>
  282. * @private
  283. */
  284. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  285. var positions = []; //values for the positions of vertices
  286. var normals = []; //Values for the normals
  287. var uvs = []; //Values for the textures
  288. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  289. var handledMesh; //The current mesh of meshes array
  290. var indicesForBabylon = []; //The list of indices for VertexData
  291. var wrappedPositionForBabylon = []; //The list of position in vectors
  292. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  293. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  294. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  295. var curPositionInIndices = 0;
  296. var hasMeshes = false; //Meshes are defined in the file
  297. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  298. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  299. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  300. var triangles = []; //Indices from new triangles coming from polygons
  301. var materialNameFromObj = ""; //The name of the current material
  302. var fileToLoad = ""; //The name of the mtlFile to load
  303. var materialsFromMTLFile = new MTLFileLoader();
  304. var objMeshName = ""; //The name of the current obj mesh
  305. var increment = 1; //Id for meshes created by the multimaterial
  306. var isFirstMaterial = true;
  307. /**
  308. * Search for obj in the given array.
  309. * This function is called to check if a couple of data already exists in an array.
  310. *
  311. * If found, returns the index of the founded tuple index. Returns -1 if not found
  312. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  313. * @param obj Array<number>
  314. * @returns {boolean}
  315. */
  316. var isInArray = function (arr, obj) {
  317. if (!arr[obj[0]])
  318. arr[obj[0]] = { normals: [], idx: [] };
  319. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  320. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  321. };
  322. var isInArrayUV = function (arr, obj) {
  323. if (!arr[obj[0]])
  324. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  325. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  326. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  327. return arr[obj[0]].idx[idx];
  328. }
  329. return -1;
  330. };
  331. /**
  332. * This function set the data for each triangle.
  333. * Data are position, normals and uvs
  334. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  335. * If the tuple already exist, add only their indice
  336. *
  337. * @param indicePositionFromObj Integer The index in positions array
  338. * @param indiceUvsFromObj Integer The index in uvs array
  339. * @param indiceNormalFromObj Integer The index in normals array
  340. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  341. * @param textureVectorFromOBJ Vector3 The value of uvs
  342. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  343. */
  344. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  345. //Check if this tuple already exists in the list of tuples
  346. var _index;
  347. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  348. _index = isInArrayUV(tuplePosNorm, [
  349. indicePositionFromObj,
  350. indiceNormalFromObj,
  351. indiceUvsFromObj
  352. ]);
  353. }
  354. else {
  355. _index = isInArray(tuplePosNorm, [
  356. indicePositionFromObj,
  357. indiceNormalFromObj
  358. ]);
  359. }
  360. //If it not exists
  361. if (_index == -1) {
  362. //Add an new indice.
  363. //The array of indices is only an array with his length equal to the number of triangles - 1.
  364. //We add vertices data in this order
  365. indicesForBabylon.push(wrappedPositionForBabylon.length);
  366. //Push the position of vertice for Babylon
  367. //Each element is a BABYLON.Vector3(x,y,z)
  368. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  369. //Push the uvs for Babylon
  370. //Each element is a BABYLON.Vector3(u,v)
  371. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  372. //Push the normals for Babylon
  373. //Each element is a BABYLON.Vector3(x,y,z)
  374. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  375. //Add the tuple in the comparison list
  376. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  377. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  378. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  379. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  380. }
  381. else {
  382. //The tuple already exists
  383. //Add the index of the already existing tuple
  384. //At this index we can get the value of position, normal and uvs of vertex
  385. indicesForBabylon.push(_index);
  386. }
  387. };
  388. /**
  389. * Transform BABYLON.Vector() object onto 3 digits in an array
  390. */
  391. var unwrapData = function () {
  392. //Every array has the same length
  393. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  394. //Push the x, y, z values of each element in the unwrapped array
  395. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  396. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  397. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  398. }
  399. // Reset arrays for the next new meshes
  400. wrappedPositionForBabylon = [];
  401. wrappedNormalsForBabylon = [];
  402. wrappedUvsForBabylon = [];
  403. tuplePosNorm = [];
  404. curPositionInIndices = 0;
  405. };
  406. /**
  407. * Create triangles from polygons by recursion
  408. * The best to understand how it works is to draw it in the same time you get the recursion.
  409. * It is important to notice that a triangle is a polygon
  410. * We get 4 patterns of face defined in OBJ File :
  411. * facePattern1 = ["1","2","3","4","5","6"]
  412. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  413. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  414. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  415. * Each pattern is divided by the same method
  416. * @param face Array[String] The indices of elements
  417. * @param v Integer The variable to increment
  418. */
  419. var getTriangles = function (face, v) {
  420. //Work for each element of the array
  421. if (v + 1 < face.length) {
  422. //Add on the triangle variable the indexes to obtain triangles
  423. triangles.push(face[0], face[v], face[v + 1]);
  424. //Incrementation for recursion
  425. v += 1;
  426. //Recursion
  427. getTriangles(face, v);
  428. }
  429. //Result obtained after 2 iterations:
  430. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  431. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  432. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  433. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  434. };
  435. /**
  436. * Create triangles and push the data for each polygon for the pattern 1
  437. * In this pattern we get vertice positions
  438. * @param face
  439. * @param v
  440. */
  441. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  442. //Get the indices of triangles for each polygon
  443. getTriangles(face, v);
  444. //For each element in the triangles array.
  445. //This var could contains 1 to an infinity of triangles
  446. for (var k = 0; k < triangles.length; k++) {
  447. // Set position indice
  448. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  449. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  450. positions[indicePositionFromObj], //Get the vectors data
  451. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  452. );
  453. }
  454. //Reset variable for the next line
  455. triangles = [];
  456. };
  457. /**
  458. * Create triangles and push the data for each polygon for the pattern 2
  459. * In this pattern we get vertice positions and uvsu
  460. * @param face
  461. * @param v
  462. */
  463. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  464. //Get the indices of triangles for each polygon
  465. getTriangles(face, v);
  466. for (var k = 0; k < triangles.length; k++) {
  467. //triangle[k] = "1/1"
  468. //Split the data for getting position and uv
  469. var point = triangles[k].split("/"); // ["1", "1"]
  470. //Set position indice
  471. var indicePositionFromObj = parseInt(point[0]) - 1;
  472. //Set uv indice
  473. var indiceUvsFromObj = parseInt(point[1]) - 1;
  474. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  475. positions[indicePositionFromObj], //Get the values for each element
  476. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  477. );
  478. }
  479. //Reset variable for the next line
  480. triangles = [];
  481. };
  482. /**
  483. * Create triangles and push the data for each polygon for the pattern 3
  484. * In this pattern we get vertice positions, uvs and normals
  485. * @param face
  486. * @param v
  487. */
  488. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  489. //Get the indices of triangles for each polygon
  490. getTriangles(face, v);
  491. for (var k = 0; k < triangles.length; k++) {
  492. //triangle[k] = "1/1/1"
  493. //Split the data for getting position, uv, and normals
  494. var point = triangles[k].split("/"); // ["1", "1", "1"]
  495. // Set position indice
  496. var indicePositionFromObj = parseInt(point[0]) - 1;
  497. // Set uv indice
  498. var indiceUvsFromObj = parseInt(point[1]) - 1;
  499. // Set normal indice
  500. var indiceNormalFromObj = parseInt(point[2]) - 1;
  501. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  502. );
  503. }
  504. //Reset variable for the next line
  505. triangles = [];
  506. };
  507. /**
  508. * Create triangles and push the data for each polygon for the pattern 4
  509. * In this pattern we get vertice positions and normals
  510. * @param face
  511. * @param v
  512. */
  513. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  514. getTriangles(face, v);
  515. for (var k = 0; k < triangles.length; k++) {
  516. //triangle[k] = "1//1"
  517. //Split the data for getting position and normals
  518. var point = triangles[k].split("//"); // ["1", "1"]
  519. // We check indices, and normals
  520. var indicePositionFromObj = parseInt(point[0]) - 1;
  521. var indiceNormalFromObj = parseInt(point[1]) - 1;
  522. setData(indicePositionFromObj, 1, //Default value for uv
  523. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  524. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  525. }
  526. //Reset variable for the next line
  527. triangles = [];
  528. };
  529. var addPreviousObjMesh = function () {
  530. //Check if it is not the first mesh. Otherwise we don't have data.
  531. if (meshesFromObj.length > 0) {
  532. //Get the previous mesh for applying the data about the faces
  533. //=> in obj file, faces definition append after the name of the mesh
  534. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  535. //Set the data into Array for the mesh
  536. unwrapData();
  537. // Reverse tab. Otherwise face are displayed in the wrong sens
  538. indicesForBabylon.reverse();
  539. //Set the information for the mesh
  540. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  541. handledMesh.indices = indicesForBabylon.slice();
  542. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  543. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  544. handledMesh.uvs = unwrappedUVForBabylon.slice();
  545. //Reset the array for the next mesh
  546. indicesForBabylon = [];
  547. unwrappedPositionsForBabylon = [];
  548. unwrappedNormalsForBabylon = [];
  549. unwrappedUVForBabylon = [];
  550. }
  551. };
  552. //Main function
  553. //Split the file into lines
  554. var lines = data.split('\n');
  555. //Look at each line
  556. for (var i = 0; i < lines.length; i++) {
  557. var line = lines[i].trim();
  558. var result;
  559. //Comment or newLine
  560. if (line.length === 0 || line.charAt(0) === '#') {
  561. continue;
  562. //Get information about one position possible for the vertices
  563. }
  564. else if ((result = this.vertexPattern.exec(line)) !== null) {
  565. //Create a Vector3 with the position x, y, z
  566. //Value of result:
  567. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  568. //Add the Vector in the list of positions
  569. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  570. }
  571. else if ((result = this.normalPattern.exec(line)) !== null) {
  572. //Create a Vector3 with the normals x, y, z
  573. //Value of result
  574. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  575. //Add the Vector in the list of normals
  576. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  577. }
  578. else if ((result = this.uvPattern.exec(line)) !== null) {
  579. //Create a Vector2 with the normals u, v
  580. //Value of result
  581. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  582. //Add the Vector in the list of uvs
  583. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  584. //Identify patterns of faces
  585. //Face could be defined in different type of pattern
  586. }
  587. else if ((result = this.facePattern3.exec(line)) !== null) {
  588. //Value of result:
  589. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  590. //Set the data for this face
  591. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  592. 1);
  593. }
  594. else if ((result = this.facePattern4.exec(line)) !== null) {
  595. //Value of result:
  596. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  597. //Set the data for this face
  598. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  599. 1);
  600. }
  601. else if ((result = this.facePattern2.exec(line)) !== null) {
  602. //Value of result:
  603. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  604. //Set the data for this face
  605. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  606. 1);
  607. }
  608. else if ((result = this.facePattern1.exec(line)) !== null) {
  609. //Value of result
  610. //["f 1 2 3", "1 2 3"...]
  611. //Set the data for this face
  612. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  613. 1);
  614. //Define a mesh or an object
  615. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  616. }
  617. else if (this.group.test(line) || this.obj.test(line)) {
  618. //Create a new mesh corresponding to the name of the group.
  619. //Definition of the mesh
  620. var objMesh =
  621. //Set the name of the current obj mesh
  622. {
  623. name: line.substring(2).trim(),
  624. indices: undefined,
  625. positions: undefined,
  626. normals: undefined,
  627. uvs: undefined,
  628. materialName: ""
  629. };
  630. addPreviousObjMesh();
  631. //Push the last mesh created with only the name
  632. meshesFromObj.push(objMesh);
  633. //Set this variable to indicate that now meshesFromObj has objects defined inside
  634. hasMeshes = true;
  635. isFirstMaterial = true;
  636. increment = 1;
  637. //Keyword for applying a material
  638. }
  639. else if (this.usemtl.test(line)) {
  640. //Get the name of the material
  641. materialNameFromObj = line.substring(7).trim();
  642. //If this new material is in the same mesh
  643. if (!isFirstMaterial) {
  644. //Set the data for the previous mesh
  645. addPreviousObjMesh();
  646. //Create a new mesh
  647. var objMesh =
  648. //Set the name of the current obj mesh
  649. {
  650. name: objMeshName + "_mm" + increment.toString(),
  651. indices: undefined,
  652. positions: undefined,
  653. normals: undefined,
  654. uvs: undefined,
  655. materialName: materialNameFromObj
  656. };
  657. increment++;
  658. //If meshes are already defined
  659. meshesFromObj.push(objMesh);
  660. }
  661. //Set the material name if the previous line define a mesh
  662. if (hasMeshes && isFirstMaterial) {
  663. //Set the material name to the previous mesh (1 material per mesh)
  664. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  665. isFirstMaterial = false;
  666. }
  667. //Keyword for loading the mtl file
  668. }
  669. else if (this.mtllib.test(line)) {
  670. //Get the name of mtl file
  671. fileToLoad = line.substring(7).trim();
  672. //Apply smoothing
  673. }
  674. else if (this.smooth.test(line)) {
  675. // smooth shading => apply smoothing
  676. //Toda y I don't know it work with babylon and with obj.
  677. //With the obj file an integer is set
  678. }
  679. else {
  680. //If there is another possibility
  681. console.log("Unhandled expression at line : " + line);
  682. }
  683. }
  684. //At the end of the file, add the last mesh into the meshesFromObj array
  685. if (hasMeshes) {
  686. //Set the data for the last mesh
  687. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  688. //Reverse indices for displaying faces in the good sens
  689. indicesForBabylon.reverse();
  690. //Get the good array
  691. unwrapData();
  692. //Set array
  693. handledMesh.indices = indicesForBabylon;
  694. handledMesh.positions = unwrappedPositionsForBabylon;
  695. handledMesh.normals = unwrappedNormalsForBabylon;
  696. handledMesh.uvs = unwrappedUVForBabylon;
  697. }
  698. //If any o or g keyword found, create a mesj with a random id
  699. if (!hasMeshes) {
  700. // reverse tab of indices
  701. indicesForBabylon.reverse();
  702. //Get positions normals uvs
  703. unwrapData();
  704. //Set data for one mesh
  705. meshesFromObj.push({
  706. name: BABYLON.Geometry.RandomId(),
  707. indices: indicesForBabylon,
  708. positions: unwrappedPositionsForBabylon,
  709. normals: unwrappedNormalsForBabylon,
  710. uvs: unwrappedUVForBabylon,
  711. materialName: materialNameFromObj
  712. });
  713. }
  714. //Create a BABYLON.Mesh list
  715. var babylonMeshesArray = []; //The mesh for babylon
  716. var materialToUse = new Array();
  717. //Set data for each mesh
  718. for (var j = 0; j < meshesFromObj.length; j++) {
  719. //check meshesNames (stlFileLoader)
  720. if (meshesNames && meshesFromObj[j].name) {
  721. if (meshesNames instanceof Array) {
  722. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  723. continue;
  724. }
  725. }
  726. else {
  727. if (meshesFromObj[j].name !== meshesNames) {
  728. continue;
  729. }
  730. }
  731. }
  732. //Get the current mesh
  733. //Set the data with VertexBuffer for each mesh
  734. handledMesh = meshesFromObj[j];
  735. //Create a BABYLON.Mesh with the name of the obj mesh
  736. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  737. //Push the name of the material to an array
  738. //This is indispensable for the importMesh function
  739. materialToUse.push(meshesFromObj[j].materialName);
  740. var vertexData = new BABYLON.VertexData(); //The container for the values
  741. //Set the data for the babylonMesh
  742. vertexData.positions = handledMesh.positions;
  743. vertexData.normals = handledMesh.normals;
  744. vertexData.uvs = handledMesh.uvs;
  745. vertexData.indices = handledMesh.indices;
  746. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  747. vertexData.applyToMesh(babylonMesh);
  748. //Push the mesh into an array
  749. babylonMeshesArray.push(babylonMesh);
  750. }
  751. //load the materials
  752. //Check if we have a file to load
  753. if (fileToLoad !== "") {
  754. //Load the file synchronously
  755. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  756. //Create materials thanks MTLLoader function
  757. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  758. //Look at each material loaded in the mtl file
  759. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  760. //Three variables to get all meshes with the same material
  761. var startIndex = 0;
  762. var _indices = [];
  763. var _index;
  764. //The material from MTL file is used in the meshes loaded
  765. //Push the indice in an array
  766. //Check if the material is not used for another mesh
  767. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  768. _indices.push(_index);
  769. startIndex = _index + 1;
  770. }
  771. //If the material is not used dispose it
  772. if (_index == -1 && _indices.length == 0) {
  773. //If the material is not needed, remove it
  774. materialsFromMTLFile.materials[n].dispose();
  775. }
  776. else {
  777. for (var o = 0; o < _indices.length; o++) {
  778. //Apply the material to the BABYLON.Mesh for each mesh with the material
  779. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  780. }
  781. }
  782. }
  783. });
  784. }
  785. //Return an array with all BABYLON.Mesh
  786. return babylonMeshesArray;
  787. };
  788. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  789. return OBJFileLoader;
  790. }());
  791. BABYLON.OBJFileLoader = OBJFileLoader;
  792. if (BABYLON.SceneLoader) {
  793. //Add this loader into the register plugin
  794. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  795. }
  796. })(BABYLON || (BABYLON = {}));
  797. //# sourceMappingURL=babylon.objFileLoader.js.map