babylon.objFileLoader.ts 47 KB

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