babylon.objFileLoader.js 48 KB

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