babylon.objFileLoader.ts 40 KB

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