babylon.objFileLoader.ts 41 KB

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