objFileLoader.ts 51 KB

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