babylon.objFileLoader.js 40 KB

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