babylon.objFileLoader.js 59 KB

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