babylon.objFileLoader.js 59 KB

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