babylon.objFileLoader.ts 41 KB

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