babylon.objFileLoader.js 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296
  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_tools__) {
  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 _mtlFileLoader__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./mtlFileLoader */ "./OBJ/mtlFileLoader.ts");
  130. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MTLFileLoader", function() { return _mtlFileLoader__WEBPACK_IMPORTED_MODULE_0__["MTLFileLoader"]; });
  131. /* harmony import */ var _objFileLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./objFileLoader */ "./OBJ/objFileLoader.ts");
  132. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OBJFileLoader", function() { return _objFileLoader__WEBPACK_IMPORTED_MODULE_1__["OBJFileLoader"]; });
  133. /***/ }),
  134. /***/ "./OBJ/mtlFileLoader.ts":
  135. /*!******************************!*\
  136. !*** ./OBJ/mtlFileLoader.ts ***!
  137. \******************************/
  138. /*! exports provided: MTLFileLoader */
  139. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  140. "use strict";
  141. __webpack_require__.r(__webpack_exports__);
  142. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MTLFileLoader", function() { return MTLFileLoader; });
  143. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/tools");
  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, false, MTLFileLoader.INVERT_TEXTURE_Y);
  351. };
  352. /**
  353. * Invert Y-Axis of referenced textures on load
  354. */
  355. MTLFileLoader.INVERT_TEXTURE_Y = true;
  356. return MTLFileLoader;
  357. }());
  358. /***/ }),
  359. /***/ "./OBJ/objFileLoader.ts":
  360. /*!******************************!*\
  361. !*** ./OBJ/objFileLoader.ts ***!
  362. \******************************/
  363. /*! exports provided: OBJFileLoader */
  364. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  365. "use strict";
  366. __webpack_require__.r(__webpack_exports__);
  367. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OBJFileLoader", function() { return OBJFileLoader; });
  368. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Misc/tools");
  369. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__);
  370. /* harmony import */ var _mtlFileLoader__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./mtlFileLoader */ "./OBJ/mtlFileLoader.ts");
  371. /**
  372. * OBJ file type loader.
  373. * This is a babylon scene loader plugin.
  374. */
  375. var OBJFileLoader = /** @class */ (function () {
  376. /**
  377. * Creates loader for .OBJ files
  378. *
  379. * @param meshLoadOptions options for loading and parsing OBJ/MTL files.
  380. */
  381. function OBJFileLoader(meshLoadOptions) {
  382. /**
  383. * Defines the name of the plugin.
  384. */
  385. this.name = "obj";
  386. /**
  387. * Defines the extension the plugin is able to load.
  388. */
  389. this.extensions = ".obj";
  390. /** @hidden */
  391. this.obj = /^o/;
  392. /** @hidden */
  393. this.group = /^g/;
  394. /** @hidden */
  395. this.mtllib = /^mtllib /;
  396. /** @hidden */
  397. this.usemtl = /^usemtl /;
  398. /** @hidden */
  399. this.smooth = /^s /;
  400. /** @hidden */
  401. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+){3,7}/;
  402. // vn float float float
  403. /** @hidden */
  404. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  405. // vt float float
  406. /** @hidden */
  407. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  408. // f vertex vertex vertex ...
  409. /** @hidden */
  410. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  411. // f vertex/uvs vertex/uvs vertex/uvs ...
  412. /** @hidden */
  413. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  414. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  415. /** @hidden */
  416. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  417. // f vertex//normal vertex//normal vertex//normal ...
  418. /** @hidden */
  419. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  420. // f -vertex/-uvs/-normal -vertex/-uvs/-normal -vertex/-uvs/-normal ...
  421. /** @hidden */
  422. this.facePattern5 = /f\s+(((-[\d]{1,}\/-[\d]{1,}\/-[\d]{1,}[\s]?){3,})+)/;
  423. this._meshLoadOptions = meshLoadOptions || OBJFileLoader.currentMeshLoadOptions;
  424. }
  425. Object.defineProperty(OBJFileLoader, "INVERT_TEXTURE_Y", {
  426. /**
  427. * Invert Y-Axis of referenced textures on load
  428. */
  429. get: function () {
  430. return _mtlFileLoader__WEBPACK_IMPORTED_MODULE_1__["MTLFileLoader"].INVERT_TEXTURE_Y;
  431. },
  432. set: function (value) {
  433. _mtlFileLoader__WEBPACK_IMPORTED_MODULE_1__["MTLFileLoader"].INVERT_TEXTURE_Y = value;
  434. },
  435. enumerable: true,
  436. configurable: true
  437. });
  438. Object.defineProperty(OBJFileLoader, "currentMeshLoadOptions", {
  439. get: function () {
  440. return {
  441. ComputeNormals: OBJFileLoader.COMPUTE_NORMALS,
  442. ImportVertexColors: OBJFileLoader.IMPORT_VERTEX_COLORS,
  443. InvertY: OBJFileLoader.INVERT_Y,
  444. InvertTextureY: OBJFileLoader.INVERT_TEXTURE_Y,
  445. UVScaling: OBJFileLoader.UV_SCALING,
  446. MaterialLoadingFailsSilently: OBJFileLoader.MATERIAL_LOADING_FAILS_SILENTLY,
  447. OptimizeWithUV: OBJFileLoader.OPTIMIZE_WITH_UV,
  448. SkipMaterials: OBJFileLoader.SKIP_MATERIALS
  449. };
  450. },
  451. enumerable: true,
  452. configurable: true
  453. });
  454. /**
  455. * Calls synchronously the MTL file attached to this obj.
  456. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  457. * Without this function materials are not displayed in the first frame (but displayed after).
  458. * In consequence it is impossible to get material information in your HTML file
  459. *
  460. * @param url The URL of the MTL file
  461. * @param rootUrl
  462. * @param onSuccess Callback function to be called when the MTL file is loaded
  463. * @private
  464. */
  465. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess, onFailure) {
  466. //The complete path to the mtl file
  467. var pathOfFile = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].BaseUrl + rootUrl + url;
  468. // Loads through the babylon tools to allow fileInput search.
  469. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function (request, exception) {
  470. onFailure(pathOfFile, exception);
  471. });
  472. };
  473. /**
  474. * Instantiates a OBJ file loader plugin.
  475. * @returns the created plugin
  476. */
  477. OBJFileLoader.prototype.createPlugin = function () {
  478. return new OBJFileLoader(OBJFileLoader.currentMeshLoadOptions);
  479. };
  480. /**
  481. * If the data string can be loaded directly.
  482. *
  483. * @param data string containing the file data
  484. * @returns if the data can be loaded directly
  485. */
  486. OBJFileLoader.prototype.canDirectLoad = function (data) {
  487. return false;
  488. };
  489. /**
  490. * Imports one or more meshes from the loaded OBJ data and adds them to the scene
  491. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  492. * @param scene the scene the meshes should be added to
  493. * @param data the OBJ data to load
  494. * @param rootUrl root url to load from
  495. * @param onProgress event that fires when loading progress has occured
  496. * @param fileName Defines the name of the file to load
  497. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  498. */
  499. OBJFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  500. //get the meshes from OBJ file
  501. return this._parseSolid(meshesNames, scene, data, rootUrl).then(function (meshes) {
  502. return {
  503. meshes: meshes,
  504. particleSystems: [],
  505. skeletons: [],
  506. animationGroups: []
  507. };
  508. });
  509. };
  510. /**
  511. * Imports all objects from the loaded OBJ data and adds them to the scene
  512. * @param scene the scene the objects should be added to
  513. * @param data the OBJ data to load
  514. * @param rootUrl root url to load from
  515. * @param onProgress event that fires when loading progress has occured
  516. * @param fileName Defines the name of the file to load
  517. * @returns a promise which completes when objects have been loaded to the scene
  518. */
  519. OBJFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  520. //Get the 3D model
  521. return this.importMeshAsync(null, scene, data, rootUrl, onProgress).then(function () {
  522. // return void
  523. });
  524. };
  525. /**
  526. * Load into an asset container.
  527. * @param scene The scene to load into
  528. * @param data The data to import
  529. * @param rootUrl The root url for scene and resources
  530. * @param onProgress The callback when the load progresses
  531. * @param fileName Defines the name of the file to load
  532. * @returns The loaded asset container
  533. */
  534. OBJFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  535. return this.importMeshAsync(null, scene, data, rootUrl).then(function (result) {
  536. var container = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["AssetContainer"](scene);
  537. result.meshes.forEach(function (mesh) { return container.meshes.push(mesh); });
  538. result.meshes.forEach(function (mesh) {
  539. var material = mesh.material;
  540. if (material) {
  541. // Materials
  542. if (container.materials.indexOf(material) == -1) {
  543. container.materials.push(material);
  544. // Textures
  545. var textures = material.getActiveTextures();
  546. textures.forEach(function (t) {
  547. if (container.textures.indexOf(t) == -1) {
  548. container.textures.push(t);
  549. }
  550. });
  551. }
  552. }
  553. });
  554. return container;
  555. });
  556. };
  557. /**
  558. * Read the OBJ file and create an Array of meshes.
  559. * Each mesh contains all information given by the OBJ and the MTL file.
  560. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  561. *
  562. * @param meshesNames
  563. * @param scene Scene The scene where are displayed the data
  564. * @param data String The content of the obj file
  565. * @param rootUrl String The path to the folder
  566. * @returns Array<AbstractMesh>
  567. * @private
  568. */
  569. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  570. var _this = this;
  571. var positions = []; //values for the positions of vertices
  572. var normals = []; //Values for the normals
  573. var uvs = []; //Values for the textures
  574. var colors = [];
  575. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  576. var handledMesh; //The current mesh of meshes array
  577. var indicesForBabylon = []; //The list of indices for VertexData
  578. var wrappedPositionForBabylon = []; //The list of position in vectors
  579. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  580. var wrappedColorsForBabylon = []; // Array with all color values to match with the indices
  581. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  582. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  583. var curPositionInIndices = 0;
  584. var hasMeshes = false; //Meshes are defined in the file
  585. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  586. var unwrappedColorsForBabylon = []; // Value of colorForBabylon w/o Color4() [r,g,b,a]
  587. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  588. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  589. var triangles = []; //Indices from new triangles coming from polygons
  590. var materialNameFromObj = ""; //The name of the current material
  591. var fileToLoad = ""; //The name of the mtlFile to load
  592. var materialsFromMTLFile = new _mtlFileLoader__WEBPACK_IMPORTED_MODULE_1__["MTLFileLoader"]();
  593. var objMeshName = ""; //The name of the current obj mesh
  594. var increment = 1; //Id for meshes created by the multimaterial
  595. var isFirstMaterial = true;
  596. var grayColor = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color4"](0.5, 0.5, 0.5, 1);
  597. /**
  598. * Search for obj in the given array.
  599. * This function is called to check if a couple of data already exists in an array.
  600. *
  601. * If found, returns the index of the founded tuple index. Returns -1 if not found
  602. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  603. * @param obj Array<number>
  604. * @returns {boolean}
  605. */
  606. var isInArray = function (arr, obj) {
  607. if (!arr[obj[0]]) {
  608. arr[obj[0]] = { normals: [], idx: [] };
  609. }
  610. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  611. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  612. };
  613. var isInArrayUV = function (arr, obj) {
  614. if (!arr[obj[0]]) {
  615. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  616. }
  617. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  618. if (idx != 1 && (obj[2] === arr[obj[0]].uv[idx])) {
  619. return arr[obj[0]].idx[idx];
  620. }
  621. return -1;
  622. };
  623. /**
  624. * This function set the data for each triangle.
  625. * Data are position, normals and uvs
  626. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  627. * If the tuple already exist, add only their indice
  628. *
  629. * @param indicePositionFromObj Integer The index in positions array
  630. * @param indiceUvsFromObj Integer The index in uvs array
  631. * @param indiceNormalFromObj Integer The index in normals array
  632. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  633. * @param textureVectorFromOBJ Vector3 The value of uvs
  634. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  635. */
  636. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ, positionColorsFromOBJ) {
  637. //Check if this tuple already exists in the list of tuples
  638. var _index;
  639. if (_this._meshLoadOptions.OptimizeWithUV) {
  640. _index = isInArrayUV(tuplePosNorm, [
  641. indicePositionFromObj,
  642. indiceNormalFromObj,
  643. indiceUvsFromObj
  644. ]);
  645. }
  646. else {
  647. _index = isInArray(tuplePosNorm, [
  648. indicePositionFromObj,
  649. indiceNormalFromObj
  650. ]);
  651. }
  652. //If it not exists
  653. if (_index === -1) {
  654. //Add an new indice.
  655. //The array of indices is only an array with his length equal to the number of triangles - 1.
  656. //We add vertices data in this order
  657. indicesForBabylon.push(wrappedPositionForBabylon.length);
  658. //Push the position of vertice for Babylon
  659. //Each element is a Vector3(x,y,z)
  660. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  661. //Push the uvs for Babylon
  662. //Each element is a Vector3(u,v)
  663. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  664. //Push the normals for Babylon
  665. //Each element is a Vector3(x,y,z)
  666. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  667. if (positionColorsFromOBJ !== undefined) {
  668. //Push the colors for Babylon
  669. //Each element is a BABYLON.Color4(r,g,b,a)
  670. wrappedColorsForBabylon.push(positionColorsFromOBJ);
  671. }
  672. //Add the tuple in the comparison list
  673. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  674. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  675. if (_this._meshLoadOptions.OptimizeWithUV) {
  676. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  677. }
  678. }
  679. else {
  680. //The tuple already exists
  681. //Add the index of the already existing tuple
  682. //At this index we can get the value of position, normal, color and uvs of vertex
  683. indicesForBabylon.push(_index);
  684. }
  685. };
  686. /**
  687. * Transform Vector() and BABYLON.Color() objects into numbers in an array
  688. */
  689. var unwrapData = function () {
  690. //Every array has the same length
  691. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  692. //Push the x, y, z values of each element in the unwrapped array
  693. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  694. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  695. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  696. }
  697. if (_this._meshLoadOptions.ImportVertexColors === true) {
  698. //Push the r, g, b, a values of each element in the unwrapped array
  699. unwrappedColorsForBabylon.push(wrappedColorsForBabylon[l].r, wrappedColorsForBabylon[l].g, wrappedColorsForBabylon[l].b, wrappedColorsForBabylon[l].a);
  700. }
  701. // Reset arrays for the next new meshes
  702. wrappedPositionForBabylon = [];
  703. wrappedNormalsForBabylon = [];
  704. wrappedUvsForBabylon = [];
  705. wrappedColorsForBabylon = [];
  706. tuplePosNorm = [];
  707. curPositionInIndices = 0;
  708. };
  709. /**
  710. * Create triangles from polygons
  711. * It is important to notice that a triangle is a polygon
  712. * We get 5 patterns of face defined in OBJ File :
  713. * facePattern1 = ["1","2","3","4","5","6"]
  714. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  715. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  716. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  717. * facePattern5 = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-4/-4/-4","-5/-5/-5","-6/-6/-6"]
  718. * Each pattern is divided by the same method
  719. * @param face Array[String] The indices of elements
  720. * @param v Integer The variable to increment
  721. */
  722. var getTriangles = function (faces, v) {
  723. //Work for each element of the array
  724. for (var faceIndex = v; faceIndex < faces.length - 1; faceIndex++) {
  725. //Add on the triangle variable the indexes to obtain triangles
  726. triangles.push(faces[0], faces[faceIndex], faces[faceIndex + 1]);
  727. }
  728. //Result obtained after 2 iterations:
  729. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  730. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  731. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  732. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  733. //Pattern5 => triangle = ["-1/-1/-1","-2/-2/-2","-3/-3/-3","-1/-1/-1","-3/-3/-3","-4/-4/-4"];
  734. };
  735. /**
  736. * Create triangles and push the data for each polygon for the pattern 1
  737. * In this pattern we get vertice positions
  738. * @param face
  739. * @param v
  740. */
  741. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  742. //Get the indices of triangles for each polygon
  743. getTriangles(face, v);
  744. //For each element in the triangles array.
  745. //This var could contains 1 to an infinity of triangles
  746. for (var k = 0; k < triangles.length; k++) {
  747. // Set position indice
  748. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  749. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  750. positions[indicePositionFromObj], //Get the vectors data
  751. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero(), babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up(), //Create default vectors
  752. _this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined);
  753. }
  754. //Reset variable for the next line
  755. triangles = [];
  756. };
  757. /**
  758. * Create triangles and push the data for each polygon for the pattern 2
  759. * In this pattern we get vertice positions and uvsu
  760. * @param face
  761. * @param v
  762. */
  763. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  764. //Get the indices of triangles for each polygon
  765. getTriangles(face, v);
  766. for (var k = 0; k < triangles.length; k++) {
  767. //triangle[k] = "1/1"
  768. //Split the data for getting position and uv
  769. var point = triangles[k].split("/"); // ["1", "1"]
  770. //Set position indice
  771. var indicePositionFromObj = parseInt(point[0]) - 1;
  772. //Set uv indice
  773. var indiceUvsFromObj = parseInt(point[1]) - 1;
  774. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  775. positions[indicePositionFromObj], //Get the values for each element
  776. uvs[indiceUvsFromObj], babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Up(), //Default value for normals
  777. _this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined);
  778. }
  779. //Reset variable for the next line
  780. triangles = [];
  781. };
  782. /**
  783. * Create triangles and push the data for each polygon for the pattern 3
  784. * In this pattern we get vertice positions, uvs and normals
  785. * @param face
  786. * @param v
  787. */
  788. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  789. //Get the indices of triangles for each polygon
  790. getTriangles(face, v);
  791. for (var k = 0; k < triangles.length; k++) {
  792. //triangle[k] = "1/1/1"
  793. //Split the data for getting position, uv, and normals
  794. var point = triangles[k].split("/"); // ["1", "1", "1"]
  795. // Set position indice
  796. var indicePositionFromObj = parseInt(point[0]) - 1;
  797. // Set uv indice
  798. var indiceUvsFromObj = parseInt(point[1]) - 1;
  799. // Set normal indice
  800. var indiceNormalFromObj = parseInt(point[2]) - 1;
  801. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  802. );
  803. }
  804. //Reset variable for the next line
  805. triangles = [];
  806. };
  807. /**
  808. * Create triangles and push the data for each polygon for the pattern 4
  809. * In this pattern we get vertice positions and normals
  810. * @param face
  811. * @param v
  812. */
  813. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  814. getTriangles(face, v);
  815. for (var k = 0; k < triangles.length; k++) {
  816. //triangle[k] = "1//1"
  817. //Split the data for getting position and normals
  818. var point = triangles[k].split("//"); // ["1", "1"]
  819. // We check indices, and normals
  820. var indicePositionFromObj = parseInt(point[0]) - 1;
  821. var indiceNormalFromObj = parseInt(point[1]) - 1;
  822. setData(indicePositionFromObj, 1, //Default value for uv
  823. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  824. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].Zero(), normals[indiceNormalFromObj], _this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined);
  825. }
  826. //Reset variable for the next line
  827. triangles = [];
  828. };
  829. /**
  830. * Create triangles and push the data for each polygon for the pattern 3
  831. * In this pattern we get vertice positions, uvs and normals
  832. * @param face
  833. * @param v
  834. */
  835. var setDataForCurrentFaceWithPattern5 = function (face, v) {
  836. //Get the indices of triangles for each polygon
  837. getTriangles(face, v);
  838. for (var k = 0; k < triangles.length; k++) {
  839. //triangle[k] = "-1/-1/-1"
  840. //Split the data for getting position, uv, and normals
  841. var point = triangles[k].split("/"); // ["-1", "-1", "-1"]
  842. // Set position indice
  843. var indicePositionFromObj = positions.length + parseInt(point[0]);
  844. // Set uv indice
  845. var indiceUvsFromObj = uvs.length + parseInt(point[1]);
  846. // Set normal indice
  847. var indiceNormalFromObj = normals.length + parseInt(point[2]);
  848. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj], //Set the vector for each component
  849. _this._meshLoadOptions.ImportVertexColors === true ? colors[indicePositionFromObj] : undefined);
  850. }
  851. //Reset variable for the next line
  852. triangles = [];
  853. };
  854. var addPreviousObjMesh = function () {
  855. //Check if it is not the first mesh. Otherwise we don't have data.
  856. if (meshesFromObj.length > 0) {
  857. //Get the previous mesh for applying the data about the faces
  858. //=> in obj file, faces definition append after the name of the mesh
  859. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  860. //Set the data into Array for the mesh
  861. unwrapData();
  862. // Reverse tab. Otherwise face are displayed in the wrong sens
  863. indicesForBabylon.reverse();
  864. //Set the information for the mesh
  865. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  866. handledMesh.indices = indicesForBabylon.slice();
  867. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  868. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  869. handledMesh.uvs = unwrappedUVForBabylon.slice();
  870. if (_this._meshLoadOptions.ImportVertexColors === true) {
  871. handledMesh.colors = unwrappedColorsForBabylon.slice();
  872. }
  873. //Reset the array for the next mesh
  874. indicesForBabylon = [];
  875. unwrappedPositionsForBabylon = [];
  876. unwrappedColorsForBabylon = [];
  877. unwrappedNormalsForBabylon = [];
  878. unwrappedUVForBabylon = [];
  879. }
  880. };
  881. //Main function
  882. //Split the file into lines
  883. var lines = data.split('\n');
  884. //Look at each line
  885. for (var i = 0; i < lines.length; i++) {
  886. var line = lines[i].trim().replace(/\s\s/g, " ");
  887. var result;
  888. //Comment or newLine
  889. if (line.length === 0 || line.charAt(0) === '#') {
  890. continue;
  891. //Get information about one position possible for the vertices
  892. }
  893. else if (this.vertexPattern.test(line)) {
  894. result = line.match(/[^ ]+/g); // match will return non-null due to passing regex pattern
  895. // Value of result with line: "v 1.0 2.0 3.0"
  896. // ["v", "1.0", "2.0", "3.0"]
  897. // Create a Vector3 with the position x, y, z
  898. positions.push(new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  899. if (this._meshLoadOptions.ImportVertexColors === true) {
  900. if (result.length >= 7) {
  901. // TODO: if these numbers are > 1 we can use Color4.FromInts(r,g,b,a)
  902. 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])));
  903. }
  904. else {
  905. // TODO: maybe push NULL and if all are NULL to skip (and remove grayColor var).
  906. colors.push(grayColor);
  907. }
  908. }
  909. }
  910. else if ((result = this.normalPattern.exec(line)) !== null) {
  911. //Create a Vector3 with the normals x, y, z
  912. //Value of result
  913. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  914. //Add the Vector in the list of normals
  915. normals.push(new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  916. }
  917. else if ((result = this.uvPattern.exec(line)) !== null) {
  918. //Create a Vector2 with the normals u, v
  919. //Value of result
  920. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  921. //Add the Vector in the list of uvs
  922. uvs.push(new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](parseFloat(result[1]) * OBJFileLoader.UV_SCALING.x, parseFloat(result[2]) * OBJFileLoader.UV_SCALING.y));
  923. //Identify patterns of faces
  924. //Face could be defined in different type of pattern
  925. }
  926. else if ((result = this.facePattern3.exec(line)) !== null) {
  927. //Value of result:
  928. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  929. //Set the data for this face
  930. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  931. 1);
  932. }
  933. else if ((result = this.facePattern4.exec(line)) !== null) {
  934. //Value of result:
  935. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  936. //Set the data for this face
  937. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  938. 1);
  939. }
  940. else if ((result = this.facePattern5.exec(line)) !== null) {
  941. //Value of result:
  942. //["f -1/-1/-1 -2/-2/-2 -3/-3/-3", "-1/-1/-1 -2/-2/-2 -3/-3/-3"...]
  943. //Set the data for this face
  944. setDataForCurrentFaceWithPattern5(result[1].trim().split(" "), // ["-1/-1/-1", "-2/-2/-2", "-3/-3/-3"]
  945. 1);
  946. }
  947. else if ((result = this.facePattern2.exec(line)) !== null) {
  948. //Value of result:
  949. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  950. //Set the data for this face
  951. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  952. 1);
  953. }
  954. else if ((result = this.facePattern1.exec(line)) !== null) {
  955. //Value of result
  956. //["f 1 2 3", "1 2 3"...]
  957. //Set the data for this face
  958. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  959. 1);
  960. //Define a mesh or an object
  961. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  962. }
  963. else if (this.group.test(line) || this.obj.test(line)) {
  964. //Create a new mesh corresponding to the name of the group.
  965. //Definition of the mesh
  966. var objMesh = {
  967. name: line.substring(2).trim(),
  968. indices: undefined,
  969. positions: undefined,
  970. normals: undefined,
  971. uvs: undefined,
  972. colors: undefined,
  973. materialName: ""
  974. };
  975. addPreviousObjMesh();
  976. //Push the last mesh created with only the name
  977. meshesFromObj.push(objMesh);
  978. //Set this variable to indicate that now meshesFromObj has objects defined inside
  979. hasMeshes = true;
  980. isFirstMaterial = true;
  981. increment = 1;
  982. //Keyword for applying a material
  983. }
  984. else if (this.usemtl.test(line)) {
  985. //Get the name of the material
  986. materialNameFromObj = line.substring(7).trim();
  987. //If this new material is in the same mesh
  988. if (!isFirstMaterial || !hasMeshes) {
  989. //Set the data for the previous mesh
  990. addPreviousObjMesh();
  991. //Create a new mesh
  992. var objMesh =
  993. //Set the name of the current obj mesh
  994. {
  995. name: (objMeshName || "mesh") + "_mm" + increment.toString(),
  996. indices: undefined,
  997. positions: undefined,
  998. normals: undefined,
  999. uvs: undefined,
  1000. colors: undefined,
  1001. materialName: materialNameFromObj
  1002. };
  1003. increment++;
  1004. //If meshes are already defined
  1005. meshesFromObj.push(objMesh);
  1006. hasMeshes = true;
  1007. }
  1008. //Set the material name if the previous line define a mesh
  1009. if (hasMeshes && isFirstMaterial) {
  1010. //Set the material name to the previous mesh (1 material per mesh)
  1011. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  1012. isFirstMaterial = false;
  1013. }
  1014. //Keyword for loading the mtl file
  1015. }
  1016. else if (this.mtllib.test(line)) {
  1017. //Get the name of mtl file
  1018. fileToLoad = line.substring(7).trim();
  1019. //Apply smoothing
  1020. }
  1021. else if (this.smooth.test(line)) {
  1022. // smooth shading => apply smoothing
  1023. //Today I don't know it work with babylon and with obj.
  1024. //With the obj file an integer is set
  1025. }
  1026. else {
  1027. //If there is another possibility
  1028. console.log("Unhandled expression at line : " + line);
  1029. }
  1030. }
  1031. //At the end of the file, add the last mesh into the meshesFromObj array
  1032. if (hasMeshes) {
  1033. //Set the data for the last mesh
  1034. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  1035. //Reverse indices for displaying faces in the good sense
  1036. indicesForBabylon.reverse();
  1037. //Get the good array
  1038. unwrapData();
  1039. //Set array
  1040. handledMesh.indices = indicesForBabylon;
  1041. handledMesh.positions = unwrappedPositionsForBabylon;
  1042. handledMesh.normals = unwrappedNormalsForBabylon;
  1043. handledMesh.uvs = unwrappedUVForBabylon;
  1044. if (this._meshLoadOptions.ImportVertexColors === true) {
  1045. handledMesh.colors = unwrappedColorsForBabylon;
  1046. }
  1047. }
  1048. //If any o or g keyword found, create a mesh with a random id
  1049. if (!hasMeshes) {
  1050. // reverse tab of indices
  1051. indicesForBabylon.reverse();
  1052. //Get positions normals uvs
  1053. unwrapData();
  1054. //Set data for one mesh
  1055. meshesFromObj.push({
  1056. name: babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Geometry"].RandomId(),
  1057. indices: indicesForBabylon,
  1058. positions: unwrappedPositionsForBabylon,
  1059. colors: unwrappedColorsForBabylon,
  1060. normals: unwrappedNormalsForBabylon,
  1061. uvs: unwrappedUVForBabylon,
  1062. materialName: materialNameFromObj
  1063. });
  1064. }
  1065. //Create a Mesh list
  1066. var babylonMeshesArray = []; //The mesh for babylon
  1067. var materialToUse = new Array();
  1068. //Set data for each mesh
  1069. for (var j = 0; j < meshesFromObj.length; j++) {
  1070. //check meshesNames (stlFileLoader)
  1071. if (meshesNames && meshesFromObj[j].name) {
  1072. if (meshesNames instanceof Array) {
  1073. if (meshesNames.indexOf(meshesFromObj[j].name) === -1) {
  1074. continue;
  1075. }
  1076. }
  1077. else {
  1078. if (meshesFromObj[j].name !== meshesNames) {
  1079. continue;
  1080. }
  1081. }
  1082. }
  1083. //Get the current mesh
  1084. //Set the data with VertexBuffer for each mesh
  1085. handledMesh = meshesFromObj[j];
  1086. //Create a Mesh with the name of the obj mesh
  1087. var babylonMesh = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Mesh"](meshesFromObj[j].name, scene);
  1088. //Push the name of the material to an array
  1089. //This is indispensable for the importMesh function
  1090. materialToUse.push(meshesFromObj[j].materialName);
  1091. var vertexData = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexData"](); //The container for the values
  1092. //Set the data for the babylonMesh
  1093. vertexData.uvs = handledMesh.uvs;
  1094. vertexData.indices = handledMesh.indices;
  1095. vertexData.positions = handledMesh.positions;
  1096. if (this._meshLoadOptions.ComputeNormals === true) {
  1097. var normals_1 = new Array();
  1098. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexData"].ComputeNormals(handledMesh.positions, handledMesh.indices, normals_1);
  1099. vertexData.normals = normals_1;
  1100. }
  1101. else {
  1102. vertexData.normals = handledMesh.normals;
  1103. }
  1104. if (this._meshLoadOptions.ImportVertexColors === true) {
  1105. vertexData.colors = handledMesh.colors;
  1106. }
  1107. //Set the data from the VertexBuffer to the current Mesh
  1108. vertexData.applyToMesh(babylonMesh);
  1109. if (this._meshLoadOptions.InvertY) {
  1110. babylonMesh.scaling.y *= -1;
  1111. }
  1112. //Push the mesh into an array
  1113. babylonMeshesArray.push(babylonMesh);
  1114. }
  1115. var mtlPromises = [];
  1116. //load the materials
  1117. //Check if we have a file to load
  1118. if (fileToLoad !== "" && this._meshLoadOptions.SkipMaterials === false) {
  1119. //Load the file synchronously
  1120. mtlPromises.push(new Promise(function (resolve, reject) {
  1121. _this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  1122. try {
  1123. //Create materials thanks MTLLoader function
  1124. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  1125. //Look at each material loaded in the mtl file
  1126. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  1127. //Three variables to get all meshes with the same material
  1128. var startIndex = 0;
  1129. var _indices = [];
  1130. var _index;
  1131. //The material from MTL file is used in the meshes loaded
  1132. //Push the indice in an array
  1133. //Check if the material is not used for another mesh
  1134. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  1135. _indices.push(_index);
  1136. startIndex = _index + 1;
  1137. }
  1138. //If the material is not used dispose it
  1139. if (_index === -1 && _indices.length === 0) {
  1140. //If the material is not needed, remove it
  1141. materialsFromMTLFile.materials[n].dispose();
  1142. }
  1143. else {
  1144. for (var o = 0; o < _indices.length; o++) {
  1145. //Apply the material to the Mesh for each mesh with the material
  1146. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  1147. }
  1148. }
  1149. }
  1150. resolve();
  1151. }
  1152. catch (e) {
  1153. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Error processing MTL file: '" + fileToLoad + "'");
  1154. if (_this._meshLoadOptions.MaterialLoadingFailsSilently) {
  1155. resolve();
  1156. }
  1157. else {
  1158. reject(e);
  1159. }
  1160. }
  1161. }, function (pathOfFile, exception) {
  1162. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Error downloading MTL file: '" + fileToLoad + "'");
  1163. if (_this._meshLoadOptions.MaterialLoadingFailsSilently) {
  1164. resolve();
  1165. }
  1166. else {
  1167. reject(exception);
  1168. }
  1169. });
  1170. }));
  1171. }
  1172. //Return an array with all Mesh
  1173. return Promise.all(mtlPromises).then(function () {
  1174. return babylonMeshesArray;
  1175. });
  1176. };
  1177. /**
  1178. * Defines if UVs are optimized by default during load.
  1179. */
  1180. OBJFileLoader.OPTIMIZE_WITH_UV = true;
  1181. /**
  1182. * Invert model on y-axis (does a model scaling inversion)
  1183. */
  1184. OBJFileLoader.INVERT_Y = false;
  1185. /**
  1186. * Include in meshes the vertex colors available in some OBJ files. This is not part of OBJ standard.
  1187. */
  1188. OBJFileLoader.IMPORT_VERTEX_COLORS = false;
  1189. /**
  1190. * Compute the normals for the model, even if normals are present in the file.
  1191. */
  1192. OBJFileLoader.COMPUTE_NORMALS = false;
  1193. /**
  1194. * Defines custom scaling of UV coordinates of loaded meshes.
  1195. */
  1196. OBJFileLoader.UV_SCALING = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](1, 1);
  1197. /**
  1198. * Skip loading the materials even if defined in the OBJ file (materials are ignored).
  1199. */
  1200. OBJFileLoader.SKIP_MATERIALS = false;
  1201. /**
  1202. * When a material fails to load OBJ loader will silently fail and onSuccess() callback will be triggered.
  1203. *
  1204. * Defaults to true for backwards compatibility.
  1205. */
  1206. OBJFileLoader.MATERIAL_LOADING_FAILS_SILENTLY = true;
  1207. return OBJFileLoader;
  1208. }());
  1209. if (babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["SceneLoader"]) {
  1210. //Add this loader into the register plugin
  1211. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["SceneLoader"].RegisterPlugin(new OBJFileLoader());
  1212. }
  1213. /***/ }),
  1214. /***/ "./legacy/legacy-objFileLoader.ts":
  1215. /*!****************************************!*\
  1216. !*** ./legacy/legacy-objFileLoader.ts ***!
  1217. \****************************************/
  1218. /*! exports provided: MTLFileLoader, OBJFileLoader */
  1219. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  1220. "use strict";
  1221. __webpack_require__.r(__webpack_exports__);
  1222. /* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _OBJ__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OBJ */ "./OBJ/index.ts");
  1223. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "MTLFileLoader", function() { return _OBJ__WEBPACK_IMPORTED_MODULE_0__["MTLFileLoader"]; });
  1224. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OBJFileLoader", function() { return _OBJ__WEBPACK_IMPORTED_MODULE_0__["OBJFileLoader"]; });
  1225. /**
  1226. * This is the entry point for the UMD module.
  1227. * The entry point for a future ESM package should be index.ts
  1228. */
  1229. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  1230. if (typeof globalObject !== "undefined") {
  1231. for (var key in _OBJ__WEBPACK_IMPORTED_MODULE_0__) {
  1232. globalObject.BABYLON[key] = _OBJ__WEBPACK_IMPORTED_MODULE_0__[key];
  1233. }
  1234. }
  1235. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
  1236. /***/ }),
  1237. /***/ "babylonjs/Misc/tools":
  1238. /*!****************************************************************************************************!*\
  1239. !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***!
  1240. \****************************************************************************************************/
  1241. /*! no static exports found */
  1242. /***/ (function(module, exports) {
  1243. module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs_Misc_tools__;
  1244. /***/ })
  1245. /******/ });
  1246. });
  1247. //# sourceMappingURL=babylon.objFileLoader.js.map