babylon.objFileLoader.js 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242
  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. })(window, 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. container.removeAllFromScene();
  507. return container;
  508. });
  509. };
  510. /**
  511. * Read the OBJ file and create an Array of meshes.
  512. * Each mesh contains all information given by the OBJ and the MTL file.
  513. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  514. *
  515. * @param meshesNames
  516. * @param scene Scene The scene where are displayed the data
  517. * @param data String The content of the obj file
  518. * @param rootUrl String The path to the folder
  519. * @returns Array<AbstractMesh>
  520. * @private
  521. */
  522. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  523. var _this = this;
  524. var positions = []; //values for the positions of vertices
  525. var normals = []; //Values for the normals
  526. var uvs = []; //Values for the textures
  527. var colors = [];
  528. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  529. var handledMesh; //The current mesh of meshes array
  530. var indicesForBabylon = []; //The list of indices for VertexData
  531. var wrappedPositionForBabylon = []; //The list of position in vectors
  532. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  533. var wrappedColorsForBabylon = []; // Array with all color values to match with the indices
  534. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  535. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  536. var curPositionInIndices = 0;
  537. var hasMeshes = false; //Meshes are defined in the file
  538. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  539. var unwrappedColorsForBabylon = []; // Value of colorForBabylon w/o Color4() [r,g,b,a]
  540. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  541. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  542. var triangles = []; //Indices from new triangles coming from polygons
  543. var materialNameFromObj = ""; //The name of the current material
  544. var fileToLoad = ""; //The name of the mtlFile to load
  545. var materialsFromMTLFile = new MTLFileLoader();
  546. var objMeshName = ""; //The name of the current obj mesh
  547. var increment = 1; //Id for meshes created by the multimaterial
  548. var isFirstMaterial = true;
  549. var grayColor = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color4"](0.5, 0.5, 0.5, 1);
  550. /**
  551. * Search for obj in the given array.
  552. * This function is called to check if a couple of data already exists in an array.
  553. *
  554. * If found, returns the index of the founded tuple index. Returns -1 if not found
  555. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  556. * @param obj Array<number>
  557. * @returns {boolean}
  558. */
  559. var isInArray = function (arr, obj) {
  560. if (!arr[obj[0]]) {
  561. arr[obj[0]] = { normals: [], idx: [] };
  562. }
  563. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  564. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  565. };
  566. var isInArrayUV = function (arr, obj) {
  567. if (!arr[obj[0]]) {
  568. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  569. }
  570. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  571. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  572. return arr[obj[0]].idx[idx];
  573. }
  574. return -1;
  575. };
  576. /**
  577. * This function set the data for each triangle.
  578. * Data are position, normals and uvs
  579. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  580. * If the tuple already exist, add only their indice
  581. *
  582. * @param indicePositionFromObj Integer The index in positions array
  583. * @param indiceUvsFromObj Integer The index in uvs array
  584. * @param indiceNormalFromObj Integer The index in normals array
  585. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  586. * @param textureVectorFromOBJ Vector3 The value of uvs
  587. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  588. */
  589. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ, positionColorsFromOBJ) {
  590. //Check if this tuple already exists in the list of tuples
  591. var _index;
  592. if (_this._meshLoadOptions.OptimizeWithUV) {
  593. _index = isInArrayUV(tuplePosNorm, [
  594. indicePositionFromObj,
  595. indiceNormalFromObj,
  596. indiceUvsFromObj
  597. ]);
  598. }
  599. else {
  600. _index = isInArray(tuplePosNorm, [
  601. indicePositionFromObj,
  602. indiceNormalFromObj
  603. ]);
  604. }
  605. //If it not exists
  606. if (_index == -1) {
  607. //Add an new indice.
  608. //The array of indices is only an array with his length equal to the number of triangles - 1.
  609. //We add vertices data in this order
  610. indicesForBabylon.push(wrappedPositionForBabylon.length);
  611. //Push the position of vertice for Babylon
  612. //Each element is a Vector3(x,y,z)
  613. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  614. //Push the uvs for Babylon
  615. //Each element is a Vector3(u,v)
  616. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  617. //Push the normals for Babylon
  618. //Each element is a Vector3(x,y,z)
  619. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  620. if (positionColorsFromOBJ !== undefined) {
  621. //Push the colors for Babylon
  622. //Each element is a BABYLON.Color4(r,g,b,a)
  623. wrappedColorsForBabylon.push(positionColorsFromOBJ);
  624. }
  625. //Add the tuple in the comparison list
  626. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  627. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  628. if (_this._meshLoadOptions.OptimizeWithUV) {
  629. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  630. }
  631. }
  632. else {
  633. //The tuple already exists
  634. //Add the index of the already existing tuple
  635. //At this index we can get the value of position, normal, color and uvs of vertex
  636. indicesForBabylon.push(_index);
  637. }
  638. };
  639. /**
  640. * Transform Vector() and BABYLON.Color() objects into numbers in an array
  641. */
  642. var unwrapData = function () {
  643. //Every array has the same length
  644. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  645. //Push the x, y, z values of each element in the unwrapped array
  646. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  647. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  648. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  649. }
  650. if (_this._meshLoadOptions.ImportVertexColors === true) {
  651. //Push the r, g, b, a values of each element in the unwrapped array
  652. unwrappedColorsForBabylon.push(wrappedColorsForBabylon[l].r, wrappedColorsForBabylon[l].g, wrappedColorsForBabylon[l].b, wrappedColorsForBabylon[l].a);
  653. }
  654. // Reset arrays for the next new meshes
  655. wrappedPositionForBabylon = [];
  656. wrappedNormalsForBabylon = [];
  657. wrappedUvsForBabylon = [];
  658. wrappedColorsForBabylon = [];
  659. tuplePosNorm = [];
  660. curPositionInIndices = 0;
  661. };
  662. /**
  663. * Create triangles from polygons by recursion
  664. * The best to understand how it works is to draw it in the same time you get the recursion.
  665. * It is important to notice that a triangle is a polygon
  666. * We get 5 patterns of face defined in OBJ File :
  667. * facePattern1 = ["1","2","3","4","5","6"]
  668. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  669. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  670. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  671. * facePattern5 = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-4/-4/-4","-5/-5/-5","-6/-6/-6"]
  672. * Each pattern is divided by the same method
  673. * @param face Array[String] The indices of elements
  674. * @param v Integer The variable to increment
  675. */
  676. var getTriangles = function (face, v) {
  677. //Work for each element of the array
  678. if (v + 1 < face.length) {
  679. //Add on the triangle variable the indexes to obtain triangles
  680. triangles.push(face[0], face[v], face[v + 1]);
  681. //Incrementation for recursion
  682. v += 1;
  683. //Recursion
  684. getTriangles(face, v);
  685. }
  686. //Result obtained after 2 iterations:
  687. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  688. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  689. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  690. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  691. //Pattern5 => triangle = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-1/-1/-1","-3/-3/-3","-4/-4/-4"];
  692. };
  693. /**
  694. * Create triangles and push the data for each polygon for the pattern 1
  695. * In this pattern we get vertice positions
  696. * @param face
  697. * @param v
  698. */
  699. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  700. //Get the indices of triangles for each polygon
  701. getTriangles(face, v);
  702. //For each element in the triangles array.
  703. //This var could contains 1 to an infinity of triangles
  704. for (var k = 0; k < triangles.length; k++) {
  705. // Set position indice
  706. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  707. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  708. positions[indicePositionFromObj], //Get the vectors data
  709. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero(), babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up(), //Create default vectors
  710. _this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined);
  711. }
  712. //Reset variable for the next line
  713. triangles = [];
  714. };
  715. /**
  716. * Create triangles and push the data for each polygon for the pattern 2
  717. * In this pattern we get vertice positions and uvsu
  718. * @param face
  719. * @param v
  720. */
  721. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  722. //Get the indices of triangles for each polygon
  723. getTriangles(face, v);
  724. for (var k = 0; k < triangles.length; k++) {
  725. //triangle[k] = "1/1"
  726. //Split the data for getting position and uv
  727. var point = triangles[k].split("/"); // ["1", "1"]
  728. //Set position indice
  729. var indicePositionFromObj = parseInt(point[0]) - 1;
  730. //Set uv indice
  731. var indiceUvsFromObj = parseInt(point[1]) - 1;
  732. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  733. positions[indicePositionFromObj], //Get the values for each element
  734. uvs[indiceUvsFromObj], babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up(), //Default value for normals
  735. _this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined);
  736. }
  737. //Reset variable for the next line
  738. triangles = [];
  739. };
  740. /**
  741. * Create triangles and push the data for each polygon for the pattern 3
  742. * In this pattern we get vertice positions, uvs and normals
  743. * @param face
  744. * @param v
  745. */
  746. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  747. //Get the indices of triangles for each polygon
  748. getTriangles(face, v);
  749. for (var k = 0; k < triangles.length; k++) {
  750. //triangle[k] = "1/1/1"
  751. //Split the data for getting position, uv, and normals
  752. var point = triangles[k].split("/"); // ["1", "1", "1"]
  753. // Set position indice
  754. var indicePositionFromObj = parseInt(point[0]) - 1;
  755. // Set uv indice
  756. var indiceUvsFromObj = parseInt(point[1]) - 1;
  757. // Set normal indice
  758. var indiceNormalFromObj = parseInt(point[2]) - 1;
  759. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  760. );
  761. }
  762. //Reset variable for the next line
  763. triangles = [];
  764. };
  765. /**
  766. * Create triangles and push the data for each polygon for the pattern 4
  767. * In this pattern we get vertice positions and normals
  768. * @param face
  769. * @param v
  770. */
  771. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  772. getTriangles(face, v);
  773. for (var k = 0; k < triangles.length; k++) {
  774. //triangle[k] = "1//1"
  775. //Split the data for getting position and normals
  776. var point = triangles[k].split("//"); // ["1", "1"]
  777. // We check indices, and normals
  778. var indicePositionFromObj = parseInt(point[0]) - 1;
  779. var indiceNormalFromObj = parseInt(point[1]) - 1;
  780. setData(indicePositionFromObj, 1, //Default value for uv
  781. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  782. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero(), normals[indiceNormalFromObj], _this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined);
  783. }
  784. //Reset variable for the next line
  785. triangles = [];
  786. };
  787. /**
  788. * Create triangles and push the data for each polygon for the pattern 3
  789. * In this pattern we get vertice positions, uvs and normals
  790. * @param face
  791. * @param v
  792. */
  793. var setDataForCurrentFaceWithPattern5 = function (face, v) {
  794. //Get the indices of triangles for each polygon
  795. getTriangles(face, v);
  796. for (var k = 0; k < triangles.length; k++) {
  797. //triangle[k] = "-1/-1/-1"
  798. //Split the data for getting position, uv, and normals
  799. var point = triangles[k].split("/"); // ["-1", "-1", "-1"]
  800. // Set position indice
  801. var indicePositionFromObj = positions.length + parseInt(point[0]);
  802. // Set uv indice
  803. var indiceUvsFromObj = uvs.length + parseInt(point[1]);
  804. // Set normal indice
  805. var indiceNormalFromObj = normals.length + parseInt(point[2]);
  806. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj], //Set the vector for each component
  807. _this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined);
  808. }
  809. //Reset variable for the next line
  810. triangles = [];
  811. };
  812. var addPreviousObjMesh = function () {
  813. //Check if it is not the first mesh. Otherwise we don't have data.
  814. if (meshesFromObj.length > 0) {
  815. //Get the previous mesh for applying the data about the faces
  816. //=> in obj file, faces definition append after the name of the mesh
  817. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  818. //Set the data into Array for the mesh
  819. unwrapData();
  820. // Reverse tab. Otherwise face are displayed in the wrong sens
  821. indicesForBabylon.reverse();
  822. //Set the information for the mesh
  823. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  824. handledMesh.indices = indicesForBabylon.slice();
  825. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  826. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  827. handledMesh.uvs = unwrappedUVForBabylon.slice();
  828. if (_this._meshLoadOptions.ImportVertexColors === true) {
  829. handledMesh.colors = unwrappedColorsForBabylon.slice();
  830. }
  831. //Reset the array for the next mesh
  832. indicesForBabylon = [];
  833. unwrappedPositionsForBabylon = [];
  834. unwrappedColorsForBabylon = [];
  835. unwrappedNormalsForBabylon = [];
  836. unwrappedUVForBabylon = [];
  837. }
  838. };
  839. //Main function
  840. //Split the file into lines
  841. var lines = data.split('\n');
  842. //Look at each line
  843. for (var i = 0; i < lines.length; i++) {
  844. var line = lines[i].trim();
  845. var result;
  846. //Comment or newLine
  847. if (line.length === 0 || line.charAt(0) === '#') {
  848. continue;
  849. //Get information about one position possible for the vertices
  850. }
  851. else if (this.vertexPattern.test(line)) {
  852. result = line.split(' ');
  853. //Value of result with line: "v 1.0 2.0 3.0"
  854. // ["v", "1.0", "2.0", "3.0"]
  855. //Create a Vector3 with the position x, y, z
  856. positions.push(new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  857. if (this._meshLoadOptions.ImportVertexColors === true) {
  858. if (result.length >= 7) {
  859. // TODO: if these numbers are > 1 we can use Color4.FromInts(r,g,b,a)
  860. 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])));
  861. }
  862. else {
  863. // TODO: maybe push NULL and if all are NULL to skip (and remove grayColor var).
  864. colors.push(grayColor);
  865. }
  866. }
  867. }
  868. else if ((result = this.normalPattern.exec(line)) !== null) {
  869. //Create a Vector3 with the normals x, y, z
  870. //Value of result
  871. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  872. //Add the Vector in the list of normals
  873. normals.push(new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  874. }
  875. else if ((result = this.uvPattern.exec(line)) !== null) {
  876. //Create a Vector2 with the normals u, v
  877. //Value of result
  878. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  879. //Add the Vector in the list of uvs
  880. uvs.push(new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](parseFloat(result[1]), parseFloat(result[2])));
  881. //Identify patterns of faces
  882. //Face could be defined in different type of pattern
  883. }
  884. else if ((result = this.facePattern3.exec(line)) !== null) {
  885. //Value of result:
  886. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  887. //Set the data for this face
  888. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  889. 1);
  890. }
  891. else if ((result = this.facePattern4.exec(line)) !== null) {
  892. //Value of result:
  893. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  894. //Set the data for this face
  895. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  896. 1);
  897. }
  898. else if ((result = this.facePattern5.exec(line)) !== null) {
  899. //Value of result:
  900. //["f -1/-1/-1 -2/-2/-2 -3/-3/-3", "-1/-1/-1 -2/-2/-2 -3/-3/-3"...]
  901. //Set the data for this face
  902. setDataForCurrentFaceWithPattern5(result[1].trim().split(" "), // ["-1/-1/-1", "-2/-2/-2", "-3/-3/-3"]
  903. 1);
  904. }
  905. else if ((result = this.facePattern2.exec(line)) !== null) {
  906. //Value of result:
  907. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  908. //Set the data for this face
  909. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  910. 1);
  911. }
  912. else if ((result = this.facePattern1.exec(line)) !== null) {
  913. //Value of result
  914. //["f 1 2 3", "1 2 3"...]
  915. //Set the data for this face
  916. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  917. 1);
  918. //Define a mesh or an object
  919. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  920. }
  921. else if (this.group.test(line) || this.obj.test(line)) {
  922. //Create a new mesh corresponding to the name of the group.
  923. //Definition of the mesh
  924. var objMesh = {
  925. name: line.substring(2).trim(),
  926. indices: undefined,
  927. positions: undefined,
  928. normals: undefined,
  929. uvs: undefined,
  930. colors: undefined,
  931. materialName: ""
  932. };
  933. addPreviousObjMesh();
  934. //Push the last mesh created with only the name
  935. meshesFromObj.push(objMesh);
  936. //Set this variable to indicate that now meshesFromObj has objects defined inside
  937. hasMeshes = true;
  938. isFirstMaterial = true;
  939. increment = 1;
  940. //Keyword for applying a material
  941. }
  942. else if (this.usemtl.test(line)) {
  943. //Get the name of the material
  944. materialNameFromObj = line.substring(7).trim();
  945. //If this new material is in the same mesh
  946. if (!isFirstMaterial) {
  947. //Set the data for the previous mesh
  948. addPreviousObjMesh();
  949. //Create a new mesh
  950. var objMesh =
  951. //Set the name of the current obj mesh
  952. {
  953. name: objMeshName + "_mm" + increment.toString(),
  954. indices: undefined,
  955. positions: undefined,
  956. normals: undefined,
  957. uvs: undefined,
  958. colors: undefined,
  959. materialName: materialNameFromObj
  960. };
  961. increment++;
  962. //If meshes are already defined
  963. meshesFromObj.push(objMesh);
  964. }
  965. //Set the material name if the previous line define a mesh
  966. if (hasMeshes && isFirstMaterial) {
  967. //Set the material name to the previous mesh (1 material per mesh)
  968. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  969. isFirstMaterial = false;
  970. }
  971. //Keyword for loading the mtl file
  972. }
  973. else if (this.mtllib.test(line)) {
  974. //Get the name of mtl file
  975. fileToLoad = line.substring(7).trim();
  976. //Apply smoothing
  977. }
  978. else if (this.smooth.test(line)) {
  979. // smooth shading => apply smoothing
  980. //Toda y I don't know it work with babylon and with obj.
  981. //With the obj file an integer is set
  982. }
  983. else {
  984. //If there is another possibility
  985. console.log("Unhandled expression at line : " + line);
  986. }
  987. }
  988. //At the end of the file, add the last mesh into the meshesFromObj array
  989. if (hasMeshes) {
  990. //Set the data for the last mesh
  991. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  992. //Reverse indices for displaying faces in the good sense
  993. indicesForBabylon.reverse();
  994. //Get the good array
  995. unwrapData();
  996. //Set array
  997. handledMesh.indices = indicesForBabylon;
  998. handledMesh.positions = unwrappedPositionsForBabylon;
  999. handledMesh.normals = unwrappedNormalsForBabylon;
  1000. handledMesh.uvs = unwrappedUVForBabylon;
  1001. if (this._meshLoadOptions.ImportVertexColors === true) {
  1002. handledMesh.colors = unwrappedColorsForBabylon;
  1003. }
  1004. }
  1005. //If any o or g keyword found, create a mesh with a random id
  1006. if (!hasMeshes) {
  1007. // reverse tab of indices
  1008. indicesForBabylon.reverse();
  1009. //Get positions normals uvs
  1010. unwrapData();
  1011. //Set data for one mesh
  1012. meshesFromObj.push({
  1013. name: babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Geometry"].RandomId(),
  1014. indices: indicesForBabylon,
  1015. positions: unwrappedPositionsForBabylon,
  1016. colors: unwrappedColorsForBabylon,
  1017. normals: unwrappedNormalsForBabylon,
  1018. uvs: unwrappedUVForBabylon,
  1019. materialName: materialNameFromObj
  1020. });
  1021. }
  1022. //Create a Mesh list
  1023. var babylonMeshesArray = []; //The mesh for babylon
  1024. var materialToUse = new Array();
  1025. //Set data for each mesh
  1026. for (var j = 0; j < meshesFromObj.length; j++) {
  1027. //check meshesNames (stlFileLoader)
  1028. if (meshesNames && meshesFromObj[j].name) {
  1029. if (meshesNames instanceof Array) {
  1030. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  1031. continue;
  1032. }
  1033. }
  1034. else {
  1035. if (meshesFromObj[j].name !== meshesNames) {
  1036. continue;
  1037. }
  1038. }
  1039. }
  1040. //Get the current mesh
  1041. //Set the data with VertexBuffer for each mesh
  1042. handledMesh = meshesFromObj[j];
  1043. //Create a Mesh with the name of the obj mesh
  1044. var babylonMesh = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Mesh"](meshesFromObj[j].name, scene);
  1045. //Push the name of the material to an array
  1046. //This is indispensable for the importMesh function
  1047. materialToUse.push(meshesFromObj[j].materialName);
  1048. var vertexData = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexData"](); //The container for the values
  1049. //Set the data for the babylonMesh
  1050. vertexData.uvs = handledMesh.uvs;
  1051. vertexData.indices = handledMesh.indices;
  1052. vertexData.positions = handledMesh.positions;
  1053. if (this._meshLoadOptions.ComputeNormals === true) {
  1054. var normals_1 = new Array();
  1055. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexData"].ComputeNormals(handledMesh.positions, handledMesh.indices, normals_1);
  1056. vertexData.normals = normals_1;
  1057. }
  1058. else {
  1059. vertexData.normals = handledMesh.normals;
  1060. }
  1061. if (this._meshLoadOptions.ImportVertexColors === true) {
  1062. vertexData.colors = handledMesh.colors;
  1063. }
  1064. //Set the data from the VertexBuffer to the current Mesh
  1065. vertexData.applyToMesh(babylonMesh);
  1066. if (this._meshLoadOptions.InvertY) {
  1067. babylonMesh.scaling.y *= -1;
  1068. }
  1069. //Push the mesh into an array
  1070. babylonMeshesArray.push(babylonMesh);
  1071. }
  1072. var mtlPromises = [];
  1073. //load the materials
  1074. //Check if we have a file to load
  1075. if (fileToLoad !== "" && this._meshLoadOptions.SkipMaterials === false) {
  1076. //Load the file synchronously
  1077. mtlPromises.push(new Promise(function (resolve, reject) {
  1078. _this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  1079. try {
  1080. //Create materials thanks MTLLoader function
  1081. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  1082. //Look at each material loaded in the mtl file
  1083. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  1084. //Three variables to get all meshes with the same material
  1085. var startIndex = 0;
  1086. var _indices = [];
  1087. var _index;
  1088. //The material from MTL file is used in the meshes loaded
  1089. //Push the indice in an array
  1090. //Check if the material is not used for another mesh
  1091. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  1092. _indices.push(_index);
  1093. startIndex = _index + 1;
  1094. }
  1095. //If the material is not used dispose it
  1096. if (_index == -1 && _indices.length == 0) {
  1097. //If the material is not needed, remove it
  1098. materialsFromMTLFile.materials[n].dispose();
  1099. }
  1100. else {
  1101. for (var o = 0; o < _indices.length; o++) {
  1102. //Apply the material to the Mesh for each mesh with the material
  1103. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  1104. }
  1105. }
  1106. }
  1107. resolve();
  1108. }
  1109. catch (e) {
  1110. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Error processing MTL file: '" + fileToLoad + "'");
  1111. if (_this._meshLoadOptions.MaterialLoadingFailsSilently) {
  1112. resolve();
  1113. }
  1114. else {
  1115. reject(e);
  1116. }
  1117. }
  1118. }, function (pathOfFile, exception) {
  1119. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Error downloading MTL file: '" + fileToLoad + "'");
  1120. if (_this._meshLoadOptions.MaterialLoadingFailsSilently) {
  1121. resolve();
  1122. }
  1123. else {
  1124. reject(exception);
  1125. }
  1126. });
  1127. }));
  1128. }
  1129. //Return an array with all Mesh
  1130. return Promise.all(mtlPromises).then(function () {
  1131. return babylonMeshesArray;
  1132. });
  1133. };
  1134. /**
  1135. * Defines if UVs are optimized by default during load.
  1136. */
  1137. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  1138. /**
  1139. * Invert model on y-axis (does a model scaling inversion)
  1140. */
  1141. OBJFileLoader.INVERT_Y = false;
  1142. /**
  1143. * Include in meshes the vertex colors available in some OBJ files. This is not part of OBJ standard.
  1144. */
  1145. OBJFileLoader.IMPORT_VERTEX_COLORS = false;
  1146. /**
  1147. * Compute the normals for the model, even if normals are present in the file.
  1148. */
  1149. OBJFileLoader.COMPUTE_NORMALS = false;
  1150. /**
  1151. * Skip loading the materials even if defined in the OBJ file (materials are ignored).
  1152. */
  1153. OBJFileLoader.SKIP_MATERIALS = false;
  1154. /**
  1155. * When a material fails to load OBJ loader will silently fail and onSuccess() callback will be triggered.
  1156. *
  1157. * Defaults to true for backwards compatibility.
  1158. */
  1159. OBJFileLoader.MATERIAL_LOADING_FAILS_SILENTLY = true;
  1160. return OBJFileLoader;
  1161. }());
  1162. if (babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["SceneLoader"]) {
  1163. //Add this loader into the register plugin
  1164. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["SceneLoader"].RegisterPlugin(new OBJFileLoader());
  1165. }
  1166. /***/ }),
  1167. /***/ "./legacy/legacy-objFileLoader.ts":
  1168. /*!****************************************!*\
  1169. !*** ./legacy/legacy-objFileLoader.ts ***!
  1170. \****************************************/
  1171. /*! exports provided: MTLFileLoader, OBJFileLoader */
  1172. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  1173. "use strict";
  1174. __webpack_require__.r(__webpack_exports__);
  1175. /* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _OBJ__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OBJ */ "./OBJ/index.ts");
  1176. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MTLFileLoader", function() { return _OBJ__WEBPACK_IMPORTED_MODULE_0__["MTLFileLoader"]; });
  1177. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OBJFileLoader", function() { return _OBJ__WEBPACK_IMPORTED_MODULE_0__["OBJFileLoader"]; });
  1178. /**
  1179. * This is the entry point for the UMD module.
  1180. * The entry point for a future ESM package should be index.ts
  1181. */
  1182. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  1183. if (typeof globalObject !== "undefined") {
  1184. for (var key in _OBJ__WEBPACK_IMPORTED_MODULE_0__) {
  1185. globalObject.BABYLON[key] = _OBJ__WEBPACK_IMPORTED_MODULE_0__[key];
  1186. }
  1187. }
  1188. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
  1189. /***/ }),
  1190. /***/ "babylonjs/Misc/observable":
  1191. /*!****************************************************************************************************!*\
  1192. !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***!
  1193. \****************************************************************************************************/
  1194. /*! no static exports found */
  1195. /***/ (function(module, exports) {
  1196. module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs_Misc_observable__;
  1197. /***/ })
  1198. /******/ });
  1199. });
  1200. //# sourceMappingURL=babylon.objFileLoader.js.map