babylon.objFileLoader.js 40 KB

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