babylonjs.serializers.js 246 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660
  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-serializers", ["babylonjs"], factory);
  6. else if(typeof exports === 'object')
  7. exports["babylonjs-serializers"] = factory(require("babylonjs"));
  8. else
  9. root["SERIALIZERS"] = factory(root["BABYLON"]);
  10. })((typeof self !== "undefined" ? self : typeof global !== "undefined" ? global : this), function(__WEBPACK_EXTERNAL_MODULE_babylonjs_Maths_math__) {
  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.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: OBJExport */
  126. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  127. "use strict";
  128. __webpack_require__.r(__webpack_exports__);
  129. /* harmony import */ var _objSerializer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./objSerializer */ "./OBJ/objSerializer.ts");
  130. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OBJExport", function() { return _objSerializer__WEBPACK_IMPORTED_MODULE_0__["OBJExport"]; });
  131. /***/ }),
  132. /***/ "./OBJ/objSerializer.ts":
  133. /*!******************************!*\
  134. !*** ./OBJ/objSerializer.ts ***!
  135. \******************************/
  136. /*! exports provided: OBJExport */
  137. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  138. "use strict";
  139. __webpack_require__.r(__webpack_exports__);
  140. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OBJExport", function() { return OBJExport; });
  141. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Maths/math");
  142. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__);
  143. /**
  144. * Class for generating OBJ data from a Babylon scene.
  145. */
  146. var OBJExport = /** @class */ (function () {
  147. function OBJExport() {
  148. }
  149. /**
  150. * Exports the geometry of a Mesh array in .OBJ file format (text)
  151. * @param mesh defines the list of meshes to serialize
  152. * @param materials defines if materials should be exported
  153. * @param matlibname defines the name of the associated mtl file
  154. * @param globalposition defines if the exported positions are globals or local to the exported mesh
  155. * @returns the OBJ content
  156. */
  157. OBJExport.OBJ = function (mesh, materials, matlibname, globalposition) {
  158. var output = [];
  159. var v = 1;
  160. if (materials) {
  161. if (!matlibname) {
  162. matlibname = 'mat';
  163. }
  164. output.push("mtllib " + matlibname + ".mtl");
  165. }
  166. for (var j = 0; j < mesh.length; j++) {
  167. output.push("g object" + j);
  168. output.push("o object_" + j);
  169. //Uses the position of the item in the scene, to the file (this back to normal in the end)
  170. var lastMatrix = null;
  171. if (globalposition) {
  172. var newMatrix = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(mesh[j].position.x, mesh[j].position.y, mesh[j].position.z);
  173. lastMatrix = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Matrix"].Translation(-(mesh[j].position.x), -(mesh[j].position.y), -(mesh[j].position.z));
  174. mesh[j].bakeTransformIntoVertices(newMatrix);
  175. }
  176. //TODO: submeshes (groups)
  177. //TODO: smoothing groups (s 1, s off);
  178. if (materials) {
  179. var mat = mesh[j].material;
  180. if (mat) {
  181. output.push("usemtl " + mat.id);
  182. }
  183. }
  184. var g = mesh[j].geometry;
  185. if (!g) {
  186. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("No geometry is present on the mesh");
  187. continue;
  188. }
  189. var trunkVerts = g.getVerticesData('position');
  190. var trunkNormals = g.getVerticesData('normal');
  191. var trunkUV = g.getVerticesData('uv');
  192. var trunkFaces = g.getIndices();
  193. var curV = 0;
  194. if (!trunkVerts || !trunkFaces) {
  195. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("There are no position vertices or indices on the mesh!");
  196. continue;
  197. }
  198. for (var i = 0; i < trunkVerts.length; i += 3) {
  199. output.push("v " + trunkVerts[i] + " " + trunkVerts[i + 1] + " " + trunkVerts[i + 2]);
  200. curV++;
  201. }
  202. if (trunkNormals != null) {
  203. for (i = 0; i < trunkNormals.length; i += 3) {
  204. output.push("vn " + trunkNormals[i] + " " + trunkNormals[i + 1] + " " + trunkNormals[i + 2]);
  205. }
  206. }
  207. if (trunkUV != null) {
  208. for (i = 0; i < trunkUV.length; i += 2) {
  209. output.push("vt " + trunkUV[i] + " " + trunkUV[i + 1]);
  210. }
  211. }
  212. for (i = 0; i < trunkFaces.length; i += 3) {
  213. var indices = [String(trunkFaces[i + 2] + v), String(trunkFaces[i + 1] + v), String(trunkFaces[i] + v)];
  214. var blanks = ["", "", ""];
  215. var facePositions = indices;
  216. var faceUVs = trunkUV != null ? indices : blanks;
  217. var faceNormals = trunkNormals != null ? indices : blanks;
  218. output.push("f " + facePositions[0] + "/" + faceUVs[0] + "/" + faceNormals[0] +
  219. " " + facePositions[1] + "/" + faceUVs[1] + "/" + faceNormals[1] +
  220. " " + facePositions[2] + "/" + faceUVs[2] + "/" + faceNormals[2]);
  221. }
  222. //back de previous matrix, to not change the original mesh in the scene
  223. if (globalposition && lastMatrix) {
  224. mesh[j].bakeTransformIntoVertices(lastMatrix);
  225. }
  226. v += curV;
  227. }
  228. var text = output.join("\n");
  229. return (text);
  230. };
  231. /**
  232. * Exports the material(s) of a mesh in .MTL file format (text)
  233. * @param mesh defines the mesh to extract the material from
  234. * @returns the mtl content
  235. */
  236. //TODO: Export the materials of mesh array
  237. OBJExport.MTL = function (mesh) {
  238. var output = [];
  239. var m = mesh.material;
  240. output.push("newmtl mat1");
  241. output.push(" Ns " + m.specularPower.toFixed(4));
  242. output.push(" Ni 1.5000");
  243. output.push(" d " + m.alpha.toFixed(4));
  244. output.push(" Tr 0.0000");
  245. output.push(" Tf 1.0000 1.0000 1.0000");
  246. output.push(" illum 2");
  247. output.push(" Ka " + m.ambientColor.r.toFixed(4) + " " + m.ambientColor.g.toFixed(4) + " " + m.ambientColor.b.toFixed(4));
  248. output.push(" Kd " + m.diffuseColor.r.toFixed(4) + " " + m.diffuseColor.g.toFixed(4) + " " + m.diffuseColor.b.toFixed(4));
  249. output.push(" Ks " + m.specularColor.r.toFixed(4) + " " + m.specularColor.g.toFixed(4) + " " + m.specularColor.b.toFixed(4));
  250. output.push(" Ke " + m.emissiveColor.r.toFixed(4) + " " + m.emissiveColor.g.toFixed(4) + " " + m.emissiveColor.b.toFixed(4));
  251. //TODO: uv scale, offset, wrap
  252. //TODO: UV mirrored in Blender? second UV channel? lightMap? reflection textures?
  253. var uvscale = "";
  254. if (m.ambientTexture) {
  255. output.push(" map_Ka " + uvscale + m.ambientTexture.name);
  256. }
  257. if (m.diffuseTexture) {
  258. output.push(" map_Kd " + uvscale + m.diffuseTexture.name);
  259. //TODO: alpha testing, opacity in diffuse texture alpha channel (diffuseTexture.hasAlpha -> map_d)
  260. }
  261. if (m.specularTexture) {
  262. output.push(" map_Ks " + uvscale + m.specularTexture.name);
  263. /* TODO: glossiness = specular highlight component is in alpha channel of specularTexture. (???)
  264. if (m.useGlossinessFromSpecularMapAlpha) {
  265. output.push(" map_Ns "+uvscale + m.specularTexture.name);
  266. }
  267. */
  268. }
  269. /* TODO: emissive texture not in .MAT format (???)
  270. if (m.emissiveTexture) {
  271. output.push(" map_d "+uvscale+m.emissiveTexture.name);
  272. }
  273. */
  274. if (m.bumpTexture) {
  275. output.push(" map_bump -imfchan z " + uvscale + m.bumpTexture.name);
  276. }
  277. if (m.opacityTexture) {
  278. output.push(" map_d " + uvscale + m.opacityTexture.name);
  279. }
  280. var text = output.join("\n");
  281. return (text);
  282. };
  283. return OBJExport;
  284. }());
  285. /***/ }),
  286. /***/ "./glTF/2.0/Extensions/KHR_lights_punctual.ts":
  287. /*!****************************************************!*\
  288. !*** ./glTF/2.0/Extensions/KHR_lights_punctual.ts ***!
  289. \****************************************************/
  290. /*! exports provided: KHR_lights_punctual */
  291. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  292. "use strict";
  293. __webpack_require__.r(__webpack_exports__);
  294. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KHR_lights_punctual", function() { return KHR_lights_punctual; });
  295. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Maths/math");
  296. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__);
  297. /* harmony import */ var _glTFExporter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTFExporter */ "./glTF/2.0/glTFExporter.ts");
  298. /* harmony import */ var _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../glTFUtilities */ "./glTF/2.0/glTFUtilities.ts");
  299. var NAME = "KHR_lights_punctual";
  300. var LightType;
  301. (function (LightType) {
  302. LightType["DIRECTIONAL"] = "directional";
  303. LightType["POINT"] = "point";
  304. LightType["SPOT"] = "spot";
  305. })(LightType || (LightType = {}));
  306. /**
  307. * [Specification](https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_lights_punctual/README.md)
  308. */
  309. var KHR_lights_punctual = /** @class */ (function () {
  310. /** @hidden */
  311. function KHR_lights_punctual(exporter) {
  312. /** The name of this extension. */
  313. this.name = NAME;
  314. /** Defines whether this extension is enabled. */
  315. this.enabled = true;
  316. /** Defines whether this extension is required */
  317. this.required = false;
  318. this._exporter = exporter;
  319. }
  320. /** @hidden */
  321. KHR_lights_punctual.prototype.dispose = function () {
  322. delete this._exporter;
  323. delete this._lights;
  324. };
  325. /** @hidden */
  326. KHR_lights_punctual.prototype.onExporting = function () {
  327. if (this._lights) {
  328. if (this._exporter._glTF.extensionsUsed == null) {
  329. this._exporter._glTF.extensionsUsed = [];
  330. }
  331. if (this._exporter._glTF.extensionsUsed.indexOf(NAME) === -1) {
  332. this._exporter._glTF.extensionsUsed.push(NAME);
  333. }
  334. if (this.required) {
  335. if (this._exporter._glTF.extensionsRequired == null) {
  336. this._exporter._glTF.extensionsRequired = [];
  337. }
  338. if (this._exporter._glTF.extensionsRequired.indexOf(NAME) === -1) {
  339. this._exporter._glTF.extensionsRequired.push(NAME);
  340. }
  341. }
  342. if (this._exporter._glTF.extensions == null) {
  343. this._exporter._glTF.extensions = {};
  344. }
  345. this._exporter._glTF.extensions[NAME] = this._lights;
  346. }
  347. };
  348. /**
  349. * Define this method to modify the default behavior when exporting a node
  350. * @param context The context when exporting the node
  351. * @param node glTF node
  352. * @param babylonNode BabylonJS node
  353. * @returns nullable INode promise
  354. */
  355. KHR_lights_punctual.prototype.postExportNodeAsync = function (context, node, babylonNode) {
  356. var _this = this;
  357. return new Promise(function (resolve, reject) {
  358. if (babylonNode instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["ShadowLight"]) {
  359. var babylonLight = babylonNode;
  360. var light = void 0;
  361. var lightType = (babylonLight.getTypeID() == babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Light"].LIGHTTYPEID_POINTLIGHT ? LightType.POINT : (babylonLight.getTypeID() == babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Light"].LIGHTTYPEID_DIRECTIONALLIGHT ? LightType.DIRECTIONAL : (babylonLight.getTypeID() == babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Light"].LIGHTTYPEID_SPOTLIGHT ? LightType.SPOT : null)));
  362. if (lightType == null) {
  363. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn(context + ": Light " + babylonLight.name + " is not supported in " + NAME);
  364. }
  365. else {
  366. var lightPosition = babylonLight.position.clone();
  367. if (!lightPosition.equals(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Zero())) {
  368. if (_this._exporter._convertToRightHandedSystem) {
  369. _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._GetRightHandedPositionVector3FromRef(lightPosition);
  370. }
  371. node.translation = lightPosition.asArray();
  372. }
  373. if (lightType !== LightType.POINT) {
  374. var localAxis = babylonLight.direction;
  375. var yaw = -Math.atan2(localAxis.z, localAxis.x) + Math.PI / 2;
  376. var len = Math.sqrt(localAxis.x * localAxis.x + localAxis.z * localAxis.z);
  377. var pitch = -Math.atan2(localAxis.y, len);
  378. var lightRotationQuaternion = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].RotationYawPitchRoll(yaw, pitch, 0);
  379. if (_this._exporter._convertToRightHandedSystem) {
  380. _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._GetRightHandedQuaternionFromRef(lightRotationQuaternion);
  381. }
  382. if (!lightRotationQuaternion.equals(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Identity())) {
  383. node.rotation = lightRotationQuaternion.asArray();
  384. }
  385. }
  386. if (babylonLight.falloffType !== babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Light"].FALLOFF_GLTF) {
  387. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Logger"].Warn(context + ": Light falloff for " + babylonLight.name + " does not match the " + NAME + " specification!");
  388. }
  389. light = {
  390. type: lightType
  391. };
  392. if (!babylonLight.diffuse.equals(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].White())) {
  393. light.color = babylonLight.diffuse.asArray();
  394. }
  395. if (babylonLight.intensity !== 1.0) {
  396. light.intensity = babylonLight.intensity;
  397. }
  398. if (babylonLight.range !== Number.MAX_VALUE) {
  399. light.range = babylonLight.range;
  400. }
  401. if (lightType === LightType.SPOT) {
  402. var babylonSpotLight = babylonLight;
  403. if (babylonSpotLight.angle !== Math.PI / 2.0) {
  404. if (light.spot == null) {
  405. light.spot = {};
  406. }
  407. light.spot.outerConeAngle = babylonSpotLight.angle / 2.0;
  408. }
  409. if (babylonSpotLight.innerAngle !== 0) {
  410. if (light.spot == null) {
  411. light.spot = {};
  412. }
  413. light.spot.innerConeAngle = babylonSpotLight.innerAngle / 2.0;
  414. }
  415. }
  416. if (_this._lights == null) {
  417. _this._lights = {
  418. lights: []
  419. };
  420. }
  421. _this._lights.lights.push(light);
  422. if (node.extensions == null) {
  423. node.extensions = {};
  424. }
  425. var lightReference = {
  426. light: _this._lights.lights.length - 1
  427. };
  428. node.extensions[NAME] = lightReference;
  429. }
  430. }
  431. resolve(node);
  432. });
  433. };
  434. return KHR_lights_punctual;
  435. }());
  436. _glTFExporter__WEBPACK_IMPORTED_MODULE_1__["_Exporter"].RegisterExtension(NAME, function (exporter) { return new KHR_lights_punctual(exporter); });
  437. /***/ }),
  438. /***/ "./glTF/2.0/Extensions/KHR_texture_transform.ts":
  439. /*!******************************************************!*\
  440. !*** ./glTF/2.0/Extensions/KHR_texture_transform.ts ***!
  441. \******************************************************/
  442. /*! exports provided: KHR_texture_transform */
  443. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  444. "use strict";
  445. __webpack_require__.r(__webpack_exports__);
  446. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "KHR_texture_transform", function() { return KHR_texture_transform; });
  447. /* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Misc/tools */ "babylonjs/Maths/math");
  448. /* harmony import */ var babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_0__);
  449. /* harmony import */ var _glTFExporter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTFExporter */ "./glTF/2.0/glTFExporter.ts");
  450. /* harmony import */ var _shaders_textureTransform_fragment__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../shaders/textureTransform.fragment */ "./glTF/2.0/shaders/textureTransform.fragment.ts");
  451. var NAME = "KHR_texture_transform";
  452. /**
  453. * @hidden
  454. */
  455. var KHR_texture_transform = /** @class */ (function () {
  456. function KHR_texture_transform(exporter) {
  457. /** Name of this extension */
  458. this.name = NAME;
  459. /** Defines whether this extension is enabled */
  460. this.enabled = true;
  461. /** Defines whether this extension is required */
  462. this.required = false;
  463. this._exporter = exporter;
  464. }
  465. KHR_texture_transform.prototype.dispose = function () {
  466. delete this._exporter;
  467. };
  468. KHR_texture_transform.prototype.preExportTextureAsync = function (context, babylonTexture, mimeType) {
  469. var _this = this;
  470. return new Promise(function (resolve, reject) {
  471. var scene = babylonTexture.getScene();
  472. if (!scene) {
  473. reject(context + ": \"scene\" is not defined for Babylon texture " + babylonTexture.name + "!");
  474. return;
  475. }
  476. // TODO: this doesn't take into account rotation center values
  477. var texture_transform_extension = {};
  478. if (babylonTexture.uOffset !== 0 || babylonTexture.vOffset !== 0) {
  479. texture_transform_extension.offset = [babylonTexture.uOffset, babylonTexture.vOffset];
  480. }
  481. if (babylonTexture.uScale !== 1 || babylonTexture.vScale !== 1) {
  482. texture_transform_extension.scale = [babylonTexture.uScale, babylonTexture.vScale];
  483. }
  484. if (babylonTexture.wAng !== 0) {
  485. texture_transform_extension.rotation = babylonTexture.wAng;
  486. }
  487. if (!Object.keys(texture_transform_extension).length) {
  488. resolve(babylonTexture);
  489. return;
  490. }
  491. return _this._textureTransformTextureAsync(babylonTexture, scene);
  492. });
  493. };
  494. /**
  495. * Transform the babylon texture by the offset, rotation and scale parameters using a procedural texture
  496. * @param babylonTexture
  497. * @param offset
  498. * @param rotation
  499. * @param scale
  500. * @param scene
  501. */
  502. KHR_texture_transform.prototype._textureTransformTextureAsync = function (babylonTexture, scene) {
  503. return new Promise(function (resolve) {
  504. var proceduralTexture = new babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["ProceduralTexture"]("" + babylonTexture.name, babylonTexture.getSize(), "textureTransform", scene);
  505. if (!proceduralTexture) {
  506. babylonjs_Misc_tools__WEBPACK_IMPORTED_MODULE_0__["Tools"].Log("Cannot create procedural texture for " + babylonTexture.name + "!");
  507. resolve(babylonTexture);
  508. }
  509. proceduralTexture.setTexture("textureSampler", babylonTexture);
  510. proceduralTexture.setMatrix("textureTransformMat", babylonTexture.getTextureMatrix());
  511. // isReady trigger creation of effect if it doesnt exist yet
  512. if (proceduralTexture.isReady()) {
  513. proceduralTexture.render();
  514. resolve(proceduralTexture);
  515. }
  516. else {
  517. proceduralTexture.getEffect().executeWhenCompiled(function () {
  518. proceduralTexture.render();
  519. resolve(proceduralTexture);
  520. });
  521. }
  522. });
  523. };
  524. return KHR_texture_transform;
  525. }());
  526. _glTFExporter__WEBPACK_IMPORTED_MODULE_1__["_Exporter"].RegisterExtension(NAME, function (exporter) { return new KHR_texture_transform(exporter); });
  527. /***/ }),
  528. /***/ "./glTF/2.0/Extensions/index.ts":
  529. /*!**************************************!*\
  530. !*** ./glTF/2.0/Extensions/index.ts ***!
  531. \**************************************/
  532. /*! exports provided: KHR_texture_transform, KHR_lights_punctual */
  533. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  534. "use strict";
  535. __webpack_require__.r(__webpack_exports__);
  536. /* harmony import */ var _KHR_texture_transform__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./KHR_texture_transform */ "./glTF/2.0/Extensions/KHR_texture_transform.ts");
  537. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_texture_transform", function() { return _KHR_texture_transform__WEBPACK_IMPORTED_MODULE_0__["KHR_texture_transform"]; });
  538. /* harmony import */ var _KHR_lights_punctual__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./KHR_lights_punctual */ "./glTF/2.0/Extensions/KHR_lights_punctual.ts");
  539. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_lights_punctual", function() { return _KHR_lights_punctual__WEBPACK_IMPORTED_MODULE_1__["KHR_lights_punctual"]; });
  540. /***/ }),
  541. /***/ "./glTF/2.0/glTFAnimation.ts":
  542. /*!***********************************!*\
  543. !*** ./glTF/2.0/glTFAnimation.ts ***!
  544. \***********************************/
  545. /*! exports provided: _GLTFAnimation */
  546. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  547. "use strict";
  548. __webpack_require__.r(__webpack_exports__);
  549. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_GLTFAnimation", function() { return _GLTFAnimation; });
  550. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Maths/math");
  551. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__);
  552. /* harmony import */ var _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./glTFUtilities */ "./glTF/2.0/glTFUtilities.ts");
  553. /**
  554. * @hidden
  555. * Enum for handling in tangent and out tangent.
  556. */
  557. var _TangentType;
  558. (function (_TangentType) {
  559. /**
  560. * Specifies that input tangents are used.
  561. */
  562. _TangentType[_TangentType["INTANGENT"] = 0] = "INTANGENT";
  563. /**
  564. * Specifies that output tangents are used.
  565. */
  566. _TangentType[_TangentType["OUTTANGENT"] = 1] = "OUTTANGENT";
  567. })(_TangentType || (_TangentType = {}));
  568. /**
  569. * @hidden
  570. * Utility class for generating glTF animation data from BabylonJS.
  571. */
  572. var _GLTFAnimation = /** @class */ (function () {
  573. function _GLTFAnimation() {
  574. }
  575. /**
  576. * @ignore
  577. *
  578. * Creates glTF channel animation from BabylonJS animation.
  579. * @param babylonTransformNode - BabylonJS mesh.
  580. * @param animation - animation.
  581. * @param animationChannelTargetPath - The target animation channel.
  582. * @param convertToRightHandedSystem - Specifies if the values should be converted to right-handed.
  583. * @param useQuaternion - Specifies if quaternions are used.
  584. * @returns nullable IAnimationData
  585. */
  586. _GLTFAnimation._CreateNodeAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  587. var inputs = [];
  588. var outputs = [];
  589. var keyFrames = animation.getKeys();
  590. var minMaxKeyFrames = _GLTFAnimation.calculateMinMaxKeyFrames(keyFrames);
  591. var interpolationOrBake = _GLTFAnimation._DeduceInterpolation(keyFrames, animationChannelTargetPath, useQuaternion);
  592. var frameDelta = minMaxKeyFrames.max - minMaxKeyFrames.min;
  593. var interpolation = interpolationOrBake.interpolationType;
  594. var shouldBakeAnimation = interpolationOrBake.shouldBakeAnimation;
  595. if (shouldBakeAnimation) {
  596. _GLTFAnimation._CreateBakedAnimation(babylonTransformNode, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  597. }
  598. else {
  599. if (interpolation === "LINEAR" /* LINEAR */ || interpolation === "STEP" /* STEP */) {
  600. _GLTFAnimation._CreateLinearOrStepAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  601. }
  602. else if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  603. _GLTFAnimation._CreateCubicSplineAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  604. }
  605. else {
  606. _GLTFAnimation._CreateBakedAnimation(babylonTransformNode, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  607. }
  608. }
  609. if (inputs.length && outputs.length) {
  610. var result = {
  611. inputs: inputs,
  612. outputs: outputs,
  613. samplerInterpolation: interpolation,
  614. inputsMin: shouldBakeAnimation ? minMaxKeyFrames.min : babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].FloatRound(minMaxKeyFrames.min / animation.framePerSecond),
  615. inputsMax: shouldBakeAnimation ? minMaxKeyFrames.max : babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].FloatRound(minMaxKeyFrames.max / animation.framePerSecond)
  616. };
  617. return result;
  618. }
  619. return null;
  620. };
  621. _GLTFAnimation._DeduceAnimationInfo = function (animation) {
  622. var animationChannelTargetPath = null;
  623. var dataAccessorType = "VEC3" /* VEC3 */;
  624. var useQuaternion = false;
  625. var property = animation.targetProperty.split('.');
  626. switch (property[0]) {
  627. case 'scaling': {
  628. animationChannelTargetPath = "scale" /* SCALE */;
  629. break;
  630. }
  631. case 'position': {
  632. animationChannelTargetPath = "translation" /* TRANSLATION */;
  633. break;
  634. }
  635. case 'rotation': {
  636. dataAccessorType = "VEC4" /* VEC4 */;
  637. animationChannelTargetPath = "rotation" /* ROTATION */;
  638. break;
  639. }
  640. case 'rotationQuaternion': {
  641. dataAccessorType = "VEC4" /* VEC4 */;
  642. useQuaternion = true;
  643. animationChannelTargetPath = "rotation" /* ROTATION */;
  644. break;
  645. }
  646. default: {
  647. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("Unsupported animatable property " + property[0]);
  648. }
  649. }
  650. if (animationChannelTargetPath) {
  651. return { animationChannelTargetPath: animationChannelTargetPath, dataAccessorType: dataAccessorType, useQuaternion: useQuaternion };
  652. }
  653. else {
  654. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error('animation channel target path and data accessor type could be deduced');
  655. }
  656. return null;
  657. };
  658. /**
  659. * @ignore
  660. * Create node animations from the transform node animations
  661. * @param babylonNode
  662. * @param runtimeGLTFAnimation
  663. * @param idleGLTFAnimations
  664. * @param nodeMap
  665. * @param nodes
  666. * @param binaryWriter
  667. * @param bufferViews
  668. * @param accessors
  669. * @param convertToRightHandedSystem
  670. */
  671. _GLTFAnimation._CreateNodeAnimationFromNodeAnimations = function (babylonNode, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  672. var glTFAnimation;
  673. if (babylonNode instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["TransformNode"]) {
  674. if (babylonNode.animations) {
  675. for (var _i = 0, _a = babylonNode.animations; _i < _a.length; _i++) {
  676. var animation = _a[_i];
  677. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(animation);
  678. if (animationInfo) {
  679. glTFAnimation = {
  680. name: animation.name,
  681. samplers: [],
  682. channels: []
  683. };
  684. _GLTFAnimation.AddAnimation("" + animation.name, animation.hasRunningRuntimeAnimations ? runtimeGLTFAnimation : glTFAnimation, babylonNode, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  685. if (glTFAnimation.samplers.length && glTFAnimation.channels.length) {
  686. idleGLTFAnimations.push(glTFAnimation);
  687. }
  688. }
  689. }
  690. }
  691. }
  692. };
  693. /**
  694. * @ignore
  695. * Create node animations from the animation groups
  696. * @param babylonScene
  697. * @param glTFAnimations
  698. * @param nodeMap
  699. * @param nodes
  700. * @param binaryWriter
  701. * @param bufferViews
  702. * @param accessors
  703. * @param convertToRightHandedSystem
  704. */
  705. _GLTFAnimation._CreateNodeAnimationFromAnimationGroups = function (babylonScene, glTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  706. var glTFAnimation;
  707. if (babylonScene.animationGroups) {
  708. var animationGroups = babylonScene.animationGroups;
  709. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  710. var animationGroup = animationGroups_1[_i];
  711. glTFAnimation = {
  712. name: animationGroup.name,
  713. channels: [],
  714. samplers: []
  715. };
  716. for (var _a = 0, _b = animationGroup.targetedAnimations; _a < _b.length; _a++) {
  717. var targetAnimation = _b[_a];
  718. var target = targetAnimation.target;
  719. var animation = targetAnimation.animation;
  720. if (target instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Mesh"] || target.length === 1 && target[0] instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Mesh"]) { // TODO: Update to support bones
  721. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(targetAnimation.animation);
  722. if (animationInfo) {
  723. var babylonMesh = target instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Mesh"] ? target : target[0];
  724. _GLTFAnimation.AddAnimation("" + animation.name, glTFAnimation, babylonMesh, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  725. }
  726. }
  727. }
  728. if (glTFAnimation.channels.length && glTFAnimation.samplers.length) {
  729. glTFAnimations.push(glTFAnimation);
  730. }
  731. }
  732. }
  733. };
  734. _GLTFAnimation.AddAnimation = function (name, glTFAnimation, babylonTransformNode, animation, dataAccessorType, animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  735. var animationData = _GLTFAnimation._CreateNodeAnimation(babylonTransformNode, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate);
  736. var bufferView;
  737. var accessor;
  738. var keyframeAccessorIndex;
  739. var dataAccessorIndex;
  740. var outputLength;
  741. var animationSampler;
  742. var animationChannel;
  743. if (animationData) {
  744. var nodeIndex = nodeMap[babylonTransformNode.uniqueId];
  745. // Creates buffer view and accessor for key frames.
  746. var byteLength = animationData.inputs.length * 4;
  747. bufferView = _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " keyframe data view");
  748. bufferViews.push(bufferView);
  749. animationData.inputs.forEach(function (input) {
  750. binaryWriter.setFloat32(input);
  751. });
  752. accessor = _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._CreateAccessor(bufferViews.length - 1, name + " keyframes", "SCALAR" /* SCALAR */, 5126 /* FLOAT */, animationData.inputs.length, null, [animationData.inputsMin], [animationData.inputsMax]);
  753. accessors.push(accessor);
  754. keyframeAccessorIndex = accessors.length - 1;
  755. // create bufferview and accessor for keyed values.
  756. outputLength = animationData.outputs.length;
  757. byteLength = dataAccessorType === "VEC3" /* VEC3 */ ? animationData.outputs.length * 12 : animationData.outputs.length * 16;
  758. // check for in and out tangents
  759. bufferView = _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " data view");
  760. bufferViews.push(bufferView);
  761. animationData.outputs.forEach(function (output) {
  762. output.forEach(function (entry) {
  763. binaryWriter.setFloat32(entry);
  764. });
  765. });
  766. accessor = _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._CreateAccessor(bufferViews.length - 1, name + " data", dataAccessorType, 5126 /* FLOAT */, outputLength, null, null, null);
  767. accessors.push(accessor);
  768. dataAccessorIndex = accessors.length - 1;
  769. // create sampler
  770. animationSampler = {
  771. interpolation: animationData.samplerInterpolation,
  772. input: keyframeAccessorIndex,
  773. output: dataAccessorIndex
  774. };
  775. glTFAnimation.samplers.push(animationSampler);
  776. // create channel
  777. animationChannel = {
  778. sampler: glTFAnimation.samplers.length - 1,
  779. target: {
  780. node: nodeIndex,
  781. path: animationChannelTargetPath
  782. }
  783. };
  784. glTFAnimation.channels.push(animationChannel);
  785. }
  786. };
  787. /**
  788. * Create a baked animation
  789. * @param babylonTransformNode BabylonJS mesh
  790. * @param animation BabylonJS animation corresponding to the BabylonJS mesh
  791. * @param animationChannelTargetPath animation target channel
  792. * @param minFrame minimum animation frame
  793. * @param maxFrame maximum animation frame
  794. * @param fps frames per second of the animation
  795. * @param inputs input key frames of the animation
  796. * @param outputs output key frame data of the animation
  797. * @param convertToRightHandedSystem converts the values to right-handed
  798. * @param useQuaternion specifies if quaternions should be used
  799. */
  800. _GLTFAnimation._CreateBakedAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, minFrame, maxFrame, fps, sampleRate, inputs, outputs, minMaxFrames, convertToRightHandedSystem, useQuaternion) {
  801. var value;
  802. var quaternionCache = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Identity();
  803. var previousTime = null;
  804. var time;
  805. var maxUsedFrame = null;
  806. var currKeyFrame = null;
  807. var nextKeyFrame = null;
  808. var prevKeyFrame = null;
  809. var endFrame = null;
  810. minMaxFrames.min = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].FloatRound(minFrame / fps);
  811. var keyFrames = animation.getKeys();
  812. for (var i = 0, length_1 = keyFrames.length; i < length_1; ++i) {
  813. endFrame = null;
  814. currKeyFrame = keyFrames[i];
  815. if (i + 1 < length_1) {
  816. nextKeyFrame = keyFrames[i + 1];
  817. if (currKeyFrame.value.equals(nextKeyFrame.value)) {
  818. if (i === 0) { // set the first frame to itself
  819. endFrame = currKeyFrame.frame;
  820. }
  821. else {
  822. continue;
  823. }
  824. }
  825. else {
  826. endFrame = nextKeyFrame.frame;
  827. }
  828. }
  829. else {
  830. // at the last key frame
  831. prevKeyFrame = keyFrames[i - 1];
  832. if (currKeyFrame.value.equals(prevKeyFrame.value)) {
  833. continue;
  834. }
  835. else {
  836. endFrame = maxFrame;
  837. }
  838. }
  839. if (endFrame) {
  840. for (var f = currKeyFrame.frame; f <= endFrame; f += sampleRate) {
  841. time = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].FloatRound(f / fps);
  842. if (time === previousTime) {
  843. continue;
  844. }
  845. previousTime = time;
  846. maxUsedFrame = time;
  847. var state = {
  848. key: 0,
  849. repeatCount: 0,
  850. loopMode: animation.loopMode
  851. };
  852. value = animation._interpolate(f, state);
  853. _GLTFAnimation._SetInterpolatedValue(babylonTransformNode, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  854. }
  855. }
  856. }
  857. if (maxUsedFrame) {
  858. minMaxFrames.max = maxUsedFrame;
  859. }
  860. };
  861. _GLTFAnimation._ConvertFactorToVector3OrQuaternion = function (factor, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  862. var property;
  863. var componentName;
  864. var value = null;
  865. var basePositionRotationOrScale = _GLTFAnimation._GetBasePositionRotationOrScale(babylonTransformNode, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  866. if (animationType === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONTYPE_FLOAT) { // handles single component x, y, z or w component animation by using a base property and animating over a component.
  867. property = animation.targetProperty.split('.');
  868. componentName = property ? property[1] : ''; // x, y, or z component
  869. value = useQuaternion ? babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(basePositionRotationOrScale).normalize() : babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(basePositionRotationOrScale);
  870. switch (componentName) {
  871. case 'x': {
  872. value[componentName] = (convertToRightHandedSystem && useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  873. break;
  874. }
  875. case 'y': {
  876. value[componentName] = (convertToRightHandedSystem && useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  877. break;
  878. }
  879. case 'z': {
  880. value[componentName] = (convertToRightHandedSystem && !useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  881. break;
  882. }
  883. case 'w': {
  884. value.w = factor;
  885. break;
  886. }
  887. default: {
  888. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("glTFAnimation: Unsupported component type \"" + componentName + "\" for scale animation!");
  889. }
  890. }
  891. }
  892. return value;
  893. };
  894. _GLTFAnimation._SetInterpolatedValue = function (babylonTransformNode, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  895. var animationType = animation.dataType;
  896. var cacheValue;
  897. inputs.push(time);
  898. if (typeof value === "number") {
  899. value = this._ConvertFactorToVector3OrQuaternion(value, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  900. }
  901. if (value) {
  902. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  903. if (useQuaternion) {
  904. quaternionCache = value;
  905. }
  906. else {
  907. cacheValue = value;
  908. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].RotationYawPitchRollToRef(cacheValue.y, cacheValue.x, cacheValue.z, quaternionCache);
  909. }
  910. if (convertToRightHandedSystem) {
  911. _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._GetRightHandedQuaternionFromRef(quaternionCache);
  912. if (!babylonTransformNode.parent) {
  913. quaternionCache = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray([0, 1, 0, 0]).multiply(quaternionCache);
  914. }
  915. }
  916. outputs.push(quaternionCache.asArray());
  917. }
  918. else {
  919. cacheValue = value;
  920. if (convertToRightHandedSystem && (animationChannelTargetPath !== "scale" /* SCALE */)) {
  921. _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._GetRightHandedPositionVector3FromRef(cacheValue);
  922. if (!babylonTransformNode.parent) {
  923. cacheValue.x *= -1;
  924. cacheValue.z *= -1;
  925. }
  926. }
  927. outputs.push(cacheValue.asArray());
  928. }
  929. }
  930. };
  931. /**
  932. * Creates linear animation from the animation key frames
  933. * @param babylonTransformNode BabylonJS mesh
  934. * @param animation BabylonJS animation
  935. * @param animationChannelTargetPath The target animation channel
  936. * @param frameDelta The difference between the last and first frame of the animation
  937. * @param inputs Array to store the key frame times
  938. * @param outputs Array to store the key frame data
  939. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  940. * @param useQuaternion Specifies if quaternions are used in the animation
  941. */
  942. _GLTFAnimation._CreateLinearOrStepAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  943. for (var _i = 0, _a = animation.getKeys(); _i < _a.length; _i++) {
  944. var keyFrame = _a[_i];
  945. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  946. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion);
  947. }
  948. };
  949. /**
  950. * Creates cubic spline animation from the animation key frames
  951. * @param babylonTransformNode BabylonJS mesh
  952. * @param animation BabylonJS animation
  953. * @param animationChannelTargetPath The target animation channel
  954. * @param frameDelta The difference between the last and first frame of the animation
  955. * @param inputs Array to store the key frame times
  956. * @param outputs Array to store the key frame data
  957. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  958. * @param useQuaternion Specifies if quaternions are used in the animation
  959. */
  960. _GLTFAnimation._CreateCubicSplineAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  961. animation.getKeys().forEach(function (keyFrame) {
  962. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  963. _GLTFAnimation.AddSplineTangent(babylonTransformNode, _TangentType.INTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  964. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion);
  965. _GLTFAnimation.AddSplineTangent(babylonTransformNode, _TangentType.OUTTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  966. });
  967. };
  968. _GLTFAnimation._GetBasePositionRotationOrScale = function (babylonTransformNode, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  969. var basePositionRotationOrScale;
  970. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  971. if (useQuaternion) {
  972. if (babylonTransformNode.rotationQuaternion) {
  973. basePositionRotationOrScale = babylonTransformNode.rotationQuaternion.asArray();
  974. if (convertToRightHandedSystem) {
  975. _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._GetRightHandedQuaternionArrayFromRef(basePositionRotationOrScale);
  976. if (!babylonTransformNode.parent) {
  977. basePositionRotationOrScale = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray([0, 1, 0, 0]).multiply(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(basePositionRotationOrScale)).asArray();
  978. }
  979. }
  980. }
  981. else {
  982. basePositionRotationOrScale = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].Identity().asArray();
  983. }
  984. }
  985. else {
  986. basePositionRotationOrScale = babylonTransformNode.rotation.asArray();
  987. _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._GetRightHandedNormalArray3FromRef(basePositionRotationOrScale);
  988. }
  989. }
  990. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  991. basePositionRotationOrScale = babylonTransformNode.position.asArray();
  992. if (convertToRightHandedSystem) {
  993. _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._GetRightHandedPositionArray3FromRef(basePositionRotationOrScale);
  994. }
  995. }
  996. else { // scale
  997. basePositionRotationOrScale = babylonTransformNode.scaling.asArray();
  998. }
  999. return basePositionRotationOrScale;
  1000. };
  1001. /**
  1002. * Adds a key frame value
  1003. * @param keyFrame
  1004. * @param animation
  1005. * @param outputs
  1006. * @param animationChannelTargetPath
  1007. * @param basePositionRotationOrScale
  1008. * @param convertToRightHandedSystem
  1009. * @param useQuaternion
  1010. */
  1011. _GLTFAnimation._AddKeyframeValue = function (keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion) {
  1012. var value;
  1013. var newPositionRotationOrScale;
  1014. var animationType = animation.dataType;
  1015. if (animationType === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONTYPE_VECTOR3) {
  1016. value = keyFrame.value.asArray();
  1017. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  1018. var array = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(value);
  1019. var rotationQuaternion = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].RotationYawPitchRoll(array.y, array.x, array.z);
  1020. if (convertToRightHandedSystem) {
  1021. _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._GetRightHandedQuaternionFromRef(rotationQuaternion);
  1022. if (!babylonTransformNode.parent) {
  1023. rotationQuaternion = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray([0, 1, 0, 0]).multiply(rotationQuaternion);
  1024. }
  1025. }
  1026. value = rotationQuaternion.asArray();
  1027. }
  1028. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  1029. if (convertToRightHandedSystem) {
  1030. _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._GetRightHandedNormalArray3FromRef(value);
  1031. if (!babylonTransformNode.parent) {
  1032. value[0] *= -1;
  1033. value[2] *= -1;
  1034. }
  1035. }
  1036. }
  1037. outputs.push(value); // scale vector.
  1038. }
  1039. else if (animationType === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONTYPE_FLOAT) { // handles single component x, y, z or w component animation by using a base property and animating over a component.
  1040. newPositionRotationOrScale = this._ConvertFactorToVector3OrQuaternion(keyFrame.value, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  1041. if (newPositionRotationOrScale) {
  1042. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  1043. var posRotScale = useQuaternion ? newPositionRotationOrScale : babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].RotationYawPitchRoll(newPositionRotationOrScale.y, newPositionRotationOrScale.x, newPositionRotationOrScale.z).normalize();
  1044. if (convertToRightHandedSystem) {
  1045. _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._GetRightHandedQuaternionFromRef(posRotScale);
  1046. if (!babylonTransformNode.parent) {
  1047. posRotScale = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray([0, 1, 0, 0]).multiply(posRotScale);
  1048. }
  1049. }
  1050. outputs.push(posRotScale.asArray());
  1051. }
  1052. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  1053. if (convertToRightHandedSystem) {
  1054. _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._GetRightHandedNormalVector3FromRef(newPositionRotationOrScale);
  1055. if (!babylonTransformNode.parent) {
  1056. newPositionRotationOrScale.x *= -1;
  1057. newPositionRotationOrScale.z *= -1;
  1058. }
  1059. }
  1060. }
  1061. outputs.push(newPositionRotationOrScale.asArray());
  1062. }
  1063. }
  1064. else if (animationType === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Animation"].ANIMATIONTYPE_QUATERNION) {
  1065. value = keyFrame.value.normalize().asArray();
  1066. if (convertToRightHandedSystem) {
  1067. _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._GetRightHandedQuaternionArrayFromRef(value);
  1068. if (!babylonTransformNode.parent) {
  1069. value = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray([0, 1, 0, 0]).multiply(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(value)).asArray();
  1070. }
  1071. }
  1072. outputs.push(value);
  1073. }
  1074. else {
  1075. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error('glTFAnimation: Unsupported key frame values for animation!');
  1076. }
  1077. };
  1078. /**
  1079. * Determine the interpolation based on the key frames
  1080. * @param keyFrames
  1081. * @param animationChannelTargetPath
  1082. * @param useQuaternion
  1083. */
  1084. _GLTFAnimation._DeduceInterpolation = function (keyFrames, animationChannelTargetPath, useQuaternion) {
  1085. var interpolationType;
  1086. var shouldBakeAnimation = false;
  1087. var key;
  1088. if (animationChannelTargetPath === "rotation" /* ROTATION */ && !useQuaternion) {
  1089. return { interpolationType: "LINEAR" /* LINEAR */, shouldBakeAnimation: true };
  1090. }
  1091. for (var i = 0, length_2 = keyFrames.length; i < length_2; ++i) {
  1092. key = keyFrames[i];
  1093. if (key.inTangent || key.outTangent) {
  1094. if (interpolationType) {
  1095. if (interpolationType !== "CUBICSPLINE" /* CUBICSPLINE */) {
  1096. interpolationType = "LINEAR" /* LINEAR */;
  1097. shouldBakeAnimation = true;
  1098. break;
  1099. }
  1100. }
  1101. else {
  1102. interpolationType = "CUBICSPLINE" /* CUBICSPLINE */;
  1103. }
  1104. }
  1105. else {
  1106. if (interpolationType) {
  1107. if (interpolationType === "CUBICSPLINE" /* CUBICSPLINE */ ||
  1108. (key.interpolation && (key.interpolation === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["AnimationKeyInterpolation"].STEP) && interpolationType !== "STEP" /* STEP */)) {
  1109. interpolationType = "LINEAR" /* LINEAR */;
  1110. shouldBakeAnimation = true;
  1111. break;
  1112. }
  1113. }
  1114. else {
  1115. if (key.interpolation && (key.interpolation === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["AnimationKeyInterpolation"].STEP)) {
  1116. interpolationType = "STEP" /* STEP */;
  1117. }
  1118. else {
  1119. interpolationType = "LINEAR" /* LINEAR */;
  1120. }
  1121. }
  1122. }
  1123. }
  1124. if (!interpolationType) {
  1125. interpolationType = "LINEAR" /* LINEAR */;
  1126. }
  1127. return { interpolationType: interpolationType, shouldBakeAnimation: shouldBakeAnimation };
  1128. };
  1129. /**
  1130. * Adds an input tangent or output tangent to the output data
  1131. * If an input tangent or output tangent is missing, it uses the zero vector or zero quaternion
  1132. * @param tangentType Specifies which type of tangent to handle (inTangent or outTangent)
  1133. * @param outputs The animation data by keyframe
  1134. * @param animationChannelTargetPath The target animation channel
  1135. * @param interpolation The interpolation type
  1136. * @param keyFrame The key frame with the animation data
  1137. * @param frameDelta Time difference between two frames used to scale the tangent by the frame delta
  1138. * @param useQuaternion Specifies if quaternions are used
  1139. * @param convertToRightHandedSystem Specifies if the values should be converted to right-handed
  1140. */
  1141. _GLTFAnimation.AddSplineTangent = function (babylonTransformNode, tangentType, outputs, animationChannelTargetPath, interpolation, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem) {
  1142. var tangent;
  1143. var tangentValue = tangentType === _TangentType.INTANGENT ? keyFrame.inTangent : keyFrame.outTangent;
  1144. if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  1145. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  1146. if (tangentValue) {
  1147. if (useQuaternion) {
  1148. tangent = tangentValue.scale(frameDelta).asArray();
  1149. }
  1150. else {
  1151. var array = tangentValue.scale(frameDelta);
  1152. tangent = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].RotationYawPitchRoll(array.y, array.x, array.z).asArray();
  1153. }
  1154. if (convertToRightHandedSystem) {
  1155. _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._GetRightHandedQuaternionArrayFromRef(tangent);
  1156. if (!babylonTransformNode.parent) {
  1157. tangent = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray([0, 1, 0, 0]).multiply(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(tangent)).asArray();
  1158. }
  1159. }
  1160. }
  1161. else {
  1162. tangent = [0, 0, 0, 0];
  1163. }
  1164. }
  1165. else {
  1166. if (tangentValue) {
  1167. tangent = tangentValue.scale(frameDelta).asArray();
  1168. if (convertToRightHandedSystem) {
  1169. if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  1170. _glTFUtilities__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]._GetRightHandedPositionArray3FromRef(tangent);
  1171. if (!babylonTransformNode.parent) {
  1172. tangent[0] *= -1; // x
  1173. tangent[2] *= -1; // z
  1174. }
  1175. }
  1176. }
  1177. }
  1178. else {
  1179. tangent = [0, 0, 0];
  1180. }
  1181. }
  1182. outputs.push(tangent);
  1183. }
  1184. };
  1185. /**
  1186. * Get the minimum and maximum key frames' frame values
  1187. * @param keyFrames animation key frames
  1188. * @returns the minimum and maximum key frame value
  1189. */
  1190. _GLTFAnimation.calculateMinMaxKeyFrames = function (keyFrames) {
  1191. var min = Infinity;
  1192. var max = -Infinity;
  1193. keyFrames.forEach(function (keyFrame) {
  1194. min = Math.min(min, keyFrame.frame);
  1195. max = Math.max(max, keyFrame.frame);
  1196. });
  1197. return { min: min, max: max };
  1198. };
  1199. return _GLTFAnimation;
  1200. }());
  1201. /***/ }),
  1202. /***/ "./glTF/2.0/glTFData.ts":
  1203. /*!******************************!*\
  1204. !*** ./glTF/2.0/glTFData.ts ***!
  1205. \******************************/
  1206. /*! exports provided: GLTFData */
  1207. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  1208. "use strict";
  1209. __webpack_require__.r(__webpack_exports__);
  1210. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GLTFData", function() { return GLTFData; });
  1211. /**
  1212. * Class for holding and downloading glTF file data
  1213. */
  1214. var GLTFData = /** @class */ (function () {
  1215. /**
  1216. * Initializes the glTF file object
  1217. */
  1218. function GLTFData() {
  1219. this.glTFFiles = {};
  1220. }
  1221. /**
  1222. * Downloads the glTF data as files based on their names and data
  1223. */
  1224. GLTFData.prototype.downloadFiles = function () {
  1225. /**
  1226. * Checks for a matching suffix at the end of a string (for ES5 and lower)
  1227. * @param str Source string
  1228. * @param suffix Suffix to search for in the source string
  1229. * @returns Boolean indicating whether the suffix was found (true) or not (false)
  1230. */
  1231. function endsWith(str, suffix) {
  1232. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  1233. }
  1234. for (var key in this.glTFFiles) {
  1235. var link = document.createElement('a');
  1236. document.body.appendChild(link);
  1237. link.setAttribute("type", "hidden");
  1238. link.download = key;
  1239. var blob = this.glTFFiles[key];
  1240. var mimeType = void 0;
  1241. if (endsWith(key, ".glb")) {
  1242. mimeType = { type: "model/gltf-binary" };
  1243. }
  1244. else if (endsWith(key, ".bin")) {
  1245. mimeType = { type: "application/octet-stream" };
  1246. }
  1247. else if (endsWith(key, ".gltf")) {
  1248. mimeType = { type: "model/gltf+json" };
  1249. }
  1250. else if (endsWith(key, ".jpeg" || false)) {
  1251. mimeType = { type: "image/jpeg" /* JPEG */ };
  1252. }
  1253. else if (endsWith(key, ".png")) {
  1254. mimeType = { type: "image/png" /* PNG */ };
  1255. }
  1256. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  1257. link.click();
  1258. }
  1259. };
  1260. return GLTFData;
  1261. }());
  1262. /***/ }),
  1263. /***/ "./glTF/2.0/glTFExporter.ts":
  1264. /*!**********************************!*\
  1265. !*** ./glTF/2.0/glTFExporter.ts ***!
  1266. \**********************************/
  1267. /*! exports provided: _Exporter, _BinaryWriter */
  1268. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  1269. "use strict";
  1270. __webpack_require__.r(__webpack_exports__);
  1271. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_Exporter", function() { return _Exporter; });
  1272. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_BinaryWriter", function() { return _BinaryWriter; });
  1273. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Maths/math");
  1274. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__);
  1275. /* harmony import */ var _glTFMaterialExporter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./glTFMaterialExporter */ "./glTF/2.0/glTFMaterialExporter.ts");
  1276. /* harmony import */ var _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./glTFUtilities */ "./glTF/2.0/glTFUtilities.ts");
  1277. /* harmony import */ var _glTFData__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./glTFData */ "./glTF/2.0/glTFData.ts");
  1278. /* harmony import */ var _glTFAnimation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./glTFAnimation */ "./glTF/2.0/glTFAnimation.ts");
  1279. /**
  1280. * Converts Babylon Scene into glTF 2.0.
  1281. * @hidden
  1282. */
  1283. var _Exporter = /** @class */ (function () {
  1284. /**
  1285. * Creates a glTF Exporter instance, which can accept optional exporter options
  1286. * @param babylonScene Babylon scene object
  1287. * @param options Options to modify the behavior of the exporter
  1288. */
  1289. function _Exporter(babylonScene, options) {
  1290. this._extensions = {};
  1291. this._glTF = {
  1292. asset: { generator: "BabylonJS", version: "2.0" }
  1293. };
  1294. this._babylonScene = babylonScene;
  1295. this._bufferViews = [];
  1296. this._accessors = [];
  1297. this._meshes = [];
  1298. this._scenes = [];
  1299. this._nodes = [];
  1300. this._images = [];
  1301. this._materials = [];
  1302. this._materialMap = [];
  1303. this._textures = [];
  1304. this._samplers = [];
  1305. this._animations = [];
  1306. this._imageData = {};
  1307. this._convertToRightHandedSystem = this._babylonScene.useRightHandedSystem ? false : true;
  1308. var _options = options || {};
  1309. this._shouldExportNode = _options.shouldExportNode ? _options.shouldExportNode : function (babylonNode) { return true; };
  1310. this._animationSampleRate = _options.animationSampleRate ? _options.animationSampleRate : 1 / 60;
  1311. this._glTFMaterialExporter = new _glTFMaterialExporter__WEBPACK_IMPORTED_MODULE_1__["_GLTFMaterialExporter"](this);
  1312. this._loadExtensions();
  1313. }
  1314. _Exporter.prototype._applyExtensions = function (property, actionAsync) {
  1315. for (var _i = 0, _a = _Exporter._ExtensionNames; _i < _a.length; _i++) {
  1316. var name_1 = _a[_i];
  1317. var extension = this._extensions[name_1];
  1318. if (extension.enabled) {
  1319. var exporterProperty = property;
  1320. exporterProperty._activeLoaderExtensions = exporterProperty._activeLoaderExtensions || {};
  1321. var activeLoaderExtensions = exporterProperty._activeLoaderExtensions;
  1322. if (!activeLoaderExtensions[name_1]) {
  1323. activeLoaderExtensions[name_1] = true;
  1324. try {
  1325. var result = actionAsync(extension);
  1326. if (result) {
  1327. return result;
  1328. }
  1329. }
  1330. finally {
  1331. delete activeLoaderExtensions[name_1];
  1332. delete exporterProperty._activeLoaderExtensions;
  1333. }
  1334. }
  1335. }
  1336. }
  1337. return null;
  1338. };
  1339. _Exporter.prototype._extensionsPreExportTextureAsync = function (context, babylonTexture, mimeType) {
  1340. return this._applyExtensions(babylonTexture, function (extension) { return extension.preExportTextureAsync && extension.preExportTextureAsync(context, babylonTexture, mimeType); });
  1341. };
  1342. _Exporter.prototype._extensionsPostExportMeshPrimitiveAsync = function (context, meshPrimitive, babylonSubMesh, binaryWriter) {
  1343. return this._applyExtensions(meshPrimitive, function (extension) { return extension.postExportMeshPrimitiveAsync && extension.postExportMeshPrimitiveAsync(context, meshPrimitive, babylonSubMesh, binaryWriter); });
  1344. };
  1345. _Exporter.prototype._extensionsPostExportNodeAsync = function (context, node, babylonNode) {
  1346. return this._applyExtensions(node, function (extension) { return extension.postExportNodeAsync && extension.postExportNodeAsync(context, node, babylonNode); });
  1347. };
  1348. _Exporter.prototype._forEachExtensions = function (action) {
  1349. for (var _i = 0, _a = _Exporter._ExtensionNames; _i < _a.length; _i++) {
  1350. var name_2 = _a[_i];
  1351. var extension = this._extensions[name_2];
  1352. if (extension.enabled) {
  1353. action(extension);
  1354. }
  1355. }
  1356. };
  1357. _Exporter.prototype._extensionsOnExporting = function () {
  1358. this._forEachExtensions(function (extension) { return extension.onExporting && extension.onExporting(); });
  1359. };
  1360. /**
  1361. * Load glTF serializer extensions
  1362. */
  1363. _Exporter.prototype._loadExtensions = function () {
  1364. for (var _i = 0, _a = _Exporter._ExtensionNames; _i < _a.length; _i++) {
  1365. var name_3 = _a[_i];
  1366. var extension = _Exporter._ExtensionFactories[name_3](this);
  1367. this._extensions[name_3] = extension;
  1368. }
  1369. };
  1370. /**
  1371. * Registers a glTF exporter extension
  1372. * @param name Name of the extension to export
  1373. * @param factory The factory function that creates the exporter extension
  1374. */
  1375. _Exporter.RegisterExtension = function (name, factory) {
  1376. if (_Exporter.UnregisterExtension(name)) {
  1377. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Extension with the name " + name + " already exists");
  1378. }
  1379. _Exporter._ExtensionFactories[name] = factory;
  1380. _Exporter._ExtensionNames.push(name);
  1381. };
  1382. /**
  1383. * Un-registers an exporter extension
  1384. * @param name The name fo the exporter extension
  1385. * @returns A boolean indicating whether the extension has been un-registered
  1386. */
  1387. _Exporter.UnregisterExtension = function (name) {
  1388. if (!_Exporter._ExtensionFactories[name]) {
  1389. return false;
  1390. }
  1391. delete _Exporter._ExtensionFactories[name];
  1392. var index = _Exporter._ExtensionNames.indexOf(name);
  1393. if (index !== -1) {
  1394. _Exporter._ExtensionNames.splice(index, 1);
  1395. }
  1396. return true;
  1397. };
  1398. /**
  1399. * Lazy load a local engine with premultiplied alpha set to false
  1400. */
  1401. _Exporter.prototype._getLocalEngine = function () {
  1402. if (!this._localEngine) {
  1403. var localCanvas = document.createElement('canvas');
  1404. localCanvas.id = "WriteCanvas";
  1405. localCanvas.width = 2048;
  1406. localCanvas.height = 2048;
  1407. this._localEngine = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Engine"](localCanvas, true, { premultipliedAlpha: false, preserveDrawingBuffer: true });
  1408. this._localEngine.setViewport(new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Viewport"](0, 0, 1, 1));
  1409. }
  1410. return this._localEngine;
  1411. };
  1412. _Exporter.prototype.reorderIndicesBasedOnPrimitiveMode = function (submesh, primitiveMode, babylonIndices, byteOffset, binaryWriter) {
  1413. switch (primitiveMode) {
  1414. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].TriangleFillMode: {
  1415. if (!byteOffset) {
  1416. byteOffset = 0;
  1417. }
  1418. for (var i = submesh.indexStart, length_1 = submesh.indexStart + submesh.indexCount; i < length_1; i = i + 3) {
  1419. var index = byteOffset + i * 4;
  1420. // swap the second and third indices
  1421. var secondIndex = binaryWriter.getUInt32(index + 4);
  1422. var thirdIndex = binaryWriter.getUInt32(index + 8);
  1423. binaryWriter.setUInt32(thirdIndex, index + 4);
  1424. binaryWriter.setUInt32(secondIndex, index + 8);
  1425. }
  1426. break;
  1427. }
  1428. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].TriangleFanDrawMode: {
  1429. for (var i = submesh.indexStart + submesh.indexCount - 1, start = submesh.indexStart; i >= start; --i) {
  1430. binaryWriter.setUInt32(babylonIndices[i], byteOffset);
  1431. byteOffset += 4;
  1432. }
  1433. break;
  1434. }
  1435. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].TriangleStripDrawMode: {
  1436. if (submesh.indexCount >= 3) {
  1437. binaryWriter.setUInt32(babylonIndices[submesh.indexStart + 2], byteOffset + 4);
  1438. binaryWriter.setUInt32(babylonIndices[submesh.indexStart + 1], byteOffset + 8);
  1439. }
  1440. break;
  1441. }
  1442. }
  1443. };
  1444. /**
  1445. * Reorders the vertex attribute data based on the primitive mode. This is necessary when indices are not available and the winding order is
  1446. * clock-wise during export to glTF
  1447. * @param submesh BabylonJS submesh
  1448. * @param primitiveMode Primitive mode of the mesh
  1449. * @param sideOrientation the winding order of the submesh
  1450. * @param vertexBufferKind The type of vertex attribute
  1451. * @param meshAttributeArray The vertex attribute data
  1452. * @param byteOffset The offset to the binary data
  1453. * @param binaryWriter The binary data for the glTF file
  1454. */
  1455. _Exporter.prototype.reorderVertexAttributeDataBasedOnPrimitiveMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  1456. if (this._convertToRightHandedSystem && sideOrientation === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].ClockWiseSideOrientation) {
  1457. switch (primitiveMode) {
  1458. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].TriangleFillMode: {
  1459. this.reorderTriangleFillMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  1460. break;
  1461. }
  1462. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].TriangleStripDrawMode: {
  1463. this.reorderTriangleStripDrawMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  1464. break;
  1465. }
  1466. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].TriangleFanDrawMode: {
  1467. this.reorderTriangleFanMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  1468. break;
  1469. }
  1470. }
  1471. }
  1472. };
  1473. /**
  1474. * Reorders the vertex attributes in the correct triangle mode order . This is necessary when indices are not available and the winding order is
  1475. * clock-wise during export to glTF
  1476. * @param submesh BabylonJS submesh
  1477. * @param primitiveMode Primitive mode of the mesh
  1478. * @param sideOrientation the winding order of the submesh
  1479. * @param vertexBufferKind The type of vertex attribute
  1480. * @param meshAttributeArray The vertex attribute data
  1481. * @param byteOffset The offset to the binary data
  1482. * @param binaryWriter The binary data for the glTF file
  1483. */
  1484. _Exporter.prototype.reorderTriangleFillMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  1485. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  1486. if (vertexBuffer) {
  1487. var stride = vertexBuffer.byteStride / babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].GetTypeByteLength(vertexBuffer.type);
  1488. if (submesh.verticesCount % 3 !== 0) {
  1489. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error('The submesh vertices for the triangle fill mode is not divisible by 3!');
  1490. }
  1491. else {
  1492. var vertexData = [];
  1493. var index = 0;
  1494. switch (vertexBufferKind) {
  1495. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].PositionKind:
  1496. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].NormalKind: {
  1497. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  1498. index = x * stride;
  1499. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index));
  1500. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index + 2 * stride));
  1501. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index + stride));
  1502. }
  1503. break;
  1504. }
  1505. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].TangentKind: {
  1506. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  1507. index = x * stride;
  1508. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"].FromArray(meshAttributeArray, index));
  1509. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"].FromArray(meshAttributeArray, index + 2 * stride));
  1510. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"].FromArray(meshAttributeArray, index + stride));
  1511. }
  1512. break;
  1513. }
  1514. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].ColorKind: {
  1515. var size = vertexBuffer.getSize();
  1516. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + size) {
  1517. index = x * stride;
  1518. if (size === 4) {
  1519. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"].FromArray(meshAttributeArray, index));
  1520. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"].FromArray(meshAttributeArray, index + 2 * stride));
  1521. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"].FromArray(meshAttributeArray, index + stride));
  1522. }
  1523. else {
  1524. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index));
  1525. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index + 2 * stride));
  1526. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index + stride));
  1527. }
  1528. }
  1529. break;
  1530. }
  1531. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UVKind:
  1532. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UV2Kind: {
  1533. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  1534. index = x * stride;
  1535. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(meshAttributeArray, index));
  1536. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(meshAttributeArray, index + 2 * stride));
  1537. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(meshAttributeArray, index + stride));
  1538. }
  1539. break;
  1540. }
  1541. default: {
  1542. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  1543. }
  1544. }
  1545. this.writeVertexAttributeData(vertexData, byteOffset, vertexBufferKind, meshAttributeArray, binaryWriter);
  1546. }
  1547. }
  1548. else {
  1549. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("reorderTriangleFillMode: Vertex Buffer Kind " + vertexBufferKind + " not present!");
  1550. }
  1551. };
  1552. /**
  1553. * Reorders the vertex attributes in the correct triangle strip order. This is necessary when indices are not available and the winding order is
  1554. * clock-wise during export to glTF
  1555. * @param submesh BabylonJS submesh
  1556. * @param primitiveMode Primitive mode of the mesh
  1557. * @param sideOrientation the winding order of the submesh
  1558. * @param vertexBufferKind The type of vertex attribute
  1559. * @param meshAttributeArray The vertex attribute data
  1560. * @param byteOffset The offset to the binary data
  1561. * @param binaryWriter The binary data for the glTF file
  1562. */
  1563. _Exporter.prototype.reorderTriangleStripDrawMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  1564. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  1565. if (vertexBuffer) {
  1566. var stride = vertexBuffer.byteStride / babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].GetTypeByteLength(vertexBuffer.type);
  1567. var vertexData = [];
  1568. var index = 0;
  1569. switch (vertexBufferKind) {
  1570. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].PositionKind:
  1571. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].NormalKind: {
  1572. index = submesh.verticesStart;
  1573. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index + 2 * stride));
  1574. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index + stride));
  1575. break;
  1576. }
  1577. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].TangentKind: {
  1578. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  1579. index = x * stride;
  1580. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"].FromArray(meshAttributeArray, index));
  1581. }
  1582. break;
  1583. }
  1584. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].ColorKind: {
  1585. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  1586. index = x * stride;
  1587. vertexBuffer.getSize() === 4 ? vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"].FromArray(meshAttributeArray, index)) : vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index));
  1588. }
  1589. break;
  1590. }
  1591. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UVKind:
  1592. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UV2Kind: {
  1593. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  1594. index = x * stride;
  1595. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(meshAttributeArray, index));
  1596. }
  1597. break;
  1598. }
  1599. default: {
  1600. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  1601. }
  1602. }
  1603. this.writeVertexAttributeData(vertexData, byteOffset + 12, vertexBufferKind, meshAttributeArray, binaryWriter);
  1604. }
  1605. else {
  1606. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("reorderTriangleStripDrawMode: Vertex buffer kind " + vertexBufferKind + " not present!");
  1607. }
  1608. };
  1609. /**
  1610. * Reorders the vertex attributes in the correct triangle fan order. This is necessary when indices are not available and the winding order is
  1611. * clock-wise during export to glTF
  1612. * @param submesh BabylonJS submesh
  1613. * @param primitiveMode Primitive mode of the mesh
  1614. * @param sideOrientation the winding order of the submesh
  1615. * @param vertexBufferKind The type of vertex attribute
  1616. * @param meshAttributeArray The vertex attribute data
  1617. * @param byteOffset The offset to the binary data
  1618. * @param binaryWriter The binary data for the glTF file
  1619. */
  1620. _Exporter.prototype.reorderTriangleFanMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  1621. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  1622. if (vertexBuffer) {
  1623. var stride = vertexBuffer.byteStride / babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].GetTypeByteLength(vertexBuffer.type);
  1624. var vertexData = [];
  1625. var index = 0;
  1626. switch (vertexBufferKind) {
  1627. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].PositionKind:
  1628. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].NormalKind: {
  1629. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  1630. index = x * stride;
  1631. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index));
  1632. }
  1633. break;
  1634. }
  1635. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].TangentKind: {
  1636. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  1637. index = x * stride;
  1638. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"].FromArray(meshAttributeArray, index));
  1639. }
  1640. break;
  1641. }
  1642. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].ColorKind: {
  1643. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  1644. index = x * stride;
  1645. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"].FromArray(meshAttributeArray, index));
  1646. vertexBuffer.getSize() === 4 ? vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"].FromArray(meshAttributeArray, index)) : vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index));
  1647. }
  1648. break;
  1649. }
  1650. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UVKind:
  1651. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UV2Kind: {
  1652. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  1653. index = x * stride;
  1654. vertexData.push(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"].FromArray(meshAttributeArray, index));
  1655. }
  1656. break;
  1657. }
  1658. default: {
  1659. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  1660. }
  1661. }
  1662. this.writeVertexAttributeData(vertexData, byteOffset, vertexBufferKind, meshAttributeArray, binaryWriter);
  1663. }
  1664. else {
  1665. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("reorderTriangleFanMode: Vertex buffer kind " + vertexBufferKind + " not present!");
  1666. }
  1667. };
  1668. /**
  1669. * Writes the vertex attribute data to binary
  1670. * @param vertices The vertices to write to the binary writer
  1671. * @param byteOffset The offset into the binary writer to overwrite binary data
  1672. * @param vertexAttributeKind The vertex attribute type
  1673. * @param meshAttributeArray The vertex attribute data
  1674. * @param binaryWriter The writer containing the binary data
  1675. */
  1676. _Exporter.prototype.writeVertexAttributeData = function (vertices, byteOffset, vertexAttributeKind, meshAttributeArray, binaryWriter) {
  1677. for (var _i = 0, vertices_1 = vertices; _i < vertices_1.length; _i++) {
  1678. var vertex = vertices_1[_i];
  1679. if (this._convertToRightHandedSystem && !(vertexAttributeKind === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].ColorKind) && !(vertex instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"])) {
  1680. if (vertex instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"]) {
  1681. if (vertexAttributeKind === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].NormalKind) {
  1682. _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._GetRightHandedNormalVector3FromRef(vertex);
  1683. }
  1684. else if (vertexAttributeKind === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].PositionKind) {
  1685. _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._GetRightHandedPositionVector3FromRef(vertex);
  1686. }
  1687. else {
  1688. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error('Unsupported vertex attribute kind!');
  1689. }
  1690. }
  1691. else {
  1692. _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._GetRightHandedVector4FromRef(vertex);
  1693. }
  1694. }
  1695. if (vertexAttributeKind === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].NormalKind) {
  1696. vertex.normalize();
  1697. }
  1698. else if (vertexAttributeKind === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].TangentKind && vertex instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"]) {
  1699. _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._NormalizeTangentFromRef(vertex);
  1700. }
  1701. for (var _a = 0, _b = vertex.asArray(); _a < _b.length; _a++) {
  1702. var component = _b[_a];
  1703. binaryWriter.setFloat32(component, byteOffset);
  1704. byteOffset += 4;
  1705. }
  1706. }
  1707. };
  1708. /**
  1709. * Writes mesh attribute data to a data buffer
  1710. * Returns the bytelength of the data
  1711. * @param vertexBufferKind Indicates what kind of vertex data is being passed in
  1712. * @param meshAttributeArray Array containing the attribute data
  1713. * @param binaryWriter The buffer to write the binary data to
  1714. * @param indices Used to specify the order of the vertex data
  1715. */
  1716. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, byteStride, binaryWriter) {
  1717. var stride = byteStride / 4;
  1718. var vertexAttributes = [];
  1719. var index;
  1720. switch (vertexBufferKind) {
  1721. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].PositionKind: {
  1722. for (var k = 0, length_2 = meshAttributeArray.length / stride; k < length_2; ++k) {
  1723. index = k * stride;
  1724. var vertexData = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index);
  1725. if (this._convertToRightHandedSystem) {
  1726. _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._GetRightHandedPositionVector3FromRef(vertexData);
  1727. }
  1728. vertexAttributes.push(vertexData.asArray());
  1729. }
  1730. break;
  1731. }
  1732. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].NormalKind: {
  1733. for (var k = 0, length_3 = meshAttributeArray.length / stride; k < length_3; ++k) {
  1734. index = k * stride;
  1735. var vertexData = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index);
  1736. if (this._convertToRightHandedSystem) {
  1737. _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._GetRightHandedNormalVector3FromRef(vertexData);
  1738. }
  1739. vertexData.normalize();
  1740. vertexAttributes.push(vertexData.asArray());
  1741. }
  1742. break;
  1743. }
  1744. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].TangentKind: {
  1745. for (var k = 0, length_4 = meshAttributeArray.length / stride; k < length_4; ++k) {
  1746. index = k * stride;
  1747. var vertexData = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"].FromArray(meshAttributeArray, index);
  1748. if (this._convertToRightHandedSystem) {
  1749. _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._GetRightHandedVector4FromRef(vertexData);
  1750. }
  1751. _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._NormalizeTangentFromRef(vertexData);
  1752. vertexAttributes.push(vertexData.asArray());
  1753. }
  1754. break;
  1755. }
  1756. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].ColorKind: {
  1757. for (var k = 0, length_5 = meshAttributeArray.length / stride; k < length_5; ++k) {
  1758. index = k * stride;
  1759. var vertexData = stride === 3 ? babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(meshAttributeArray, index) : babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector4"].FromArray(meshAttributeArray, index);
  1760. vertexAttributes.push(vertexData.asArray());
  1761. }
  1762. break;
  1763. }
  1764. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UVKind:
  1765. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UV2Kind: {
  1766. for (var k = 0, length_6 = meshAttributeArray.length / stride; k < length_6; ++k) {
  1767. index = k * stride;
  1768. vertexAttributes.push(this._convertToRightHandedSystem ? [meshAttributeArray[index], meshAttributeArray[index + 1]] : [meshAttributeArray[index], meshAttributeArray[index + 1]]);
  1769. }
  1770. break;
  1771. }
  1772. default: {
  1773. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Unsupported Vertex Buffer Type: " + vertexBufferKind);
  1774. vertexAttributes = [];
  1775. }
  1776. }
  1777. for (var _i = 0, vertexAttributes_1 = vertexAttributes; _i < vertexAttributes_1.length; _i++) {
  1778. var vertexAttribute = vertexAttributes_1[_i];
  1779. for (var _a = 0, vertexAttribute_1 = vertexAttribute; _a < vertexAttribute_1.length; _a++) {
  1780. var component = vertexAttribute_1[_a];
  1781. binaryWriter.setFloat32(component);
  1782. }
  1783. }
  1784. };
  1785. /**
  1786. * Generates glTF json data
  1787. * @param shouldUseGlb Indicates whether the json should be written for a glb file
  1788. * @param glTFPrefix Text to use when prefixing a glTF file
  1789. * @param prettyPrint Indicates whether the json file should be pretty printed (true) or not (false)
  1790. * @returns json data as string
  1791. */
  1792. _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
  1793. var _this = this;
  1794. var buffer = { byteLength: this._totalByteLength };
  1795. var imageName;
  1796. var imageData;
  1797. var bufferView;
  1798. var byteOffset = this._totalByteLength;
  1799. if (buffer.byteLength) {
  1800. this._glTF.buffers = [buffer];
  1801. }
  1802. if (this._nodes && this._nodes.length) {
  1803. this._glTF.nodes = this._nodes;
  1804. }
  1805. if (this._meshes && this._meshes.length) {
  1806. this._glTF.meshes = this._meshes;
  1807. }
  1808. if (this._scenes && this._scenes.length) {
  1809. this._glTF.scenes = this._scenes;
  1810. this._glTF.scene = 0;
  1811. }
  1812. if (this._bufferViews && this._bufferViews.length) {
  1813. this._glTF.bufferViews = this._bufferViews;
  1814. }
  1815. if (this._accessors && this._accessors.length) {
  1816. this._glTF.accessors = this._accessors;
  1817. }
  1818. if (this._animations && this._animations.length) {
  1819. this._glTF.animations = this._animations;
  1820. }
  1821. if (this._materials && this._materials.length) {
  1822. this._glTF.materials = this._materials;
  1823. }
  1824. if (this._textures && this._textures.length) {
  1825. this._glTF.textures = this._textures;
  1826. }
  1827. if (this._samplers && this._samplers.length) {
  1828. this._glTF.samplers = this._samplers;
  1829. }
  1830. if (this._images && this._images.length) {
  1831. if (!shouldUseGlb) {
  1832. this._glTF.images = this._images;
  1833. }
  1834. else {
  1835. this._glTF.images = [];
  1836. this._images.forEach(function (image) {
  1837. if (image.uri) {
  1838. imageData = _this._imageData[image.uri];
  1839. imageName = image.uri.split('.')[0] + " image";
  1840. bufferView = _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._CreateBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
  1841. byteOffset += imageData.data.buffer.byteLength;
  1842. _this._bufferViews.push(bufferView);
  1843. image.bufferView = _this._bufferViews.length - 1;
  1844. image.name = imageName;
  1845. image.mimeType = imageData.mimeType;
  1846. image.uri = undefined;
  1847. if (!_this._glTF.images) {
  1848. _this._glTF.images = [];
  1849. }
  1850. _this._glTF.images.push(image);
  1851. }
  1852. });
  1853. // Replace uri with bufferview and mime type for glb
  1854. buffer.byteLength = byteOffset;
  1855. }
  1856. }
  1857. if (!shouldUseGlb) {
  1858. buffer.uri = glTFPrefix + ".bin";
  1859. }
  1860. var jsonText = prettyPrint ? JSON.stringify(this._glTF, null, 2) : JSON.stringify(this._glTF);
  1861. return jsonText;
  1862. };
  1863. /**
  1864. * Generates data for .gltf and .bin files based on the glTF prefix string
  1865. * @param glTFPrefix Text to use when prefixing a glTF file
  1866. * @returns GLTFData with glTF file data
  1867. */
  1868. _Exporter.prototype._generateGLTFAsync = function (glTFPrefix) {
  1869. var _this = this;
  1870. return this._generateBinaryAsync().then(function (binaryBuffer) {
  1871. _this._extensionsOnExporting();
  1872. var jsonText = _this.generateJSON(false, glTFPrefix, true);
  1873. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  1874. var glTFFileName = glTFPrefix + '.gltf';
  1875. var glTFBinFile = glTFPrefix + '.bin';
  1876. var container = new _glTFData__WEBPACK_IMPORTED_MODULE_3__["GLTFData"]();
  1877. container.glTFFiles[glTFFileName] = jsonText;
  1878. container.glTFFiles[glTFBinFile] = bin;
  1879. if (_this._imageData) {
  1880. for (var image in _this._imageData) {
  1881. container.glTFFiles[image] = new Blob([_this._imageData[image].data], { type: _this._imageData[image].mimeType });
  1882. }
  1883. }
  1884. return container;
  1885. });
  1886. };
  1887. /**
  1888. * Creates a binary buffer for glTF
  1889. * @returns array buffer for binary data
  1890. */
  1891. _Exporter.prototype._generateBinaryAsync = function () {
  1892. var _this = this;
  1893. var binaryWriter = new _BinaryWriter(4);
  1894. return this.createSceneAsync(this._babylonScene, binaryWriter).then(function () {
  1895. if (_this._localEngine) {
  1896. _this._localEngine.dispose();
  1897. }
  1898. return binaryWriter.getArrayBuffer();
  1899. });
  1900. };
  1901. /**
  1902. * Pads the number to a multiple of 4
  1903. * @param num number to pad
  1904. * @returns padded number
  1905. */
  1906. _Exporter.prototype._getPadding = function (num) {
  1907. var remainder = num % 4;
  1908. var padding = remainder === 0 ? remainder : 4 - remainder;
  1909. return padding;
  1910. };
  1911. /**
  1912. * Generates a glb file from the json and binary data
  1913. * Returns an object with the glb file name as the key and data as the value
  1914. * @param glTFPrefix
  1915. * @returns object with glb filename as key and data as value
  1916. */
  1917. _Exporter.prototype._generateGLBAsync = function (glTFPrefix) {
  1918. var _this = this;
  1919. return this._generateBinaryAsync().then(function (binaryBuffer) {
  1920. _this._extensionsOnExporting();
  1921. var jsonText = _this.generateJSON(true);
  1922. var glbFileName = glTFPrefix + '.glb';
  1923. var headerLength = 12;
  1924. var chunkLengthPrefix = 8;
  1925. var jsonLength = jsonText.length;
  1926. var imageByteLength = 0;
  1927. for (var key in _this._imageData) {
  1928. imageByteLength += _this._imageData[key].data.byteLength;
  1929. }
  1930. var jsonPadding = _this._getPadding(jsonLength);
  1931. var binPadding = _this._getPadding(binaryBuffer.byteLength);
  1932. var imagePadding = _this._getPadding(imageByteLength);
  1933. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
  1934. //header
  1935. var headerBuffer = new ArrayBuffer(headerLength);
  1936. var headerBufferView = new DataView(headerBuffer);
  1937. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  1938. headerBufferView.setUint32(4, 2, true); // version
  1939. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  1940. //json chunk
  1941. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  1942. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  1943. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  1944. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  1945. //json chunk bytes
  1946. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  1947. for (var i = 0; i < jsonLength; ++i) {
  1948. jsonData[i] = jsonText.charCodeAt(i);
  1949. }
  1950. //json padding
  1951. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  1952. for (var i = 0; i < jsonPadding; ++i) {
  1953. jsonPaddingView[i] = 0x20;
  1954. }
  1955. //binary chunk
  1956. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  1957. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  1958. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
  1959. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  1960. // binary padding
  1961. var binPaddingBuffer = new ArrayBuffer(binPadding);
  1962. var binPaddingView = new Uint8Array(binPaddingBuffer);
  1963. for (var i = 0; i < binPadding; ++i) {
  1964. binPaddingView[i] = 0;
  1965. }
  1966. var imagePaddingBuffer = new ArrayBuffer(imagePadding);
  1967. var imagePaddingView = new Uint8Array(imagePaddingBuffer);
  1968. for (var i = 0; i < imagePadding; ++i) {
  1969. imagePaddingView[i] = 0;
  1970. }
  1971. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  1972. // binary data
  1973. for (var key in _this._imageData) {
  1974. glbData.push(_this._imageData[key].data.buffer);
  1975. }
  1976. glbData.push(binPaddingBuffer);
  1977. glbData.push(imagePaddingBuffer);
  1978. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  1979. var container = new _glTFData__WEBPACK_IMPORTED_MODULE_3__["GLTFData"]();
  1980. container.glTFFiles[glbFileName] = glbFile;
  1981. if (_this._localEngine != null) {
  1982. _this._localEngine.dispose();
  1983. }
  1984. return container;
  1985. });
  1986. };
  1987. /**
  1988. * Sets the TRS for each node
  1989. * @param node glTF Node for storing the transformation data
  1990. * @param babylonTransformNode Babylon mesh used as the source for the transformation data
  1991. */
  1992. _Exporter.prototype.setNodeTransformation = function (node, babylonTransformNode) {
  1993. if (!babylonTransformNode.getPivotPoint().equalsToFloats(0, 0, 0)) {
  1994. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Pivot points are not supported in the glTF serializer");
  1995. }
  1996. if (!babylonTransformNode.position.equalsToFloats(0, 0, 0)) {
  1997. node.translation = this._convertToRightHandedSystem ? _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._GetRightHandedPositionVector3(babylonTransformNode.position).asArray() : babylonTransformNode.position.asArray();
  1998. }
  1999. if (!babylonTransformNode.scaling.equalsToFloats(1, 1, 1)) {
  2000. node.scale = babylonTransformNode.scaling.asArray();
  2001. }
  2002. var rotationQuaternion = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].RotationYawPitchRoll(babylonTransformNode.rotation.y, babylonTransformNode.rotation.x, babylonTransformNode.rotation.z);
  2003. if (babylonTransformNode.rotationQuaternion) {
  2004. rotationQuaternion.multiplyInPlace(babylonTransformNode.rotationQuaternion);
  2005. }
  2006. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  2007. if (this._convertToRightHandedSystem) {
  2008. _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._GetRightHandedQuaternionFromRef(rotationQuaternion);
  2009. }
  2010. node.rotation = rotationQuaternion.normalize().asArray();
  2011. }
  2012. };
  2013. _Exporter.prototype.getVertexBufferFromMesh = function (attributeKind, bufferMesh) {
  2014. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  2015. var vertexBuffer = bufferMesh.getVertexBuffer(attributeKind);
  2016. if (vertexBuffer) {
  2017. return vertexBuffer;
  2018. }
  2019. }
  2020. return null;
  2021. };
  2022. /**
  2023. * Creates a bufferview based on the vertices type for the Babylon mesh
  2024. * @param kind Indicates the type of vertices data
  2025. * @param babylonTransformNode The Babylon mesh to get the vertices data from
  2026. * @param binaryWriter The buffer to write the bufferview data to
  2027. */
  2028. _Exporter.prototype.createBufferViewKind = function (kind, babylonTransformNode, binaryWriter, byteStride) {
  2029. var bufferMesh = babylonTransformNode instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Mesh"] ?
  2030. babylonTransformNode : babylonTransformNode instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["InstancedMesh"] ?
  2031. babylonTransformNode.sourceMesh : null;
  2032. if (bufferMesh) {
  2033. var vertexData = bufferMesh.getVerticesData(kind);
  2034. if (vertexData) {
  2035. var byteLength = vertexData.length * 4;
  2036. var bufferView = _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, byteStride, kind + " - " + bufferMesh.name);
  2037. this._bufferViews.push(bufferView);
  2038. this.writeAttributeData(kind, vertexData, byteStride, binaryWriter);
  2039. }
  2040. }
  2041. };
  2042. /**
  2043. * The primitive mode of the Babylon mesh
  2044. * @param babylonMesh The BabylonJS mesh
  2045. */
  2046. _Exporter.prototype.getMeshPrimitiveMode = function (babylonMesh) {
  2047. if (babylonMesh instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["LinesMesh"]) {
  2048. return babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].LineListDrawMode;
  2049. }
  2050. return babylonMesh.material ? babylonMesh.material.fillMode : babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].TriangleFillMode;
  2051. };
  2052. /**
  2053. * Sets the primitive mode of the glTF mesh primitive
  2054. * @param meshPrimitive glTF mesh primitive
  2055. * @param primitiveMode The primitive mode
  2056. */
  2057. _Exporter.prototype.setPrimitiveMode = function (meshPrimitive, primitiveMode) {
  2058. switch (primitiveMode) {
  2059. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].TriangleFillMode: {
  2060. // glTF defaults to using Triangle Mode
  2061. break;
  2062. }
  2063. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].TriangleStripDrawMode: {
  2064. meshPrimitive.mode = 5 /* TRIANGLE_STRIP */;
  2065. break;
  2066. }
  2067. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].TriangleFanDrawMode: {
  2068. meshPrimitive.mode = 6 /* TRIANGLE_FAN */;
  2069. break;
  2070. }
  2071. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].PointListDrawMode: {
  2072. meshPrimitive.mode = 0 /* POINTS */;
  2073. }
  2074. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].PointFillMode: {
  2075. meshPrimitive.mode = 0 /* POINTS */;
  2076. break;
  2077. }
  2078. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].LineLoopDrawMode: {
  2079. meshPrimitive.mode = 2 /* LINE_LOOP */;
  2080. break;
  2081. }
  2082. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].LineListDrawMode: {
  2083. meshPrimitive.mode = 1 /* LINES */;
  2084. break;
  2085. }
  2086. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].LineStripDrawMode: {
  2087. meshPrimitive.mode = 3 /* LINE_STRIP */;
  2088. break;
  2089. }
  2090. }
  2091. };
  2092. /**
  2093. * Sets the vertex attribute accessor based of the glTF mesh primitive
  2094. * @param meshPrimitive glTF mesh primitive
  2095. * @param attributeKind vertex attribute
  2096. * @returns boolean specifying if uv coordinates are present
  2097. */
  2098. _Exporter.prototype.setAttributeKind = function (meshPrimitive, attributeKind) {
  2099. switch (attributeKind) {
  2100. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].PositionKind: {
  2101. meshPrimitive.attributes.POSITION = this._accessors.length - 1;
  2102. break;
  2103. }
  2104. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].NormalKind: {
  2105. meshPrimitive.attributes.NORMAL = this._accessors.length - 1;
  2106. break;
  2107. }
  2108. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].ColorKind: {
  2109. meshPrimitive.attributes.COLOR_0 = this._accessors.length - 1;
  2110. break;
  2111. }
  2112. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].TangentKind: {
  2113. meshPrimitive.attributes.TANGENT = this._accessors.length - 1;
  2114. break;
  2115. }
  2116. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UVKind: {
  2117. meshPrimitive.attributes.TEXCOORD_0 = this._accessors.length - 1;
  2118. break;
  2119. }
  2120. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UV2Kind: {
  2121. meshPrimitive.attributes.TEXCOORD_1 = this._accessors.length - 1;
  2122. break;
  2123. }
  2124. default: {
  2125. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Unsupported Vertex Buffer Type: " + attributeKind);
  2126. }
  2127. }
  2128. };
  2129. /**
  2130. * Sets data for the primitive attributes of each submesh
  2131. * @param mesh glTF Mesh object to store the primitive attribute information
  2132. * @param babylonTransformNode Babylon mesh to get the primitive attribute data from
  2133. * @param binaryWriter Buffer to write the attribute data to
  2134. */
  2135. _Exporter.prototype.setPrimitiveAttributesAsync = function (mesh, babylonTransformNode, binaryWriter) {
  2136. var promises = [];
  2137. var bufferMesh = null;
  2138. var bufferView;
  2139. var uvCoordsPresent;
  2140. var minMax;
  2141. if (babylonTransformNode instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Mesh"]) {
  2142. bufferMesh = babylonTransformNode;
  2143. }
  2144. else if (babylonTransformNode instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["InstancedMesh"]) {
  2145. bufferMesh = babylonTransformNode.sourceMesh;
  2146. }
  2147. var attributeData = [
  2148. { kind: babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].PositionKind, accessorType: "VEC3" /* VEC3 */, byteStride: 12 },
  2149. { kind: babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].NormalKind, accessorType: "VEC3" /* VEC3 */, byteStride: 12 },
  2150. { kind: babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].ColorKind, accessorType: "VEC4" /* VEC4 */, byteStride: 16 },
  2151. { kind: babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].TangentKind, accessorType: "VEC4" /* VEC4 */, byteStride: 16 },
  2152. { kind: babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UVKind, accessorType: "VEC2" /* VEC2 */, byteStride: 8 },
  2153. { kind: babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UV2Kind, accessorType: "VEC2" /* VEC2 */, byteStride: 8 },
  2154. ];
  2155. if (bufferMesh) {
  2156. var indexBufferViewIndex = null;
  2157. var primitiveMode = this.getMeshPrimitiveMode(bufferMesh);
  2158. var vertexAttributeBufferViews = {};
  2159. // For each BabylonMesh, create bufferviews for each 'kind'
  2160. for (var _i = 0, attributeData_1 = attributeData; _i < attributeData_1.length; _i++) {
  2161. var attribute = attributeData_1[_i];
  2162. var attributeKind = attribute.kind;
  2163. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  2164. var vertexBuffer = this.getVertexBufferFromMesh(attributeKind, bufferMesh);
  2165. attribute.byteStride = vertexBuffer ? vertexBuffer.getSize() * 4 : babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].DeduceStride(attributeKind) * 4;
  2166. if (attribute.byteStride === 12) {
  2167. attribute.accessorType = "VEC3" /* VEC3 */;
  2168. }
  2169. this.createBufferViewKind(attributeKind, babylonTransformNode, binaryWriter, attribute.byteStride);
  2170. attribute.bufferViewIndex = this._bufferViews.length - 1;
  2171. vertexAttributeBufferViews[attributeKind] = attribute.bufferViewIndex;
  2172. }
  2173. }
  2174. if (bufferMesh.getTotalIndices()) {
  2175. var indices = bufferMesh.getIndices();
  2176. if (indices) {
  2177. var byteLength = indices.length * 4;
  2178. bufferView = _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, "Indices - " + bufferMesh.name);
  2179. this._bufferViews.push(bufferView);
  2180. indexBufferViewIndex = this._bufferViews.length - 1;
  2181. for (var k = 0, length_7 = indices.length; k < length_7; ++k) {
  2182. binaryWriter.setUInt32(indices[k]);
  2183. }
  2184. }
  2185. }
  2186. if (bufferMesh.subMeshes) {
  2187. // go through all mesh primitives (submeshes)
  2188. for (var _a = 0, _b = bufferMesh.subMeshes; _a < _b.length; _a++) {
  2189. var submesh = _b[_a];
  2190. uvCoordsPresent = false;
  2191. var babylonMaterial = submesh.getMaterial() || bufferMesh.getScene().defaultMaterial;
  2192. var materialIndex = null;
  2193. if (babylonMaterial) {
  2194. if (bufferMesh instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["LinesMesh"]) {
  2195. // get the color from the lines mesh and set it in the material
  2196. var material = {
  2197. name: bufferMesh.name + ' material'
  2198. };
  2199. if (!bufferMesh.color.equals(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].White()) || bufferMesh.alpha < 1) {
  2200. material.pbrMetallicRoughness = {
  2201. baseColorFactor: bufferMesh.color.asArray().concat([bufferMesh.alpha])
  2202. };
  2203. }
  2204. this._materials.push(material);
  2205. materialIndex = this._materials.length - 1;
  2206. }
  2207. else if (babylonMaterial instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["MultiMaterial"]) {
  2208. var subMaterial = babylonMaterial.subMaterials[submesh.materialIndex];
  2209. if (subMaterial) {
  2210. babylonMaterial = subMaterial;
  2211. materialIndex = this._materialMap[babylonMaterial.uniqueId];
  2212. }
  2213. }
  2214. else {
  2215. materialIndex = this._materialMap[babylonMaterial.uniqueId];
  2216. }
  2217. }
  2218. var glTFMaterial = materialIndex != null ? this._materials[materialIndex] : null;
  2219. var meshPrimitive = { attributes: {} };
  2220. this.setPrimitiveMode(meshPrimitive, primitiveMode);
  2221. for (var _c = 0, attributeData_2 = attributeData; _c < attributeData_2.length; _c++) {
  2222. var attribute = attributeData_2[_c];
  2223. var attributeKind = attribute.kind;
  2224. if (attributeKind === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UVKind || attributeKind === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].UV2Kind) {
  2225. if (glTFMaterial && !this._glTFMaterialExporter._hasTexturesPresent(glTFMaterial)) {
  2226. continue;
  2227. }
  2228. }
  2229. var vertexData = bufferMesh.getVerticesData(attributeKind);
  2230. if (vertexData) {
  2231. var vertexBuffer = this.getVertexBufferFromMesh(attributeKind, bufferMesh);
  2232. if (vertexBuffer) {
  2233. var stride = vertexBuffer.getSize();
  2234. var bufferViewIndex = attribute.bufferViewIndex;
  2235. if (bufferViewIndex != undefined) { // check to see if bufferviewindex has a numeric value assigned.
  2236. minMax = { min: null, max: null };
  2237. if (attributeKind == babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].PositionKind) {
  2238. minMax = _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._CalculateMinMaxPositions(vertexData, 0, vertexData.length / stride, this._convertToRightHandedSystem);
  2239. }
  2240. var accessor = _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._CreateAccessor(bufferViewIndex, attributeKind + " - " + babylonTransformNode.name, attribute.accessorType, 5126 /* FLOAT */, vertexData.length / stride, 0, minMax.min, minMax.max);
  2241. this._accessors.push(accessor);
  2242. this.setAttributeKind(meshPrimitive, attributeKind);
  2243. if (meshPrimitive.attributes.TEXCOORD_0 != null || meshPrimitive.attributes.TEXCOORD_1 != null) {
  2244. uvCoordsPresent = true;
  2245. }
  2246. }
  2247. }
  2248. }
  2249. }
  2250. if (indexBufferViewIndex) {
  2251. // Create accessor
  2252. var accessor = _glTFUtilities__WEBPACK_IMPORTED_MODULE_2__["_GLTFUtilities"]._CreateAccessor(indexBufferViewIndex, "indices - " + babylonTransformNode.name, "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4, null, null);
  2253. this._accessors.push(accessor);
  2254. meshPrimitive.indices = this._accessors.length - 1;
  2255. }
  2256. if (materialIndex != null && Object.keys(meshPrimitive.attributes).length > 0) {
  2257. var sideOrientation = babylonMaterial.sideOrientation;
  2258. // Only reverse the winding if we have a clockwise winding
  2259. if (sideOrientation === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Material"].ClockWiseSideOrientation) {
  2260. var byteOffset = indexBufferViewIndex != null ? this._bufferViews[indexBufferViewIndex].byteOffset : null;
  2261. if (byteOffset == null) {
  2262. byteOffset = 0;
  2263. }
  2264. var babylonIndices = null;
  2265. if (indexBufferViewIndex != null) {
  2266. babylonIndices = bufferMesh.getIndices();
  2267. }
  2268. if (babylonIndices) {
  2269. this.reorderIndicesBasedOnPrimitiveMode(submesh, primitiveMode, babylonIndices, byteOffset, binaryWriter);
  2270. }
  2271. else {
  2272. for (var _d = 0, attributeData_3 = attributeData; _d < attributeData_3.length; _d++) {
  2273. var attribute = attributeData_3[_d];
  2274. var vertexData = bufferMesh.getVerticesData(attribute.kind);
  2275. if (vertexData) {
  2276. var byteOffset_1 = this._bufferViews[vertexAttributeBufferViews[attribute.kind]].byteOffset;
  2277. if (!byteOffset_1) {
  2278. byteOffset_1 = 0;
  2279. }
  2280. this.reorderVertexAttributeDataBasedOnPrimitiveMode(submesh, primitiveMode, sideOrientation, attribute.kind, vertexData, byteOffset_1, binaryWriter);
  2281. }
  2282. }
  2283. }
  2284. }
  2285. if (!uvCoordsPresent && this._glTFMaterialExporter._hasTexturesPresent(this._materials[materialIndex])) {
  2286. var newMat = this._glTFMaterialExporter._stripTexturesFromMaterial(this._materials[materialIndex]);
  2287. this._materials.push(newMat);
  2288. materialIndex = this._materials.length - 1;
  2289. }
  2290. meshPrimitive.material = materialIndex;
  2291. }
  2292. mesh.primitives.push(meshPrimitive);
  2293. var promise = this._extensionsPostExportMeshPrimitiveAsync("postExport", meshPrimitive, submesh, binaryWriter);
  2294. if (promise) {
  2295. promises.push();
  2296. }
  2297. }
  2298. }
  2299. }
  2300. return Promise.all(promises).then(function () {
  2301. /* do nothing */
  2302. });
  2303. };
  2304. /**
  2305. * Creates a glTF scene based on the array of meshes
  2306. * Returns the the total byte offset
  2307. * @param babylonScene Babylon scene to get the mesh data from
  2308. * @param binaryWriter Buffer to write binary data to
  2309. */
  2310. _Exporter.prototype.createSceneAsync = function (babylonScene, binaryWriter) {
  2311. var _this = this;
  2312. var scene = { nodes: [] };
  2313. var glTFNodeIndex;
  2314. var glTFNode;
  2315. var directDescendents;
  2316. var nodes = babylonScene.transformNodes.concat(babylonScene.meshes, babylonScene.lights);
  2317. return this._glTFMaterialExporter._convertMaterialsToGLTFAsync(babylonScene.materials, "image/png" /* PNG */, true).then(function () {
  2318. return _this.createNodeMapAndAnimationsAsync(babylonScene, nodes, _this._shouldExportNode, binaryWriter).then(function (nodeMap) {
  2319. _this._nodeMap = nodeMap;
  2320. _this._totalByteLength = binaryWriter.getByteOffset();
  2321. if (_this._totalByteLength == undefined) {
  2322. throw new Error("undefined byte length!");
  2323. }
  2324. // Build Hierarchy with the node map.
  2325. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  2326. var babylonNode = nodes_1[_i];
  2327. glTFNodeIndex = _this._nodeMap[babylonNode.uniqueId];
  2328. if (glTFNodeIndex !== undefined) {
  2329. glTFNode = _this._nodes[glTFNodeIndex];
  2330. if (!babylonNode.parent) {
  2331. if (!_this._shouldExportNode(babylonNode)) {
  2332. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Log("Omitting " + babylonNode.name + " from scene.");
  2333. }
  2334. else {
  2335. if (_this._convertToRightHandedSystem) {
  2336. if (glTFNode.translation) {
  2337. glTFNode.translation[2] *= -1;
  2338. glTFNode.translation[0] *= -1;
  2339. }
  2340. glTFNode.rotation = glTFNode.rotation ? babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray([0, 1, 0, 0]).multiply(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray(glTFNode.rotation)).asArray() : (babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Quaternion"].FromArray([0, 1, 0, 0])).asArray();
  2341. }
  2342. scene.nodes.push(glTFNodeIndex);
  2343. }
  2344. }
  2345. directDescendents = babylonNode.getDescendants(true);
  2346. if (!glTFNode.children && directDescendents && directDescendents.length) {
  2347. var children = [];
  2348. for (var _a = 0, directDescendents_1 = directDescendents; _a < directDescendents_1.length; _a++) {
  2349. var descendent = directDescendents_1[_a];
  2350. if (_this._nodeMap[descendent.uniqueId] != null) {
  2351. children.push(_this._nodeMap[descendent.uniqueId]);
  2352. }
  2353. }
  2354. if (children.length) {
  2355. glTFNode.children = children;
  2356. }
  2357. }
  2358. }
  2359. }
  2360. if (scene.nodes.length) {
  2361. _this._scenes.push(scene);
  2362. }
  2363. });
  2364. });
  2365. };
  2366. /**
  2367. * Creates a mapping of Node unique id to node index and handles animations
  2368. * @param babylonScene Babylon Scene
  2369. * @param nodes Babylon transform nodes
  2370. * @param shouldExportNode Callback specifying if a transform node should be exported
  2371. * @param binaryWriter Buffer to write binary data to
  2372. * @returns Node mapping of unique id to index
  2373. */
  2374. _Exporter.prototype.createNodeMapAndAnimationsAsync = function (babylonScene, nodes, shouldExportNode, binaryWriter) {
  2375. var _this = this;
  2376. var promiseChain = Promise.resolve();
  2377. var nodeMap = {};
  2378. var nodeIndex;
  2379. var runtimeGLTFAnimation = {
  2380. name: 'runtime animations',
  2381. channels: [],
  2382. samplers: []
  2383. };
  2384. var idleGLTFAnimations = [];
  2385. var _loop_1 = function (babylonNode) {
  2386. if (shouldExportNode(babylonNode)) {
  2387. promiseChain = promiseChain.then(function () {
  2388. return _this.createNodeAsync(babylonNode, binaryWriter).then(function (node) {
  2389. var promise = _this._extensionsPostExportNodeAsync("createNodeAsync", node, babylonNode);
  2390. if (promise == null) {
  2391. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Not exporting node " + babylonNode.name);
  2392. return Promise.resolve();
  2393. }
  2394. else {
  2395. return promise.then(function (node) {
  2396. var directDescendents = babylonNode.getDescendants(true, function (node) { return (node instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Node"]); });
  2397. if (directDescendents.length || node.mesh != null || (node.extensions)) {
  2398. _this._nodes.push(node);
  2399. nodeIndex = _this._nodes.length - 1;
  2400. nodeMap[babylonNode.uniqueId] = nodeIndex;
  2401. }
  2402. if (!babylonScene.animationGroups.length && babylonNode.animations.length) {
  2403. _glTFAnimation__WEBPACK_IMPORTED_MODULE_4__["_GLTFAnimation"]._CreateNodeAnimationFromNodeAnimations(babylonNode, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, _this._nodes, binaryWriter, _this._bufferViews, _this._accessors, _this._convertToRightHandedSystem, _this._animationSampleRate);
  2404. }
  2405. });
  2406. }
  2407. });
  2408. });
  2409. }
  2410. else {
  2411. "Excluding node " + babylonNode.name;
  2412. }
  2413. };
  2414. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  2415. var babylonNode = nodes_2[_i];
  2416. _loop_1(babylonNode);
  2417. }
  2418. return promiseChain.then(function () {
  2419. if (runtimeGLTFAnimation.channels.length && runtimeGLTFAnimation.samplers.length) {
  2420. _this._animations.push(runtimeGLTFAnimation);
  2421. }
  2422. idleGLTFAnimations.forEach(function (idleGLTFAnimation) {
  2423. if (idleGLTFAnimation.channels.length && idleGLTFAnimation.samplers.length) {
  2424. _this._animations.push(idleGLTFAnimation);
  2425. }
  2426. });
  2427. if (babylonScene.animationGroups.length) {
  2428. _glTFAnimation__WEBPACK_IMPORTED_MODULE_4__["_GLTFAnimation"]._CreateNodeAnimationFromAnimationGroups(babylonScene, _this._animations, nodeMap, _this._nodes, binaryWriter, _this._bufferViews, _this._accessors, _this._convertToRightHandedSystem, _this._animationSampleRate);
  2429. }
  2430. return nodeMap;
  2431. });
  2432. };
  2433. /**
  2434. * Creates a glTF node from a Babylon mesh
  2435. * @param babylonMesh Source Babylon mesh
  2436. * @param binaryWriter Buffer for storing geometry data
  2437. * @returns glTF node
  2438. */
  2439. _Exporter.prototype.createNodeAsync = function (babylonNode, binaryWriter) {
  2440. var _this = this;
  2441. return Promise.resolve().then(function () {
  2442. // create node to hold translation/rotation/scale and the mesh
  2443. var node = {};
  2444. // create mesh
  2445. var mesh = { primitives: [] };
  2446. if (babylonNode.name) {
  2447. node.name = babylonNode.name;
  2448. }
  2449. if (babylonNode instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["TransformNode"]) {
  2450. // Set transformation
  2451. _this.setNodeTransformation(node, babylonNode);
  2452. return _this.setPrimitiveAttributesAsync(mesh, babylonNode, binaryWriter).then(function () {
  2453. if (mesh.primitives.length) {
  2454. _this._meshes.push(mesh);
  2455. node.mesh = _this._meshes.length - 1;
  2456. }
  2457. return node;
  2458. });
  2459. }
  2460. else {
  2461. return node;
  2462. }
  2463. });
  2464. };
  2465. _Exporter._ExtensionNames = new Array();
  2466. _Exporter._ExtensionFactories = {};
  2467. return _Exporter;
  2468. }());
  2469. /**
  2470. * @hidden
  2471. *
  2472. * Stores glTF binary data. If the array buffer byte length is exceeded, it doubles in size dynamically
  2473. */
  2474. var _BinaryWriter = /** @class */ (function () {
  2475. /**
  2476. * Initialize binary writer with an initial byte length
  2477. * @param byteLength Initial byte length of the array buffer
  2478. */
  2479. function _BinaryWriter(byteLength) {
  2480. this._arrayBuffer = new ArrayBuffer(byteLength);
  2481. this._dataView = new DataView(this._arrayBuffer);
  2482. this._byteOffset = 0;
  2483. }
  2484. /**
  2485. * Resize the array buffer to the specified byte length
  2486. * @param byteLength
  2487. */
  2488. _BinaryWriter.prototype.resizeBuffer = function (byteLength) {
  2489. var newBuffer = new ArrayBuffer(byteLength);
  2490. var oldUint8Array = new Uint8Array(this._arrayBuffer);
  2491. var newUint8Array = new Uint8Array(newBuffer);
  2492. for (var i = 0, length_8 = newUint8Array.byteLength; i < length_8; ++i) {
  2493. newUint8Array[i] = oldUint8Array[i];
  2494. }
  2495. this._arrayBuffer = newBuffer;
  2496. this._dataView = new DataView(this._arrayBuffer);
  2497. return newBuffer;
  2498. };
  2499. /**
  2500. * Get an array buffer with the length of the byte offset
  2501. * @returns ArrayBuffer resized to the byte offset
  2502. */
  2503. _BinaryWriter.prototype.getArrayBuffer = function () {
  2504. return this.resizeBuffer(this.getByteOffset());
  2505. };
  2506. /**
  2507. * Get the byte offset of the array buffer
  2508. * @returns byte offset
  2509. */
  2510. _BinaryWriter.prototype.getByteOffset = function () {
  2511. if (this._byteOffset == undefined) {
  2512. throw new Error("Byte offset is undefined!");
  2513. }
  2514. return this._byteOffset;
  2515. };
  2516. /**
  2517. * Stores an UInt8 in the array buffer
  2518. * @param entry
  2519. * @param byteOffset If defined, specifies where to set the value as an offset.
  2520. */
  2521. _BinaryWriter.prototype.setUInt8 = function (entry, byteOffset) {
  2522. if (byteOffset != null) {
  2523. if (byteOffset < this._byteOffset) {
  2524. this._dataView.setUint8(byteOffset, entry);
  2525. }
  2526. else {
  2527. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  2528. }
  2529. }
  2530. else {
  2531. if (this._byteOffset + 1 > this._arrayBuffer.byteLength) {
  2532. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  2533. }
  2534. this._dataView.setUint8(this._byteOffset++, entry);
  2535. }
  2536. };
  2537. /**
  2538. * Gets an UInt32 in the array buffer
  2539. * @param entry
  2540. * @param byteOffset If defined, specifies where to set the value as an offset.
  2541. */
  2542. _BinaryWriter.prototype.getUInt32 = function (byteOffset) {
  2543. if (byteOffset < this._byteOffset) {
  2544. return this._dataView.getUint32(byteOffset, true);
  2545. }
  2546. else {
  2547. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  2548. throw new Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  2549. }
  2550. };
  2551. _BinaryWriter.prototype.getVector3Float32FromRef = function (vector3, byteOffset) {
  2552. if (byteOffset + 8 > this._byteOffset) {
  2553. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  2554. }
  2555. else {
  2556. vector3.x = this._dataView.getFloat32(byteOffset, true);
  2557. vector3.y = this._dataView.getFloat32(byteOffset + 4, true);
  2558. vector3.z = this._dataView.getFloat32(byteOffset + 8, true);
  2559. }
  2560. };
  2561. _BinaryWriter.prototype.setVector3Float32FromRef = function (vector3, byteOffset) {
  2562. if (byteOffset + 8 > this._byteOffset) {
  2563. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  2564. }
  2565. else {
  2566. this._dataView.setFloat32(byteOffset, vector3.x, true);
  2567. this._dataView.setFloat32(byteOffset + 4, vector3.y, true);
  2568. this._dataView.setFloat32(byteOffset + 8, vector3.z, true);
  2569. }
  2570. };
  2571. _BinaryWriter.prototype.getVector4Float32FromRef = function (vector4, byteOffset) {
  2572. if (byteOffset + 12 > this._byteOffset) {
  2573. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  2574. }
  2575. else {
  2576. vector4.x = this._dataView.getFloat32(byteOffset, true);
  2577. vector4.y = this._dataView.getFloat32(byteOffset + 4, true);
  2578. vector4.z = this._dataView.getFloat32(byteOffset + 8, true);
  2579. vector4.w = this._dataView.getFloat32(byteOffset + 12, true);
  2580. }
  2581. };
  2582. _BinaryWriter.prototype.setVector4Float32FromRef = function (vector4, byteOffset) {
  2583. if (byteOffset + 12 > this._byteOffset) {
  2584. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  2585. }
  2586. else {
  2587. this._dataView.setFloat32(byteOffset, vector4.x, true);
  2588. this._dataView.setFloat32(byteOffset + 4, vector4.y, true);
  2589. this._dataView.setFloat32(byteOffset + 8, vector4.z, true);
  2590. this._dataView.setFloat32(byteOffset + 12, vector4.w, true);
  2591. }
  2592. };
  2593. /**
  2594. * Stores a Float32 in the array buffer
  2595. * @param entry
  2596. */
  2597. _BinaryWriter.prototype.setFloat32 = function (entry, byteOffset) {
  2598. if (isNaN(entry)) {
  2599. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error('Invalid data being written!');
  2600. }
  2601. if (byteOffset != null) {
  2602. if (byteOffset < this._byteOffset) {
  2603. this._dataView.setFloat32(byteOffset, entry, true);
  2604. }
  2605. else {
  2606. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error('BinaryWriter: byteoffset is greater than the current binary length!');
  2607. }
  2608. }
  2609. if (this._byteOffset + 4 > this._arrayBuffer.byteLength) {
  2610. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  2611. }
  2612. this._dataView.setFloat32(this._byteOffset, entry, true);
  2613. this._byteOffset += 4;
  2614. };
  2615. /**
  2616. * Stores an UInt32 in the array buffer
  2617. * @param entry
  2618. * @param byteOffset If defined, specifies where to set the value as an offset.
  2619. */
  2620. _BinaryWriter.prototype.setUInt32 = function (entry, byteOffset) {
  2621. if (byteOffset != null) {
  2622. if (byteOffset < this._byteOffset) {
  2623. this._dataView.setUint32(byteOffset, entry, true);
  2624. }
  2625. else {
  2626. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  2627. }
  2628. }
  2629. else {
  2630. if (this._byteOffset + 4 > this._arrayBuffer.byteLength) {
  2631. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  2632. }
  2633. this._dataView.setUint32(this._byteOffset, entry, true);
  2634. this._byteOffset += 4;
  2635. }
  2636. };
  2637. return _BinaryWriter;
  2638. }());
  2639. /***/ }),
  2640. /***/ "./glTF/2.0/glTFExporterExtension.ts":
  2641. /*!*******************************************!*\
  2642. !*** ./glTF/2.0/glTFExporterExtension.ts ***!
  2643. \*******************************************/
  2644. /*! exports provided: __IGLTFExporterExtensionV2 */
  2645. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  2646. "use strict";
  2647. __webpack_require__.r(__webpack_exports__);
  2648. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__IGLTFExporterExtensionV2", function() { return __IGLTFExporterExtensionV2; });
  2649. /** @hidden */
  2650. var __IGLTFExporterExtensionV2 = 0; // I am here to allow dts to be created
  2651. /***/ }),
  2652. /***/ "./glTF/2.0/glTFMaterialExporter.ts":
  2653. /*!******************************************!*\
  2654. !*** ./glTF/2.0/glTFMaterialExporter.ts ***!
  2655. \******************************************/
  2656. /*! exports provided: _GLTFMaterialExporter */
  2657. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  2658. "use strict";
  2659. __webpack_require__.r(__webpack_exports__);
  2660. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_GLTFMaterialExporter", function() { return _GLTFMaterialExporter; });
  2661. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Maths/math");
  2662. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__);
  2663. /**
  2664. * Utility methods for working with glTF material conversion properties. This class should only be used internally
  2665. * @hidden
  2666. */
  2667. var _GLTFMaterialExporter = /** @class */ (function () {
  2668. function _GLTFMaterialExporter(exporter) {
  2669. /**
  2670. * Mapping to store textures
  2671. */
  2672. this._textureMap = {};
  2673. this._textureMap = {};
  2674. this._exporter = exporter;
  2675. }
  2676. /**
  2677. * Specifies if two colors are approximately equal in value
  2678. * @param color1 first color to compare to
  2679. * @param color2 second color to compare to
  2680. * @param epsilon threshold value
  2681. */
  2682. _GLTFMaterialExporter.FuzzyEquals = function (color1, color2, epsilon) {
  2683. return babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Scalar"].WithinEpsilon(color1.r, color2.r, epsilon) &&
  2684. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Scalar"].WithinEpsilon(color1.g, color2.g, epsilon) &&
  2685. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Scalar"].WithinEpsilon(color1.b, color2.b, epsilon);
  2686. };
  2687. /**
  2688. * Gets the materials from a Babylon scene and converts them to glTF materials
  2689. * @param scene babylonjs scene
  2690. * @param mimeType texture mime type
  2691. * @param images array of images
  2692. * @param textures array of textures
  2693. * @param materials array of materials
  2694. * @param imageData mapping of texture names to base64 textures
  2695. * @param hasTextureCoords specifies if texture coordinates are present on the material
  2696. */
  2697. _GLTFMaterialExporter.prototype._convertMaterialsToGLTFAsync = function (babylonMaterials, mimeType, hasTextureCoords) {
  2698. var promises = [];
  2699. for (var _i = 0, babylonMaterials_1 = babylonMaterials; _i < babylonMaterials_1.length; _i++) {
  2700. var babylonMaterial = babylonMaterials_1[_i];
  2701. if (babylonMaterial instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["StandardMaterial"]) {
  2702. promises.push(this._convertStandardMaterialAsync(babylonMaterial, mimeType, hasTextureCoords));
  2703. }
  2704. else if (babylonMaterial instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["PBRMetallicRoughnessMaterial"]) {
  2705. promises.push(this._convertPBRMetallicRoughnessMaterialAsync(babylonMaterial, mimeType, hasTextureCoords));
  2706. }
  2707. else if (babylonMaterial instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["PBRMaterial"]) {
  2708. promises.push(this._convertPBRMaterialAsync(babylonMaterial, mimeType, hasTextureCoords));
  2709. }
  2710. else {
  2711. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Unsupported material type: " + babylonMaterial.name);
  2712. }
  2713. }
  2714. return Promise.all(promises).then(function () { });
  2715. };
  2716. /**
  2717. * Makes a copy of the glTF material without the texture parameters
  2718. * @param originalMaterial original glTF material
  2719. * @returns glTF material without texture parameters
  2720. */
  2721. _GLTFMaterialExporter.prototype._stripTexturesFromMaterial = function (originalMaterial) {
  2722. var newMaterial = {};
  2723. if (originalMaterial) {
  2724. newMaterial.name = originalMaterial.name;
  2725. newMaterial.doubleSided = originalMaterial.doubleSided;
  2726. newMaterial.alphaMode = originalMaterial.alphaMode;
  2727. newMaterial.alphaCutoff = originalMaterial.alphaCutoff;
  2728. newMaterial.emissiveFactor = originalMaterial.emissiveFactor;
  2729. var originalPBRMetallicRoughness = originalMaterial.pbrMetallicRoughness;
  2730. if (originalPBRMetallicRoughness) {
  2731. newMaterial.pbrMetallicRoughness = {};
  2732. newMaterial.pbrMetallicRoughness.baseColorFactor = originalPBRMetallicRoughness.baseColorFactor;
  2733. newMaterial.pbrMetallicRoughness.metallicFactor = originalPBRMetallicRoughness.metallicFactor;
  2734. newMaterial.pbrMetallicRoughness.roughnessFactor = originalPBRMetallicRoughness.roughnessFactor;
  2735. }
  2736. }
  2737. return newMaterial;
  2738. };
  2739. /**
  2740. * Specifies if the material has any texture parameters present
  2741. * @param material glTF Material
  2742. * @returns boolean specifying if texture parameters are present
  2743. */
  2744. _GLTFMaterialExporter.prototype._hasTexturesPresent = function (material) {
  2745. if (material.emissiveTexture || material.normalTexture || material.occlusionTexture) {
  2746. return true;
  2747. }
  2748. var pbrMat = material.pbrMetallicRoughness;
  2749. if (pbrMat) {
  2750. if (pbrMat.baseColorTexture || pbrMat.metallicRoughnessTexture) {
  2751. return true;
  2752. }
  2753. }
  2754. return false;
  2755. };
  2756. /**
  2757. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material
  2758. * @param babylonStandardMaterial
  2759. * @returns glTF Metallic Roughness Material representation
  2760. */
  2761. _GLTFMaterialExporter.prototype._convertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  2762. var P0 = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](0, 1);
  2763. var P1 = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](0, 0.1);
  2764. var P2 = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](0, 0.1);
  2765. var P3 = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector2"](1300, 0.1);
  2766. /**
  2767. * Given the control points, solve for x based on a given t for a cubic bezier curve
  2768. * @param t a value between 0 and 1
  2769. * @param p0 first control point
  2770. * @param p1 second control point
  2771. * @param p2 third control point
  2772. * @param p3 fourth control point
  2773. * @returns number result of cubic bezier curve at the specified t
  2774. */
  2775. function _cubicBezierCurve(t, p0, p1, p2, p3) {
  2776. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  2777. 3 * (1 - t) * (1 - t) * t * p1 +
  2778. 3 * (1 - t) * t * t * p2 +
  2779. t * t * t * p3);
  2780. }
  2781. /**
  2782. * Evaluates a specified specular power value to determine the appropriate roughness value,
  2783. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  2784. * and roughness on the ordinant axis (y-axis)
  2785. * @param specularPower specular power of standard material
  2786. * @returns Number representing the roughness value
  2787. */
  2788. function _solveForRoughness(specularPower) {
  2789. var t = Math.pow(specularPower / P3.x, 0.333333);
  2790. return _cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  2791. }
  2792. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  2793. var opacity = babylonStandardMaterial.alpha;
  2794. var specularPower = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Scalar"].Clamp(babylonStandardMaterial.specularPower, 0, _GLTFMaterialExporter._MaxSpecularPower);
  2795. var roughness = _solveForRoughness(specularPower);
  2796. var glTFPbrMetallicRoughness = {
  2797. baseColorFactor: [
  2798. diffuse.r,
  2799. diffuse.g,
  2800. diffuse.b,
  2801. opacity
  2802. ],
  2803. metallicFactor: 0,
  2804. roughnessFactor: roughness,
  2805. };
  2806. return glTFPbrMetallicRoughness;
  2807. };
  2808. /**
  2809. * Computes the metallic factor
  2810. * @param diffuse diffused value
  2811. * @param specular specular value
  2812. * @param oneMinusSpecularStrength one minus the specular strength
  2813. * @returns metallic value
  2814. */
  2815. _GLTFMaterialExporter._SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  2816. if (specular < this._DielectricSpecular.r) {
  2817. this._DielectricSpecular;
  2818. return 0;
  2819. }
  2820. var a = this._DielectricSpecular.r;
  2821. var b = diffuse * oneMinusSpecularStrength / (1.0 - this._DielectricSpecular.r) + specular - 2.0 * this._DielectricSpecular.r;
  2822. var c = this._DielectricSpecular.r - specular;
  2823. var D = b * b - 4.0 * a * c;
  2824. return babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Scalar"].Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  2825. };
  2826. /**
  2827. * Gets the glTF alpha mode from the Babylon Material
  2828. * @param babylonMaterial Babylon Material
  2829. * @returns The Babylon alpha mode value
  2830. */
  2831. _GLTFMaterialExporter.prototype._getAlphaMode = function (babylonMaterial) {
  2832. if (babylonMaterial.needAlphaBlending()) {
  2833. return "BLEND" /* BLEND */;
  2834. }
  2835. else if (babylonMaterial.needAlphaTesting()) {
  2836. return "MASK" /* MASK */;
  2837. }
  2838. else {
  2839. return "OPAQUE" /* OPAQUE */;
  2840. }
  2841. };
  2842. /**
  2843. * Converts a Babylon Standard Material to a glTF Material
  2844. * @param babylonStandardMaterial BJS Standard Material
  2845. * @param mimeType mime type to use for the textures
  2846. * @param images array of glTF image interfaces
  2847. * @param textures array of glTF texture interfaces
  2848. * @param materials array of glTF material interfaces
  2849. * @param imageData map of image file name to data
  2850. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2851. */
  2852. _GLTFMaterialExporter.prototype._convertStandardMaterialAsync = function (babylonStandardMaterial, mimeType, hasTextureCoords) {
  2853. var materialMap = this._exporter._materialMap;
  2854. var materials = this._exporter._materials;
  2855. var alphaMode = this._getAlphaMode(babylonStandardMaterial);
  2856. var promises = [];
  2857. var glTFPbrMetallicRoughness = this._convertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  2858. var glTFMaterial = { name: babylonStandardMaterial.name };
  2859. if (babylonStandardMaterial.backFaceCulling != null && !babylonStandardMaterial.backFaceCulling) {
  2860. if (!babylonStandardMaterial.twoSidedLighting) {
  2861. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  2862. }
  2863. glTFMaterial.doubleSided = true;
  2864. }
  2865. if (hasTextureCoords) {
  2866. if (babylonStandardMaterial.diffuseTexture) {
  2867. promises.push(this._exportTextureAsync(babylonStandardMaterial.diffuseTexture, mimeType).then(function (glTFTexture) {
  2868. if (glTFTexture) {
  2869. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  2870. }
  2871. }));
  2872. }
  2873. if (babylonStandardMaterial.bumpTexture) {
  2874. promises.push(this._exportTextureAsync(babylonStandardMaterial.bumpTexture, mimeType).then(function (glTFTexture) {
  2875. if (glTFTexture) {
  2876. glTFMaterial.normalTexture = glTFTexture;
  2877. if (babylonStandardMaterial.bumpTexture != null && babylonStandardMaterial.bumpTexture.level !== 1) {
  2878. glTFMaterial.normalTexture.scale = babylonStandardMaterial.bumpTexture.level;
  2879. }
  2880. }
  2881. }));
  2882. }
  2883. if (babylonStandardMaterial.emissiveTexture) {
  2884. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  2885. promises.push(this._exportTextureAsync(babylonStandardMaterial.emissiveTexture, mimeType).then(function (glTFEmissiveTexture) {
  2886. if (glTFEmissiveTexture) {
  2887. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  2888. }
  2889. }));
  2890. }
  2891. if (babylonStandardMaterial.ambientTexture) {
  2892. promises.push(this._exportTextureAsync(babylonStandardMaterial.ambientTexture, mimeType).then(function (glTFTexture) {
  2893. if (glTFTexture) {
  2894. var occlusionTexture = {
  2895. index: glTFTexture.index
  2896. };
  2897. glTFMaterial.occlusionTexture = occlusionTexture;
  2898. occlusionTexture.strength = 1.0;
  2899. }
  2900. }));
  2901. }
  2902. }
  2903. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  2904. if (babylonStandardMaterial.alphaMode === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Engine"].ALPHA_COMBINE) {
  2905. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  2906. }
  2907. else {
  2908. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  2909. }
  2910. }
  2911. if (babylonStandardMaterial.emissiveColor && !_GLTFMaterialExporter.FuzzyEquals(babylonStandardMaterial.emissiveColor, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Black(), _GLTFMaterialExporter._Epsilon)) {
  2912. glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
  2913. }
  2914. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  2915. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  2916. switch (alphaMode) {
  2917. case "BLEND" /* BLEND */: {
  2918. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  2919. break;
  2920. }
  2921. case "MASK" /* MASK */: {
  2922. glTFMaterial.alphaMode = "MASK" /* MASK */;
  2923. glTFMaterial.alphaCutoff = babylonStandardMaterial.alphaCutOff;
  2924. break;
  2925. }
  2926. default: {
  2927. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn("Unsupported alpha mode " + alphaMode);
  2928. }
  2929. }
  2930. }
  2931. materials.push(glTFMaterial);
  2932. materialMap[babylonStandardMaterial.uniqueId] = materials.length - 1;
  2933. return Promise.all(promises).then(function () { });
  2934. };
  2935. /**
  2936. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  2937. * @param babylonPBRMetalRoughMaterial BJS PBR Metallic Roughness Material
  2938. * @param mimeType mime type to use for the textures
  2939. * @param images array of glTF image interfaces
  2940. * @param textures array of glTF texture interfaces
  2941. * @param materials array of glTF material interfaces
  2942. * @param imageData map of image file name to data
  2943. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2944. */
  2945. _GLTFMaterialExporter.prototype._convertPBRMetallicRoughnessMaterialAsync = function (babylonPBRMetalRoughMaterial, mimeType, hasTextureCoords) {
  2946. var materialMap = this._exporter._materialMap;
  2947. var materials = this._exporter._materials;
  2948. var promises = [];
  2949. var glTFPbrMetallicRoughness = {};
  2950. if (babylonPBRMetalRoughMaterial.baseColor) {
  2951. glTFPbrMetallicRoughness.baseColorFactor = [
  2952. babylonPBRMetalRoughMaterial.baseColor.r,
  2953. babylonPBRMetalRoughMaterial.baseColor.g,
  2954. babylonPBRMetalRoughMaterial.baseColor.b,
  2955. babylonPBRMetalRoughMaterial.alpha
  2956. ];
  2957. }
  2958. if (babylonPBRMetalRoughMaterial.metallic != null && babylonPBRMetalRoughMaterial.metallic !== 1) {
  2959. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  2960. }
  2961. if (babylonPBRMetalRoughMaterial.roughness != null && babylonPBRMetalRoughMaterial.roughness !== 1) {
  2962. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  2963. }
  2964. var glTFMaterial = {
  2965. name: babylonPBRMetalRoughMaterial.name
  2966. };
  2967. if (babylonPBRMetalRoughMaterial.doubleSided) {
  2968. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  2969. }
  2970. var alphaMode = null;
  2971. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  2972. alphaMode = this._getAlphaMode(babylonPBRMetalRoughMaterial);
  2973. if (alphaMode) {
  2974. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  2975. glTFMaterial.alphaMode = alphaMode;
  2976. if (alphaMode === "MASK" /* MASK */) {
  2977. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  2978. }
  2979. }
  2980. }
  2981. }
  2982. if (hasTextureCoords) {
  2983. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  2984. promises.push(this._exportTextureAsync(babylonPBRMetalRoughMaterial.baseTexture, mimeType).then(function (glTFTexture) {
  2985. if (glTFTexture) {
  2986. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  2987. }
  2988. }));
  2989. }
  2990. if (babylonPBRMetalRoughMaterial.normalTexture) {
  2991. promises.push(this._exportTextureAsync(babylonPBRMetalRoughMaterial.normalTexture, mimeType).then(function (glTFTexture) {
  2992. if (glTFTexture) {
  2993. glTFMaterial.normalTexture = glTFTexture;
  2994. if (babylonPBRMetalRoughMaterial.normalTexture.level !== 1) {
  2995. glTFMaterial.normalTexture.scale = babylonPBRMetalRoughMaterial.normalTexture.level;
  2996. }
  2997. }
  2998. }));
  2999. }
  3000. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  3001. promises.push(this._exportTextureAsync(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType).then(function (glTFTexture) {
  3002. if (glTFTexture) {
  3003. glTFMaterial.occlusionTexture = glTFTexture;
  3004. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  3005. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  3006. }
  3007. }
  3008. }));
  3009. }
  3010. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  3011. promises.push(this._exportTextureAsync(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType).then(function (glTFTexture) {
  3012. if (glTFTexture) {
  3013. glTFMaterial.emissiveTexture = glTFTexture;
  3014. }
  3015. }));
  3016. }
  3017. }
  3018. if (_GLTFMaterialExporter.FuzzyEquals(babylonPBRMetalRoughMaterial.emissiveColor, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Black(), _GLTFMaterialExporter._Epsilon)) {
  3019. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  3020. }
  3021. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  3022. materials.push(glTFMaterial);
  3023. materialMap[babylonPBRMetalRoughMaterial.uniqueId] = materials.length - 1;
  3024. return Promise.all(promises).then(function () { });
  3025. };
  3026. /**
  3027. * Converts an image typed array buffer to a base64 image
  3028. * @param buffer typed array buffer
  3029. * @param width width of the image
  3030. * @param height height of the image
  3031. * @param mimeType mimetype of the image
  3032. * @returns base64 image string
  3033. */
  3034. _GLTFMaterialExporter.prototype._createBase64FromCanvasAsync = function (buffer, width, height, mimeType) {
  3035. var _this = this;
  3036. return new Promise(function (resolve, reject) {
  3037. var hostingScene;
  3038. var textureType = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURETYPE_UNSIGNED_INT;
  3039. var engine = _this._exporter._getLocalEngine();
  3040. hostingScene = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Scene"](engine);
  3041. // Create a temporary texture with the texture buffer data
  3042. var tempTexture = engine.createRawTexture(buffer, width, height, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTUREFORMAT_RGBA, false, true, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_SAMPLINGMODE, null, textureType);
  3043. var postProcess = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["PostProcess"]("pass", "pass", null, null, 1, null, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_SAMPLINGMODE, engine, false, undefined, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  3044. postProcess.getEffect().executeWhenCompiled(function () {
  3045. postProcess.onApply = function (effect) {
  3046. effect._bindTexture("textureSampler", tempTexture);
  3047. };
  3048. // Set the size of the texture
  3049. engine.setSize(width, height);
  3050. hostingScene.postProcessManager.directRender([postProcess], null);
  3051. postProcess.dispose();
  3052. tempTexture.dispose();
  3053. // Read data from WebGL
  3054. var canvas = engine.getRenderingCanvas();
  3055. if (canvas) {
  3056. if (!canvas.toBlob) { // fallback for browsers without "canvas.toBlob"
  3057. var dataURL = canvas.toDataURL();
  3058. resolve(dataURL);
  3059. }
  3060. else {
  3061. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].ToBlob(canvas, function (blob) {
  3062. if (blob) {
  3063. var fileReader = new FileReader();
  3064. fileReader.onload = function (event) {
  3065. var base64String = event.target.result;
  3066. hostingScene.dispose();
  3067. resolve(base64String);
  3068. };
  3069. fileReader.readAsDataURL(blob);
  3070. }
  3071. else {
  3072. reject("gltfMaterialExporter: Failed to get blob from image canvas!");
  3073. }
  3074. });
  3075. }
  3076. }
  3077. else {
  3078. reject("Engine is missing a canvas!");
  3079. }
  3080. });
  3081. });
  3082. };
  3083. /**
  3084. * Generates a white texture based on the specified width and height
  3085. * @param width width of the texture in pixels
  3086. * @param height height of the texture in pixels
  3087. * @param scene babylonjs scene
  3088. * @returns white texture
  3089. */
  3090. _GLTFMaterialExporter.prototype._createWhiteTexture = function (width, height, scene) {
  3091. var data = new Uint8Array(width * height * 4);
  3092. for (var i = 0; i < data.length; i = i + 4) {
  3093. data[i] = data[i + 1] = data[i + 2] = data[i + 3] = 0xFF;
  3094. }
  3095. var rawTexture = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["RawTexture"].CreateRGBATexture(data, width, height, scene);
  3096. return rawTexture;
  3097. };
  3098. /**
  3099. * Resizes the two source textures to the same dimensions. If a texture is null, a default white texture is generated. If both textures are null, returns null
  3100. * @param texture1 first texture to resize
  3101. * @param texture2 second texture to resize
  3102. * @param scene babylonjs scene
  3103. * @returns resized textures or null
  3104. */
  3105. _GLTFMaterialExporter.prototype._resizeTexturesToSameDimensions = function (texture1, texture2, scene) {
  3106. var texture1Size = texture1 ? texture1.getSize() : { width: 0, height: 0 };
  3107. var texture2Size = texture2 ? texture2.getSize() : { width: 0, height: 0 };
  3108. var resizedTexture1;
  3109. var resizedTexture2;
  3110. if (texture1Size.width < texture2Size.width) {
  3111. if (texture1 && texture1 instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"]) {
  3112. resizedTexture1 = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["TextureTools"].CreateResizedCopy(texture1, texture2Size.width, texture2Size.height, true);
  3113. }
  3114. else {
  3115. resizedTexture1 = this._createWhiteTexture(texture2Size.width, texture2Size.height, scene);
  3116. }
  3117. resizedTexture2 = texture2;
  3118. }
  3119. else if (texture1Size.width > texture2Size.width) {
  3120. if (texture2 && texture2 instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"]) {
  3121. resizedTexture2 = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["TextureTools"].CreateResizedCopy(texture2, texture1Size.width, texture1Size.height, true);
  3122. }
  3123. else {
  3124. resizedTexture2 = this._createWhiteTexture(texture1Size.width, texture1Size.height, scene);
  3125. }
  3126. resizedTexture1 = texture1;
  3127. }
  3128. else {
  3129. resizedTexture1 = texture1;
  3130. resizedTexture2 = texture2;
  3131. }
  3132. return {
  3133. "texture1": resizedTexture1,
  3134. "texture2": resizedTexture2
  3135. };
  3136. };
  3137. /**
  3138. * Converts an array of pixels to a Float32Array
  3139. * Throws an error if the pixel format is not supported
  3140. * @param pixels - array buffer containing pixel values
  3141. * @returns Float32 of pixels
  3142. */
  3143. _GLTFMaterialExporter.prototype._convertPixelArrayToFloat32 = function (pixels) {
  3144. if (pixels instanceof Uint8Array) {
  3145. var length_1 = pixels.length;
  3146. var buffer = new Float32Array(pixels.length);
  3147. for (var i = 0; i < length_1; ++i) {
  3148. buffer[i] = pixels[i] / 255;
  3149. }
  3150. return buffer;
  3151. }
  3152. else if (pixels instanceof Float32Array) {
  3153. return pixels;
  3154. }
  3155. else {
  3156. throw new Error('Unsupported pixel format!');
  3157. }
  3158. };
  3159. /**
  3160. * Convert Specular Glossiness Textures to Metallic Roughness
  3161. * See link below for info on the material conversions from PBR Metallic/Roughness and Specular/Glossiness
  3162. * @link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows-bjs/js/babylon.pbrUtilities.js
  3163. * @param diffuseTexture texture used to store diffuse information
  3164. * @param specularGlossinessTexture texture used to store specular and glossiness information
  3165. * @param factors specular glossiness material factors
  3166. * @param mimeType the mime type to use for the texture
  3167. * @returns pbr metallic roughness interface or null
  3168. */
  3169. _GLTFMaterialExporter.prototype._convertSpecularGlossinessTexturesToMetallicRoughnessAsync = function (diffuseTexture, specularGlossinessTexture, factors, mimeType) {
  3170. var promises = [];
  3171. if (!(diffuseTexture || specularGlossinessTexture)) {
  3172. return Promise.reject('_ConvertSpecularGlosinessTexturesToMetallicRoughness: diffuse and specular glossiness textures are not defined!');
  3173. }
  3174. var scene = diffuseTexture ? diffuseTexture.getScene() : specularGlossinessTexture ? specularGlossinessTexture.getScene() : null;
  3175. if (scene) {
  3176. var resizedTextures = this._resizeTexturesToSameDimensions(diffuseTexture, specularGlossinessTexture, scene);
  3177. var diffuseSize = resizedTextures.texture1.getSize();
  3178. var diffuseBuffer = void 0;
  3179. var specularGlossinessBuffer = void 0;
  3180. var width = diffuseSize.width;
  3181. var height = diffuseSize.height;
  3182. var diffusePixels = resizedTextures.texture1.readPixels();
  3183. var specularPixels = resizedTextures.texture2.readPixels();
  3184. if (diffusePixels) {
  3185. diffuseBuffer = this._convertPixelArrayToFloat32(diffusePixels);
  3186. }
  3187. else {
  3188. return Promise.reject("Failed to retrieve pixels from diffuse texture!");
  3189. }
  3190. if (specularPixels) {
  3191. specularGlossinessBuffer = this._convertPixelArrayToFloat32(specularPixels);
  3192. }
  3193. else {
  3194. return Promise.reject("Failed to retrieve pixels from specular glossiness texture!");
  3195. }
  3196. var byteLength = specularGlossinessBuffer.byteLength;
  3197. var metallicRoughnessBuffer = new Uint8Array(byteLength);
  3198. var baseColorBuffer = new Uint8Array(byteLength);
  3199. var strideSize = 4;
  3200. var maxBaseColor = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Black();
  3201. var maxMetallic = 0;
  3202. var maxRoughness = 0;
  3203. for (var h = 0; h < height; ++h) {
  3204. for (var w = 0; w < width; ++w) {
  3205. var offset = (width * h + w) * strideSize;
  3206. var diffuseColor = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"](diffuseBuffer[offset], diffuseBuffer[offset + 1], diffuseBuffer[offset + 2]).toLinearSpace().multiply(factors.diffuseColor);
  3207. var specularColor = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"](specularGlossinessBuffer[offset], specularGlossinessBuffer[offset + 1], specularGlossinessBuffer[offset + 2]).toLinearSpace().multiply(factors.specularColor);
  3208. var glossiness = (specularGlossinessBuffer[offset + 3]) * factors.glossiness;
  3209. var specularGlossiness = {
  3210. diffuseColor: diffuseColor,
  3211. specularColor: specularColor,
  3212. glossiness: glossiness
  3213. };
  3214. var metallicRoughness = this._convertSpecularGlossinessToMetallicRoughness(specularGlossiness);
  3215. maxBaseColor.r = Math.max(maxBaseColor.r, metallicRoughness.baseColor.r);
  3216. maxBaseColor.g = Math.max(maxBaseColor.g, metallicRoughness.baseColor.g);
  3217. maxBaseColor.b = Math.max(maxBaseColor.b, metallicRoughness.baseColor.b);
  3218. maxMetallic = Math.max(maxMetallic, metallicRoughness.metallic);
  3219. maxRoughness = Math.max(maxRoughness, metallicRoughness.roughness);
  3220. baseColorBuffer[offset] = metallicRoughness.baseColor.r * 255;
  3221. baseColorBuffer[offset + 1] = metallicRoughness.baseColor.g * 255;
  3222. baseColorBuffer[offset + 2] = metallicRoughness.baseColor.b * 255;
  3223. baseColorBuffer[offset + 3] = resizedTextures.texture1.hasAlpha ? diffuseBuffer[offset + 3] * 255 : 255;
  3224. metallicRoughnessBuffer[offset] = 0;
  3225. metallicRoughnessBuffer[offset + 1] = metallicRoughness.roughness * 255;
  3226. metallicRoughnessBuffer[offset + 2] = metallicRoughness.metallic * 255;
  3227. metallicRoughnessBuffer[offset + 3] = 255;
  3228. }
  3229. }
  3230. // Retrieves the metallic roughness factors from the maximum texture values.
  3231. var metallicRoughnessFactors_1 = {
  3232. baseColor: maxBaseColor,
  3233. metallic: maxMetallic,
  3234. roughness: maxRoughness
  3235. };
  3236. var writeOutMetallicRoughnessTexture = false;
  3237. var writeOutBaseColorTexture = false;
  3238. for (var h = 0; h < height; ++h) {
  3239. for (var w = 0; w < width; ++w) {
  3240. var destinationOffset = (width * h + w) * strideSize;
  3241. baseColorBuffer[destinationOffset] /= metallicRoughnessFactors_1.baseColor.r > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.baseColor.r : 1;
  3242. baseColorBuffer[destinationOffset + 1] /= metallicRoughnessFactors_1.baseColor.g > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.baseColor.g : 1;
  3243. baseColorBuffer[destinationOffset + 2] /= metallicRoughnessFactors_1.baseColor.b > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.baseColor.b : 1;
  3244. var linearBaseColorPixel = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromInts(baseColorBuffer[destinationOffset], baseColorBuffer[destinationOffset + 1], baseColorBuffer[destinationOffset + 2]);
  3245. var sRGBBaseColorPixel = linearBaseColorPixel.toGammaSpace();
  3246. baseColorBuffer[destinationOffset] = sRGBBaseColorPixel.r * 255;
  3247. baseColorBuffer[destinationOffset + 1] = sRGBBaseColorPixel.g * 255;
  3248. baseColorBuffer[destinationOffset + 2] = sRGBBaseColorPixel.b * 255;
  3249. if (!_GLTFMaterialExporter.FuzzyEquals(sRGBBaseColorPixel, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].White(), _GLTFMaterialExporter._Epsilon)) {
  3250. writeOutBaseColorTexture = true;
  3251. }
  3252. metallicRoughnessBuffer[destinationOffset + 1] /= metallicRoughnessFactors_1.roughness > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.roughness : 1;
  3253. metallicRoughnessBuffer[destinationOffset + 2] /= metallicRoughnessFactors_1.metallic > _GLTFMaterialExporter._Epsilon ? metallicRoughnessFactors_1.metallic : 1;
  3254. var metallicRoughnessPixel = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].FromInts(255, metallicRoughnessBuffer[destinationOffset + 1], metallicRoughnessBuffer[destinationOffset + 2]);
  3255. if (!_GLTFMaterialExporter.FuzzyEquals(metallicRoughnessPixel, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].White(), _GLTFMaterialExporter._Epsilon)) {
  3256. writeOutMetallicRoughnessTexture = true;
  3257. }
  3258. }
  3259. }
  3260. if (writeOutMetallicRoughnessTexture) {
  3261. var promise = this._createBase64FromCanvasAsync(metallicRoughnessBuffer, width, height, mimeType).then(function (metallicRoughnessBase64) {
  3262. metallicRoughnessFactors_1.metallicRoughnessTextureBase64 = metallicRoughnessBase64;
  3263. });
  3264. promises.push(promise);
  3265. }
  3266. if (writeOutBaseColorTexture) {
  3267. var promise = this._createBase64FromCanvasAsync(baseColorBuffer, width, height, mimeType).then(function (baseColorBase64) {
  3268. metallicRoughnessFactors_1.baseColorTextureBase64 = baseColorBase64;
  3269. });
  3270. promises.push(promise);
  3271. }
  3272. return Promise.all(promises).then(function () {
  3273. return metallicRoughnessFactors_1;
  3274. });
  3275. }
  3276. else {
  3277. return Promise.reject("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!");
  3278. }
  3279. };
  3280. /**
  3281. * Converts specular glossiness material properties to metallic roughness
  3282. * @param specularGlossiness interface with specular glossiness material properties
  3283. * @returns interface with metallic roughness material properties
  3284. */
  3285. _GLTFMaterialExporter.prototype._convertSpecularGlossinessToMetallicRoughness = function (specularGlossiness) {
  3286. var diffusePerceivedBrightness = this._getPerceivedBrightness(specularGlossiness.diffuseColor);
  3287. var specularPerceivedBrightness = this._getPerceivedBrightness(specularGlossiness.specularColor);
  3288. var oneMinusSpecularStrength = 1 - this._getMaxComponent(specularGlossiness.specularColor);
  3289. var metallic = _GLTFMaterialExporter._SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  3290. var baseColorFromDiffuse = specularGlossiness.diffuseColor.scale(oneMinusSpecularStrength / (1.0 - _GLTFMaterialExporter._DielectricSpecular.r) / Math.max(1 - metallic, _GLTFMaterialExporter._Epsilon));
  3291. var baseColorFromSpecular = specularGlossiness.specularColor.subtract(_GLTFMaterialExporter._DielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, _GLTFMaterialExporter._Epsilon));
  3292. var baseColor = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  3293. baseColor = baseColor.clampToRef(0, 1, baseColor);
  3294. var metallicRoughness = {
  3295. baseColor: baseColor,
  3296. metallic: metallic,
  3297. roughness: 1 - specularGlossiness.glossiness
  3298. };
  3299. return metallicRoughness;
  3300. };
  3301. /**
  3302. * Calculates the surface reflectance, independent of lighting conditions
  3303. * @param color Color source to calculate brightness from
  3304. * @returns number representing the perceived brightness, or zero if color is undefined
  3305. */
  3306. _GLTFMaterialExporter.prototype._getPerceivedBrightness = function (color) {
  3307. if (color) {
  3308. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  3309. }
  3310. return 0;
  3311. };
  3312. /**
  3313. * Returns the maximum color component value
  3314. * @param color
  3315. * @returns maximum color component value, or zero if color is null or undefined
  3316. */
  3317. _GLTFMaterialExporter.prototype._getMaxComponent = function (color) {
  3318. if (color) {
  3319. return Math.max(color.r, Math.max(color.g, color.b));
  3320. }
  3321. return 0;
  3322. };
  3323. /**
  3324. * Convert a PBRMaterial (Metallic/Roughness) to Metallic Roughness factors
  3325. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  3326. * @param mimeType mime type to use for the textures
  3327. * @param images array of glTF image interfaces
  3328. * @param textures array of glTF texture interfaces
  3329. * @param glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  3330. * @param imageData map of image file name to data
  3331. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  3332. * @returns glTF PBR Metallic Roughness factors
  3333. */
  3334. _GLTFMaterialExporter.prototype._convertMetalRoughFactorsToMetallicRoughnessAsync = function (babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords) {
  3335. var promises = [];
  3336. var metallicRoughness = {
  3337. baseColor: babylonPBRMaterial.albedoColor,
  3338. metallic: babylonPBRMaterial.metallic,
  3339. roughness: babylonPBRMaterial.roughness
  3340. };
  3341. if (hasTextureCoords) {
  3342. if (babylonPBRMaterial.albedoTexture) {
  3343. promises.push(this._exportTextureAsync(babylonPBRMaterial.albedoTexture, mimeType).then(function (glTFTexture) {
  3344. if (glTFTexture) {
  3345. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  3346. }
  3347. }));
  3348. }
  3349. if (babylonPBRMaterial.metallicTexture) {
  3350. promises.push(this._exportTextureAsync(babylonPBRMaterial.metallicTexture, mimeType).then(function (glTFTexture) {
  3351. if (glTFTexture) {
  3352. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFTexture;
  3353. }
  3354. }));
  3355. }
  3356. }
  3357. return Promise.all(promises).then(function () {
  3358. return metallicRoughness;
  3359. });
  3360. };
  3361. _GLTFMaterialExporter.prototype._getGLTFTextureSampler = function (texture) {
  3362. var sampler = this._getGLTFTextureWrapModesSampler(texture);
  3363. var samplingMode = texture instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"] ? texture.samplingMode : null;
  3364. if (samplingMode != null) {
  3365. switch (samplingMode) {
  3366. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].LINEAR_LINEAR: {
  3367. sampler.magFilter = 9729 /* LINEAR */;
  3368. sampler.minFilter = 9729 /* LINEAR */;
  3369. break;
  3370. }
  3371. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].LINEAR_NEAREST: {
  3372. sampler.magFilter = 9729 /* LINEAR */;
  3373. sampler.minFilter = 9728 /* NEAREST */;
  3374. break;
  3375. }
  3376. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_LINEAR: {
  3377. sampler.magFilter = 9728 /* NEAREST */;
  3378. sampler.minFilter = 9729 /* LINEAR */;
  3379. break;
  3380. }
  3381. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_LINEAR_MIPLINEAR: {
  3382. sampler.magFilter = 9728 /* NEAREST */;
  3383. sampler.minFilter = 9987 /* LINEAR_MIPMAP_LINEAR */;
  3384. break;
  3385. }
  3386. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_NEAREST: {
  3387. sampler.magFilter = 9728 /* NEAREST */;
  3388. sampler.minFilter = 9728 /* NEAREST */;
  3389. break;
  3390. }
  3391. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_LINEAR_MIPNEAREST: {
  3392. sampler.magFilter = 9728 /* NEAREST */;
  3393. sampler.minFilter = 9985 /* LINEAR_MIPMAP_NEAREST */;
  3394. break;
  3395. }
  3396. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].LINEAR_NEAREST_MIPNEAREST: {
  3397. sampler.magFilter = 9729 /* LINEAR */;
  3398. sampler.minFilter = 9984 /* NEAREST_MIPMAP_NEAREST */;
  3399. break;
  3400. }
  3401. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].LINEAR_NEAREST_MIPLINEAR: {
  3402. sampler.magFilter = 9729 /* LINEAR */;
  3403. sampler.minFilter = 9986 /* NEAREST_MIPMAP_LINEAR */;
  3404. break;
  3405. }
  3406. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_NEAREST_MIPLINEAR: {
  3407. sampler.magFilter = 9728 /* NEAREST */;
  3408. sampler.minFilter = 9986 /* NEAREST_MIPMAP_LINEAR */;
  3409. break;
  3410. }
  3411. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].LINEAR_LINEAR_MIPLINEAR: {
  3412. sampler.magFilter = 9729 /* LINEAR */;
  3413. sampler.minFilter = 9987 /* LINEAR_MIPMAP_LINEAR */;
  3414. break;
  3415. }
  3416. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].LINEAR_LINEAR_MIPNEAREST: {
  3417. sampler.magFilter = 9729 /* LINEAR */;
  3418. sampler.minFilter = 9985 /* LINEAR_MIPMAP_NEAREST */;
  3419. break;
  3420. }
  3421. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].NEAREST_NEAREST_MIPNEAREST: {
  3422. sampler.magFilter = 9728 /* NEAREST */;
  3423. sampler.minFilter = 9984 /* NEAREST_MIPMAP_NEAREST */;
  3424. break;
  3425. }
  3426. }
  3427. }
  3428. return sampler;
  3429. };
  3430. _GLTFMaterialExporter.prototype._getGLTFTextureWrapMode = function (wrapMode) {
  3431. switch (wrapMode) {
  3432. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].WRAP_ADDRESSMODE: {
  3433. return 10497 /* REPEAT */;
  3434. }
  3435. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].CLAMP_ADDRESSMODE: {
  3436. return 33071 /* CLAMP_TO_EDGE */;
  3437. }
  3438. case babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].MIRROR_ADDRESSMODE: {
  3439. return 33648 /* MIRRORED_REPEAT */;
  3440. }
  3441. default: {
  3442. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("Unsupported Texture Wrap Mode " + wrapMode + "!");
  3443. return 10497 /* REPEAT */;
  3444. }
  3445. }
  3446. };
  3447. _GLTFMaterialExporter.prototype._getGLTFTextureWrapModesSampler = function (texture) {
  3448. var wrapS = this._getGLTFTextureWrapMode(texture instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"] ? texture.wrapU : babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].WRAP_ADDRESSMODE);
  3449. var wrapT = this._getGLTFTextureWrapMode(texture instanceof babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"] ? texture.wrapV : babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Texture"].WRAP_ADDRESSMODE);
  3450. if (wrapS === 10497 /* REPEAT */ && wrapT === 10497 /* REPEAT */) { // default wrapping mode in glTF, so omitting
  3451. return {};
  3452. }
  3453. return { wrapS: wrapS, wrapT: wrapT };
  3454. };
  3455. /**
  3456. * Convert a PBRMaterial (Specular/Glossiness) to Metallic Roughness factors
  3457. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  3458. * @param mimeType mime type to use for the textures
  3459. * @param images array of glTF image interfaces
  3460. * @param textures array of glTF texture interfaces
  3461. * @param glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  3462. * @param imageData map of image file name to data
  3463. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  3464. * @returns glTF PBR Metallic Roughness factors
  3465. */
  3466. _GLTFMaterialExporter.prototype._convertSpecGlossFactorsToMetallicRoughnessAsync = function (babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords) {
  3467. var _this = this;
  3468. return Promise.resolve().then(function () {
  3469. var samplers = _this._exporter._samplers;
  3470. var textures = _this._exporter._textures;
  3471. var specGloss = {
  3472. diffuseColor: babylonPBRMaterial.albedoColor || babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].White(),
  3473. specularColor: babylonPBRMaterial.reflectivityColor || babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].White(),
  3474. glossiness: babylonPBRMaterial.microSurface || 1,
  3475. };
  3476. var samplerIndex = null;
  3477. var sampler = _this._getGLTFTextureSampler(babylonPBRMaterial.albedoTexture);
  3478. if (sampler.magFilter != null && sampler.minFilter != null && sampler.wrapS != null && sampler.wrapT != null) {
  3479. samplers.push(sampler);
  3480. samplerIndex = samplers.length - 1;
  3481. }
  3482. if (babylonPBRMaterial.reflectivityTexture && !babylonPBRMaterial.useMicroSurfaceFromReflectivityMapAlpha) {
  3483. return Promise.reject("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture are currently not supported");
  3484. }
  3485. if ((babylonPBRMaterial.albedoTexture || babylonPBRMaterial.reflectivityTexture) && hasTextureCoords) {
  3486. return _this._convertSpecularGlossinessTexturesToMetallicRoughnessAsync(babylonPBRMaterial.albedoTexture, babylonPBRMaterial.reflectivityTexture, specGloss, mimeType).then(function (metallicRoughnessFactors) {
  3487. if (metallicRoughnessFactors.baseColorTextureBase64) {
  3488. var glTFBaseColorTexture = _this._getTextureInfoFromBase64(metallicRoughnessFactors.baseColorTextureBase64, "bjsBaseColorTexture_" + (textures.length) + ".png", mimeType, babylonPBRMaterial.albedoTexture ? babylonPBRMaterial.albedoTexture.coordinatesIndex : null, samplerIndex);
  3489. if (glTFBaseColorTexture) {
  3490. glTFPbrMetallicRoughness.baseColorTexture = glTFBaseColorTexture;
  3491. }
  3492. }
  3493. if (metallicRoughnessFactors.metallicRoughnessTextureBase64) {
  3494. var glTFMRColorTexture = _this._getTextureInfoFromBase64(metallicRoughnessFactors.metallicRoughnessTextureBase64, "bjsMetallicRoughnessTexture_" + (textures.length) + ".png", mimeType, babylonPBRMaterial.reflectivityTexture ? babylonPBRMaterial.reflectivityTexture.coordinatesIndex : null, samplerIndex);
  3495. if (glTFMRColorTexture) {
  3496. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFMRColorTexture;
  3497. }
  3498. }
  3499. return metallicRoughnessFactors;
  3500. });
  3501. }
  3502. else {
  3503. return _this._convertSpecularGlossinessToMetallicRoughness(specGloss);
  3504. }
  3505. });
  3506. };
  3507. /**
  3508. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  3509. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  3510. * @param mimeType mime type to use for the textures
  3511. * @param images array of glTF image interfaces
  3512. * @param textures array of glTF texture interfaces
  3513. * @param materials array of glTF material interfaces
  3514. * @param imageData map of image file name to data
  3515. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  3516. */
  3517. _GLTFMaterialExporter.prototype._convertPBRMaterialAsync = function (babylonPBRMaterial, mimeType, hasTextureCoords) {
  3518. var _this = this;
  3519. var glTFPbrMetallicRoughness = {};
  3520. var glTFMaterial = {
  3521. name: babylonPBRMaterial.name
  3522. };
  3523. var useMetallicRoughness = babylonPBRMaterial.isMetallicWorkflow();
  3524. if (useMetallicRoughness) {
  3525. if (babylonPBRMaterial.albedoColor) {
  3526. glTFPbrMetallicRoughness.baseColorFactor = [
  3527. babylonPBRMaterial.albedoColor.r,
  3528. babylonPBRMaterial.albedoColor.g,
  3529. babylonPBRMaterial.albedoColor.b,
  3530. babylonPBRMaterial.alpha
  3531. ];
  3532. }
  3533. return this._convertMetalRoughFactorsToMetallicRoughnessAsync(babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords).then(function (metallicRoughness) {
  3534. return _this.setMetallicRoughnessPbrMaterial(metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, hasTextureCoords);
  3535. });
  3536. }
  3537. else {
  3538. return this._convertSpecGlossFactorsToMetallicRoughnessAsync(babylonPBRMaterial, mimeType, glTFPbrMetallicRoughness, hasTextureCoords).then(function (metallicRoughness) {
  3539. return _this.setMetallicRoughnessPbrMaterial(metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, hasTextureCoords);
  3540. });
  3541. }
  3542. };
  3543. _GLTFMaterialExporter.prototype.setMetallicRoughnessPbrMaterial = function (metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, hasTextureCoords) {
  3544. var materialMap = this._exporter._materialMap;
  3545. var materials = this._exporter._materials;
  3546. var promises = [];
  3547. if (metallicRoughness) {
  3548. var alphaMode = null;
  3549. if (babylonPBRMaterial.transparencyMode != null) {
  3550. alphaMode = this._getAlphaMode(babylonPBRMaterial);
  3551. if (alphaMode) {
  3552. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  3553. glTFMaterial.alphaMode = alphaMode;
  3554. if (alphaMode === "MASK" /* MASK */) {
  3555. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  3556. }
  3557. }
  3558. }
  3559. }
  3560. if (!(_GLTFMaterialExporter.FuzzyEquals(metallicRoughness.baseColor, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].White(), _GLTFMaterialExporter._Epsilon) && babylonPBRMaterial.alpha >= _GLTFMaterialExporter._Epsilon)) {
  3561. glTFPbrMetallicRoughness.baseColorFactor = [
  3562. metallicRoughness.baseColor.r,
  3563. metallicRoughness.baseColor.g,
  3564. metallicRoughness.baseColor.b,
  3565. babylonPBRMaterial.alpha
  3566. ];
  3567. }
  3568. if (metallicRoughness.metallic != null && metallicRoughness.metallic !== 1) {
  3569. glTFPbrMetallicRoughness.metallicFactor = metallicRoughness.metallic;
  3570. }
  3571. if (metallicRoughness.roughness != null && metallicRoughness.roughness !== 1) {
  3572. glTFPbrMetallicRoughness.roughnessFactor = metallicRoughness.roughness;
  3573. }
  3574. if (babylonPBRMaterial.backFaceCulling != null && !babylonPBRMaterial.backFaceCulling) {
  3575. if (!babylonPBRMaterial.twoSidedLighting) {
  3576. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Warn(babylonPBRMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  3577. }
  3578. glTFMaterial.doubleSided = true;
  3579. }
  3580. if (hasTextureCoords) {
  3581. if (babylonPBRMaterial.bumpTexture) {
  3582. var promise = this._exportTextureAsync(babylonPBRMaterial.bumpTexture, mimeType).then(function (glTFTexture) {
  3583. if (glTFTexture) {
  3584. glTFMaterial.normalTexture = glTFTexture;
  3585. if (babylonPBRMaterial.bumpTexture.level !== 1) {
  3586. glTFMaterial.normalTexture.scale = babylonPBRMaterial.bumpTexture.level;
  3587. }
  3588. }
  3589. });
  3590. promises.push(promise);
  3591. }
  3592. if (babylonPBRMaterial.ambientTexture) {
  3593. var promise = this._exportTextureAsync(babylonPBRMaterial.ambientTexture, mimeType).then(function (glTFTexture) {
  3594. if (glTFTexture) {
  3595. var occlusionTexture = {
  3596. index: glTFTexture.index
  3597. };
  3598. glTFMaterial.occlusionTexture = occlusionTexture;
  3599. if (babylonPBRMaterial.ambientTextureStrength) {
  3600. occlusionTexture.strength = babylonPBRMaterial.ambientTextureStrength;
  3601. }
  3602. }
  3603. });
  3604. promises.push(promise);
  3605. }
  3606. if (babylonPBRMaterial.emissiveTexture) {
  3607. var promise = this._exportTextureAsync(babylonPBRMaterial.emissiveTexture, mimeType).then(function (glTFTexture) {
  3608. if (glTFTexture) {
  3609. glTFMaterial.emissiveTexture = glTFTexture;
  3610. }
  3611. });
  3612. promises.push(promise);
  3613. }
  3614. }
  3615. if (!_GLTFMaterialExporter.FuzzyEquals(babylonPBRMaterial.emissiveColor, babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"].Black(), _GLTFMaterialExporter._Epsilon)) {
  3616. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  3617. }
  3618. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  3619. materials.push(glTFMaterial);
  3620. materialMap[babylonPBRMaterial.uniqueId] = materials.length - 1;
  3621. }
  3622. return Promise.all(promises).then(function (result) { });
  3623. };
  3624. _GLTFMaterialExporter.prototype.getPixelsFromTexture = function (babylonTexture) {
  3625. var pixels = babylonTexture.textureType === babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Engine"].TEXTURETYPE_UNSIGNED_INT ? babylonTexture.readPixels() : babylonTexture.readPixels();
  3626. return pixels;
  3627. };
  3628. /**
  3629. * Extracts a texture from a Babylon texture into file data and glTF data
  3630. * @param babylonTexture Babylon texture to extract
  3631. * @param mimeType Mime Type of the babylonTexture
  3632. * @return glTF texture info, or null if the texture format is not supported
  3633. */
  3634. _GLTFMaterialExporter.prototype._exportTextureAsync = function (babylonTexture, mimeType) {
  3635. var _this = this;
  3636. var extensionPromise = this._exporter._extensionsPreExportTextureAsync("exporter", babylonTexture, mimeType);
  3637. if (!extensionPromise) {
  3638. return this._exportTextureInfoAsync(babylonTexture, mimeType);
  3639. }
  3640. return extensionPromise.then(function (texture) {
  3641. if (!texture) {
  3642. return _this._exportTextureInfoAsync(babylonTexture, mimeType);
  3643. }
  3644. return _this._exportTextureInfoAsync(texture, mimeType);
  3645. });
  3646. };
  3647. _GLTFMaterialExporter.prototype._exportTextureInfoAsync = function (babylonTexture, mimeType) {
  3648. var _this = this;
  3649. return Promise.resolve().then(function () {
  3650. var textureUid = babylonTexture.uid;
  3651. if (textureUid in _this._textureMap) {
  3652. return _this._textureMap[textureUid];
  3653. }
  3654. else {
  3655. var samplers = _this._exporter._samplers;
  3656. var sampler = _this._getGLTFTextureSampler(babylonTexture);
  3657. var samplerIndex_1 = null;
  3658. // if a pre-existing sampler with identical parameters exists, then reuse the previous sampler
  3659. var foundSamplerIndex = null;
  3660. for (var i = 0; i < samplers.length; ++i) {
  3661. var s = samplers[i];
  3662. if (s.minFilter === sampler.minFilter && s.magFilter === sampler.magFilter &&
  3663. s.wrapS === sampler.wrapS && s.wrapT === sampler.wrapT) {
  3664. foundSamplerIndex = i;
  3665. break;
  3666. }
  3667. }
  3668. if (foundSamplerIndex == null) {
  3669. samplers.push(sampler);
  3670. samplerIndex_1 = samplers.length - 1;
  3671. }
  3672. else {
  3673. samplerIndex_1 = foundSamplerIndex;
  3674. }
  3675. var pixels = _this.getPixelsFromTexture(babylonTexture);
  3676. var size = babylonTexture.getSize();
  3677. return _this._createBase64FromCanvasAsync(pixels, size.width, size.height, mimeType).then(function (base64Data) {
  3678. var textureInfo = _this._getTextureInfoFromBase64(base64Data, babylonTexture.name.replace(/\.\/|\/|\.\\|\\/g, "_"), mimeType, babylonTexture.coordinatesIndex, samplerIndex_1);
  3679. if (textureInfo) {
  3680. _this._textureMap[textureUid] = textureInfo;
  3681. }
  3682. return textureInfo;
  3683. });
  3684. }
  3685. });
  3686. };
  3687. /**
  3688. * Builds a texture from base64 string
  3689. * @param base64Texture base64 texture string
  3690. * @param baseTextureName Name to use for the texture
  3691. * @param mimeType image mime type for the texture
  3692. * @param images array of images
  3693. * @param textures array of textures
  3694. * @param imageData map of image data
  3695. * @returns glTF texture info, or null if the texture format is not supported
  3696. */
  3697. _GLTFMaterialExporter.prototype._getTextureInfoFromBase64 = function (base64Texture, baseTextureName, mimeType, texCoordIndex, samplerIndex) {
  3698. var textures = this._exporter._textures;
  3699. var images = this._exporter._images;
  3700. var imageData = this._exporter._imageData;
  3701. var textureInfo = null;
  3702. var glTFTexture = {
  3703. source: images.length,
  3704. name: baseTextureName
  3705. };
  3706. if (samplerIndex != null) {
  3707. glTFTexture.sampler = samplerIndex;
  3708. }
  3709. var binStr = atob(base64Texture.split(',')[1]);
  3710. var arrBuff = new ArrayBuffer(binStr.length);
  3711. var arr = new Uint8Array(arrBuff);
  3712. for (var i = 0, length_2 = binStr.length; i < length_2; ++i) {
  3713. arr[i] = binStr.charCodeAt(i);
  3714. }
  3715. var imageValues = { data: arr, mimeType: mimeType };
  3716. var extension = mimeType === "image/jpeg" /* JPEG */ ? '.jpeg' : '.png';
  3717. var textureName = baseTextureName + extension;
  3718. if (textureName in imageData) {
  3719. textureName = baseTextureName + "_" + babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].RandomId() + extension;
  3720. }
  3721. imageData[textureName] = imageValues;
  3722. if (mimeType === "image/jpeg" /* JPEG */ || mimeType === "image/png" /* PNG */) {
  3723. var glTFImage = {
  3724. name: baseTextureName,
  3725. uri: textureName
  3726. };
  3727. var foundIndex = null;
  3728. for (var i = 0; i < images.length; ++i) {
  3729. if (images[i].uri === textureName) {
  3730. foundIndex = i;
  3731. break;
  3732. }
  3733. }
  3734. if (foundIndex == null) {
  3735. images.push(glTFImage);
  3736. glTFTexture.source = images.length - 1;
  3737. }
  3738. else {
  3739. glTFTexture.source = foundIndex;
  3740. }
  3741. textures.push(glTFTexture);
  3742. textureInfo = {
  3743. index: textures.length - 1
  3744. };
  3745. if (texCoordIndex != null) {
  3746. textureInfo.texCoord = texCoordIndex;
  3747. }
  3748. }
  3749. else {
  3750. babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Tools"].Error("Unsupported texture mime type " + mimeType);
  3751. }
  3752. return textureInfo;
  3753. };
  3754. /**
  3755. * Represents the dielectric specular values for R, G and B
  3756. */
  3757. _GLTFMaterialExporter._DielectricSpecular = new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Color3"](0.04, 0.04, 0.04);
  3758. /**
  3759. * Allows the maximum specular power to be defined for material calculations
  3760. */
  3761. _GLTFMaterialExporter._MaxSpecularPower = 1024;
  3762. /**
  3763. * Numeric tolerance value
  3764. */
  3765. _GLTFMaterialExporter._Epsilon = 1e-6;
  3766. return _GLTFMaterialExporter;
  3767. }());
  3768. /***/ }),
  3769. /***/ "./glTF/2.0/glTFSerializer.ts":
  3770. /*!************************************!*\
  3771. !*** ./glTF/2.0/glTFSerializer.ts ***!
  3772. \************************************/
  3773. /*! exports provided: GLTF2Export */
  3774. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  3775. "use strict";
  3776. __webpack_require__.r(__webpack_exports__);
  3777. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GLTF2Export", function() { return GLTF2Export; });
  3778. /* harmony import */ var _glTFExporter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./glTFExporter */ "./glTF/2.0/glTFExporter.ts");
  3779. /**
  3780. * Class for generating glTF data from a Babylon scene.
  3781. */
  3782. var GLTF2Export = /** @class */ (function () {
  3783. function GLTF2Export() {
  3784. }
  3785. /**
  3786. * Exports the geometry of the scene to .gltf file format asynchronously
  3787. * @param scene Babylon scene with scene hierarchy information
  3788. * @param filePrefix File prefix to use when generating the glTF file
  3789. * @param options Exporter options
  3790. * @returns Returns an object with a .gltf file and associates texture names
  3791. * as keys and their data and paths as values
  3792. */
  3793. GLTF2Export.GLTFAsync = function (scene, filePrefix, options) {
  3794. return scene.whenReadyAsync().then(function () {
  3795. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  3796. var gltfGenerator = new _glTFExporter__WEBPACK_IMPORTED_MODULE_0__["_Exporter"](scene, options);
  3797. return gltfGenerator._generateGLTFAsync(glTFPrefix);
  3798. });
  3799. };
  3800. GLTF2Export._PreExportAsync = function (scene, options) {
  3801. return Promise.resolve().then(function () {
  3802. if (options && options.exportWithoutWaitingForScene) {
  3803. return Promise.resolve();
  3804. }
  3805. else {
  3806. return scene.whenReadyAsync();
  3807. }
  3808. });
  3809. };
  3810. GLTF2Export._PostExportAsync = function (scene, glTFData, options) {
  3811. return Promise.resolve().then(function () {
  3812. if (options && options.exportWithoutWaitingForScene) {
  3813. return glTFData;
  3814. }
  3815. else {
  3816. return glTFData;
  3817. }
  3818. });
  3819. };
  3820. /**
  3821. * Exports the geometry of the scene to .glb file format asychronously
  3822. * @param scene Babylon scene with scene hierarchy information
  3823. * @param filePrefix File prefix to use when generating glb file
  3824. * @param options Exporter options
  3825. * @returns Returns an object with a .glb filename as key and data as value
  3826. */
  3827. GLTF2Export.GLBAsync = function (scene, filePrefix, options) {
  3828. var _this = this;
  3829. return this._PreExportAsync(scene, options).then(function () {
  3830. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  3831. var gltfGenerator = new _glTFExporter__WEBPACK_IMPORTED_MODULE_0__["_Exporter"](scene, options);
  3832. return gltfGenerator._generateGLBAsync(glTFPrefix).then(function (glTFData) {
  3833. return _this._PostExportAsync(scene, glTFData, options);
  3834. });
  3835. });
  3836. };
  3837. return GLTF2Export;
  3838. }());
  3839. /***/ }),
  3840. /***/ "./glTF/2.0/glTFUtilities.ts":
  3841. /*!***********************************!*\
  3842. !*** ./glTF/2.0/glTFUtilities.ts ***!
  3843. \***********************************/
  3844. /*! exports provided: _GLTFUtilities */
  3845. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  3846. "use strict";
  3847. __webpack_require__.r(__webpack_exports__);
  3848. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_GLTFUtilities", function() { return _GLTFUtilities; });
  3849. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Maths/math */ "babylonjs/Maths/math");
  3850. /* harmony import */ var babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__);
  3851. /**
  3852. * @hidden
  3853. */
  3854. var _GLTFUtilities = /** @class */ (function () {
  3855. function _GLTFUtilities() {
  3856. }
  3857. /**
  3858. * Creates a buffer view based on the supplied arguments
  3859. * @param bufferIndex index value of the specified buffer
  3860. * @param byteOffset byte offset value
  3861. * @param byteLength byte length of the bufferView
  3862. * @param byteStride byte distance between conequential elements
  3863. * @param name name of the buffer view
  3864. * @returns bufferView for glTF
  3865. */
  3866. _GLTFUtilities._CreateBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  3867. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  3868. if (byteOffset) {
  3869. bufferview.byteOffset = byteOffset;
  3870. }
  3871. if (name) {
  3872. bufferview.name = name;
  3873. }
  3874. if (byteStride) {
  3875. bufferview.byteStride = byteStride;
  3876. }
  3877. return bufferview;
  3878. };
  3879. /**
  3880. * Creates an accessor based on the supplied arguments
  3881. * @param bufferviewIndex The index of the bufferview referenced by this accessor
  3882. * @param name The name of the accessor
  3883. * @param type The type of the accessor
  3884. * @param componentType The datatype of components in the attribute
  3885. * @param count The number of attributes referenced by this accessor
  3886. * @param byteOffset The offset relative to the start of the bufferView in bytes
  3887. * @param min Minimum value of each component in this attribute
  3888. * @param max Maximum value of each component in this attribute
  3889. * @returns accessor for glTF
  3890. */
  3891. _GLTFUtilities._CreateAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  3892. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  3893. if (min != null) {
  3894. accessor.min = min;
  3895. }
  3896. if (max != null) {
  3897. accessor.max = max;
  3898. }
  3899. if (byteOffset != null) {
  3900. accessor.byteOffset = byteOffset;
  3901. }
  3902. return accessor;
  3903. };
  3904. /**
  3905. * Calculates the minimum and maximum values of an array of position floats
  3906. * @param positions Positions array of a mesh
  3907. * @param vertexStart Starting vertex offset to calculate min and max values
  3908. * @param vertexCount Number of vertices to check for min and max values
  3909. * @returns min number array and max number array
  3910. */
  3911. _GLTFUtilities._CalculateMinMaxPositions = function (positions, vertexStart, vertexCount, convertToRightHandedSystem) {
  3912. var min = [Infinity, Infinity, Infinity];
  3913. var max = [-Infinity, -Infinity, -Infinity];
  3914. var positionStrideSize = 3;
  3915. var indexOffset;
  3916. var position;
  3917. var vector;
  3918. if (vertexCount) {
  3919. for (var i = vertexStart, length_1 = vertexStart + vertexCount; i < length_1; ++i) {
  3920. indexOffset = positionStrideSize * i;
  3921. position = babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"].FromArray(positions, indexOffset);
  3922. if (convertToRightHandedSystem) {
  3923. _GLTFUtilities._GetRightHandedPositionVector3FromRef(position);
  3924. }
  3925. vector = position.asArray();
  3926. for (var j = 0; j < positionStrideSize; ++j) {
  3927. var num = vector[j];
  3928. if (num < min[j]) {
  3929. min[j] = num;
  3930. }
  3931. if (num > max[j]) {
  3932. max[j] = num;
  3933. }
  3934. ++indexOffset;
  3935. }
  3936. }
  3937. }
  3938. return { min: min, max: max };
  3939. };
  3940. /**
  3941. * Converts a new right-handed Vector3
  3942. * @param vector vector3 array
  3943. * @returns right-handed Vector3
  3944. */
  3945. _GLTFUtilities._GetRightHandedPositionVector3 = function (vector) {
  3946. return new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](vector.x, vector.y, -vector.z);
  3947. };
  3948. /**
  3949. * Converts a Vector3 to right-handed
  3950. * @param vector Vector3 to convert to right-handed
  3951. */
  3952. _GLTFUtilities._GetRightHandedPositionVector3FromRef = function (vector) {
  3953. vector.z *= -1;
  3954. };
  3955. /**
  3956. * Converts a three element number array to right-handed
  3957. * @param vector number array to convert to right-handed
  3958. */
  3959. _GLTFUtilities._GetRightHandedPositionArray3FromRef = function (vector) {
  3960. vector[2] *= -1;
  3961. };
  3962. /**
  3963. * Converts a new right-handed Vector3
  3964. * @param vector vector3 array
  3965. * @returns right-handed Vector3
  3966. */
  3967. _GLTFUtilities._GetRightHandedNormalVector3 = function (vector) {
  3968. return new babylonjs_Maths_math__WEBPACK_IMPORTED_MODULE_0__["Vector3"](vector.x, vector.y, -vector.z);
  3969. };
  3970. /**
  3971. * Converts a Vector3 to right-handed
  3972. * @param vector Vector3 to convert to right-handed
  3973. */
  3974. _GLTFUtilities._GetRightHandedNormalVector3FromRef = function (vector) {
  3975. vector.z *= -1;
  3976. };
  3977. /**
  3978. * Converts a three element number array to right-handed
  3979. * @param vector number array to convert to right-handed
  3980. */
  3981. _GLTFUtilities._GetRightHandedNormalArray3FromRef = function (vector) {
  3982. vector[2] *= -1;
  3983. };
  3984. /**
  3985. * Converts a Vector4 to right-handed
  3986. * @param vector Vector4 to convert to right-handed
  3987. */
  3988. _GLTFUtilities._GetRightHandedVector4FromRef = function (vector) {
  3989. vector.z *= -1;
  3990. vector.w *= -1;
  3991. };
  3992. /**
  3993. * Converts a Vector4 to right-handed
  3994. * @param vector Vector4 to convert to right-handed
  3995. */
  3996. _GLTFUtilities._GetRightHandedArray4FromRef = function (vector) {
  3997. vector[2] *= -1;
  3998. vector[3] *= -1;
  3999. };
  4000. /**
  4001. * Converts a Quaternion to right-handed
  4002. * @param quaternion Source quaternion to convert to right-handed
  4003. */
  4004. _GLTFUtilities._GetRightHandedQuaternionFromRef = function (quaternion) {
  4005. quaternion.x *= -1;
  4006. quaternion.y *= -1;
  4007. };
  4008. /**
  4009. * Converts a Quaternion to right-handed
  4010. * @param quaternion Source quaternion to convert to right-handed
  4011. */
  4012. _GLTFUtilities._GetRightHandedQuaternionArrayFromRef = function (quaternion) {
  4013. quaternion[0] *= -1;
  4014. quaternion[1] *= -1;
  4015. };
  4016. _GLTFUtilities._NormalizeTangentFromRef = function (tangent) {
  4017. var length = Math.sqrt(tangent.x * tangent.x + tangent.y * tangent.y + tangent.z * tangent.z);
  4018. if (length > 0) {
  4019. tangent.x /= length;
  4020. tangent.y /= length;
  4021. tangent.z /= length;
  4022. }
  4023. };
  4024. return _GLTFUtilities;
  4025. }());
  4026. /***/ }),
  4027. /***/ "./glTF/2.0/index.ts":
  4028. /*!***************************!*\
  4029. !*** ./glTF/2.0/index.ts ***!
  4030. \***************************/
  4031. /*! exports provided: GLTFData, GLTF2Export, _GLTFAnimation, _Exporter, _BinaryWriter, __IGLTFExporterExtensionV2, _GLTFMaterialExporter, _GLTFUtilities, KHR_texture_transform, KHR_lights_punctual */
  4032. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4033. "use strict";
  4034. __webpack_require__.r(__webpack_exports__);
  4035. /* harmony import */ var _glTFAnimation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./glTFAnimation */ "./glTF/2.0/glTFAnimation.ts");
  4036. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFAnimation", function() { return _glTFAnimation__WEBPACK_IMPORTED_MODULE_0__["_GLTFAnimation"]; });
  4037. /* harmony import */ var _glTFData__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./glTFData */ "./glTF/2.0/glTFData.ts");
  4038. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFData", function() { return _glTFData__WEBPACK_IMPORTED_MODULE_1__["GLTFData"]; });
  4039. /* harmony import */ var _glTFExporter__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./glTFExporter */ "./glTF/2.0/glTFExporter.ts");
  4040. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_Exporter", function() { return _glTFExporter__WEBPACK_IMPORTED_MODULE_2__["_Exporter"]; });
  4041. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BinaryWriter", function() { return _glTFExporter__WEBPACK_IMPORTED_MODULE_2__["_BinaryWriter"]; });
  4042. /* harmony import */ var _glTFExporterExtension__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./glTFExporterExtension */ "./glTF/2.0/glTFExporterExtension.ts");
  4043. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "__IGLTFExporterExtensionV2", function() { return _glTFExporterExtension__WEBPACK_IMPORTED_MODULE_3__["__IGLTFExporterExtensionV2"]; });
  4044. /* harmony import */ var _glTFMaterialExporter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./glTFMaterialExporter */ "./glTF/2.0/glTFMaterialExporter.ts");
  4045. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFMaterialExporter", function() { return _glTFMaterialExporter__WEBPACK_IMPORTED_MODULE_4__["_GLTFMaterialExporter"]; });
  4046. /* harmony import */ var _glTFSerializer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./glTFSerializer */ "./glTF/2.0/glTFSerializer.ts");
  4047. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTF2Export", function() { return _glTFSerializer__WEBPACK_IMPORTED_MODULE_5__["GLTF2Export"]; });
  4048. /* harmony import */ var _glTFUtilities__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(/*! ./glTFUtilities */ "./glTF/2.0/glTFUtilities.ts");
  4049. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFUtilities", function() { return _glTFUtilities__WEBPACK_IMPORTED_MODULE_6__["_GLTFUtilities"]; });
  4050. /* harmony import */ var _Extensions__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(/*! ./Extensions */ "./glTF/2.0/Extensions/index.ts");
  4051. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_texture_transform", function() { return _Extensions__WEBPACK_IMPORTED_MODULE_7__["KHR_texture_transform"]; });
  4052. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_lights_punctual", function() { return _Extensions__WEBPACK_IMPORTED_MODULE_7__["KHR_lights_punctual"]; });
  4053. /***/ }),
  4054. /***/ "./glTF/2.0/shaders/textureTransform.fragment.ts":
  4055. /*!*******************************************************!*\
  4056. !*** ./glTF/2.0/shaders/textureTransform.fragment.ts ***!
  4057. \*******************************************************/
  4058. /*! exports provided: textureTransformPixelShader */
  4059. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4060. "use strict";
  4061. __webpack_require__.r(__webpack_exports__);
  4062. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "textureTransformPixelShader", function() { return textureTransformPixelShader; });
  4063. /* harmony import */ var babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Materials/effect */ "babylonjs/Maths/math");
  4064. /* harmony import */ var babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0__);
  4065. var name = 'textureTransformPixelShader';
  4066. var shader = "precision highp float;\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 textureTransformMat;\nvoid main(void) {\nvec2 uvTransformed=(textureTransformMat*vec4(vUV.xy,1,1)).xy;\ngl_FragColor=texture2D(textureSampler,uvTransformed);\n}";
  4067. babylonjs_Materials_effect__WEBPACK_IMPORTED_MODULE_0__["Effect"].ShadersStore[name] = shader;
  4068. /** @hidden */
  4069. var textureTransformPixelShader = { name: name, shader: shader };
  4070. /***/ }),
  4071. /***/ "./glTF/glTFFileExporter.ts":
  4072. /*!**********************************!*\
  4073. !*** ./glTF/glTFFileExporter.ts ***!
  4074. \**********************************/
  4075. /*! exports provided: __IGLTFExporterExtension */
  4076. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4077. "use strict";
  4078. __webpack_require__.r(__webpack_exports__);
  4079. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__IGLTFExporterExtension", function() { return __IGLTFExporterExtension; });
  4080. /** @hidden */
  4081. var __IGLTFExporterExtension = 0; // I am here to allow dts to be created
  4082. /***/ }),
  4083. /***/ "./glTF/index.ts":
  4084. /*!***********************!*\
  4085. !*** ./glTF/index.ts ***!
  4086. \***********************/
  4087. /*! exports provided: __IGLTFExporterExtension, GLTFData, GLTF2Export, _GLTFAnimation, _Exporter, _BinaryWriter, __IGLTFExporterExtensionV2, _GLTFMaterialExporter, _GLTFUtilities, KHR_texture_transform, KHR_lights_punctual */
  4088. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4089. "use strict";
  4090. __webpack_require__.r(__webpack_exports__);
  4091. /* harmony import */ var _glTFFileExporter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./glTFFileExporter */ "./glTF/glTFFileExporter.ts");
  4092. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "__IGLTFExporterExtension", function() { return _glTFFileExporter__WEBPACK_IMPORTED_MODULE_0__["__IGLTFExporterExtension"]; });
  4093. /* harmony import */ var _2_0__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./2.0 */ "./glTF/2.0/index.ts");
  4094. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFData", function() { return _2_0__WEBPACK_IMPORTED_MODULE_1__["GLTFData"]; });
  4095. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTF2Export", function() { return _2_0__WEBPACK_IMPORTED_MODULE_1__["GLTF2Export"]; });
  4096. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFAnimation", function() { return _2_0__WEBPACK_IMPORTED_MODULE_1__["_GLTFAnimation"]; });
  4097. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_Exporter", function() { return _2_0__WEBPACK_IMPORTED_MODULE_1__["_Exporter"]; });
  4098. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BinaryWriter", function() { return _2_0__WEBPACK_IMPORTED_MODULE_1__["_BinaryWriter"]; });
  4099. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "__IGLTFExporterExtensionV2", function() { return _2_0__WEBPACK_IMPORTED_MODULE_1__["__IGLTFExporterExtensionV2"]; });
  4100. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFMaterialExporter", function() { return _2_0__WEBPACK_IMPORTED_MODULE_1__["_GLTFMaterialExporter"]; });
  4101. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFUtilities", function() { return _2_0__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]; });
  4102. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_texture_transform", function() { return _2_0__WEBPACK_IMPORTED_MODULE_1__["KHR_texture_transform"]; });
  4103. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_lights_punctual", function() { return _2_0__WEBPACK_IMPORTED_MODULE_1__["KHR_lights_punctual"]; });
  4104. /***/ }),
  4105. /***/ "./index.ts":
  4106. /*!******************!*\
  4107. !*** ./index.ts ***!
  4108. \******************/
  4109. /*! exports provided: __IGLTFExporterExtension, GLTFData, GLTF2Export, OBJExport, _GLTFAnimation, _Exporter, _BinaryWriter, __IGLTFExporterExtensionV2, _GLTFMaterialExporter, _GLTFUtilities, STLExport, KHR_texture_transform, KHR_lights_punctual */
  4110. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4111. "use strict";
  4112. __webpack_require__.r(__webpack_exports__);
  4113. /* harmony import */ var _OBJ__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./OBJ */ "./OBJ/index.ts");
  4114. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OBJExport", function() { return _OBJ__WEBPACK_IMPORTED_MODULE_0__["OBJExport"]; });
  4115. /* harmony import */ var _glTF__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./glTF */ "./glTF/index.ts");
  4116. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "__IGLTFExporterExtension", function() { return _glTF__WEBPACK_IMPORTED_MODULE_1__["__IGLTFExporterExtension"]; });
  4117. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFData", function() { return _glTF__WEBPACK_IMPORTED_MODULE_1__["GLTFData"]; });
  4118. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTF2Export", function() { return _glTF__WEBPACK_IMPORTED_MODULE_1__["GLTF2Export"]; });
  4119. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFAnimation", function() { return _glTF__WEBPACK_IMPORTED_MODULE_1__["_GLTFAnimation"]; });
  4120. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_Exporter", function() { return _glTF__WEBPACK_IMPORTED_MODULE_1__["_Exporter"]; });
  4121. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BinaryWriter", function() { return _glTF__WEBPACK_IMPORTED_MODULE_1__["_BinaryWriter"]; });
  4122. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "__IGLTFExporterExtensionV2", function() { return _glTF__WEBPACK_IMPORTED_MODULE_1__["__IGLTFExporterExtensionV2"]; });
  4123. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFMaterialExporter", function() { return _glTF__WEBPACK_IMPORTED_MODULE_1__["_GLTFMaterialExporter"]; });
  4124. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFUtilities", function() { return _glTF__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]; });
  4125. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_texture_transform", function() { return _glTF__WEBPACK_IMPORTED_MODULE_1__["KHR_texture_transform"]; });
  4126. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_lights_punctual", function() { return _glTF__WEBPACK_IMPORTED_MODULE_1__["KHR_lights_punctual"]; });
  4127. /* harmony import */ var _stl__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./stl */ "./stl/index.ts");
  4128. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "STLExport", function() { return _stl__WEBPACK_IMPORTED_MODULE_2__["STLExport"]; });
  4129. /***/ }),
  4130. /***/ "./legacy/legacy-glTF2Serializer.ts":
  4131. /*!******************************************!*\
  4132. !*** ./legacy/legacy-glTF2Serializer.ts ***!
  4133. \******************************************/
  4134. /*! exports provided: __IGLTFExporterExtension, GLTFData, GLTF2Export, _GLTFAnimation, _Exporter, _BinaryWriter, __IGLTFExporterExtensionV2, _GLTFMaterialExporter, _GLTFUtilities, KHR_texture_transform, KHR_lights_punctual */
  4135. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4136. "use strict";
  4137. __webpack_require__.r(__webpack_exports__);
  4138. /* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _glTF_glTFFileExporter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../glTF/glTFFileExporter */ "./glTF/glTFFileExporter.ts");
  4139. /* harmony import */ var _glTF_2_0_glTFData__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../glTF/2.0/glTFData */ "./glTF/2.0/glTFData.ts");
  4140. /* harmony import */ var _glTF_2_0_glTFSerializer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../glTF/2.0/glTFSerializer */ "./glTF/2.0/glTFSerializer.ts");
  4141. /* harmony import */ var _glTF_2_0_Extensions__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../glTF/2.0/Extensions */ "./glTF/2.0/Extensions/index.ts");
  4142. /* harmony import */ var _glTF_2_0__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../glTF/2.0 */ "./glTF/2.0/index.ts");
  4143. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "__IGLTFExporterExtension", function() { return _glTF_glTFFileExporter__WEBPACK_IMPORTED_MODULE_0__["__IGLTFExporterExtension"]; });
  4144. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFData", function() { return _glTF_2_0__WEBPACK_IMPORTED_MODULE_4__["GLTFData"]; });
  4145. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTF2Export", function() { return _glTF_2_0__WEBPACK_IMPORTED_MODULE_4__["GLTF2Export"]; });
  4146. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFAnimation", function() { return _glTF_2_0__WEBPACK_IMPORTED_MODULE_4__["_GLTFAnimation"]; });
  4147. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_Exporter", function() { return _glTF_2_0__WEBPACK_IMPORTED_MODULE_4__["_Exporter"]; });
  4148. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BinaryWriter", function() { return _glTF_2_0__WEBPACK_IMPORTED_MODULE_4__["_BinaryWriter"]; });
  4149. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "__IGLTFExporterExtensionV2", function() { return _glTF_2_0__WEBPACK_IMPORTED_MODULE_4__["__IGLTFExporterExtensionV2"]; });
  4150. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFMaterialExporter", function() { return _glTF_2_0__WEBPACK_IMPORTED_MODULE_4__["_GLTFMaterialExporter"]; });
  4151. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFUtilities", function() { return _glTF_2_0__WEBPACK_IMPORTED_MODULE_4__["_GLTFUtilities"]; });
  4152. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_texture_transform", function() { return _glTF_2_0__WEBPACK_IMPORTED_MODULE_4__["KHR_texture_transform"]; });
  4153. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_lights_punctual", function() { return _glTF_2_0__WEBPACK_IMPORTED_MODULE_4__["KHR_lights_punctual"]; });
  4154. /**
  4155. * This is the entry point for the UMD module.
  4156. * The entry point for a future ESM package should be index.ts
  4157. */
  4158. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  4159. if (typeof globalObject !== "undefined") {
  4160. globalObject.BABYLON = globalObject.BABYLON || {};
  4161. var BABYLON = globalObject.BABYLON;
  4162. BABYLON.GLTF2 = BABYLON.GLTF2 || {};
  4163. BABYLON.GLTF2.Exporter = BABYLON.GLTF2.Exporter || {};
  4164. BABYLON.GLTF2.Exporter.Extensions = BABYLON.GLTF2.Exporter.Extensions || {};
  4165. var keys = [];
  4166. for (var key in _glTF_glTFFileExporter__WEBPACK_IMPORTED_MODULE_0__) {
  4167. BABYLON[key] = _glTF_glTFFileExporter__WEBPACK_IMPORTED_MODULE_0__[key];
  4168. keys.push(key);
  4169. }
  4170. for (var key in _glTF_2_0_glTFData__WEBPACK_IMPORTED_MODULE_1__) {
  4171. BABYLON[key] = _glTF_2_0_glTFData__WEBPACK_IMPORTED_MODULE_1__[key];
  4172. keys.push(key);
  4173. }
  4174. for (var key in _glTF_2_0_glTFSerializer__WEBPACK_IMPORTED_MODULE_2__) {
  4175. BABYLON[key] = _glTF_2_0_glTFSerializer__WEBPACK_IMPORTED_MODULE_2__[key];
  4176. keys.push(key);
  4177. }
  4178. for (var key in _glTF_2_0_Extensions__WEBPACK_IMPORTED_MODULE_3__) {
  4179. BABYLON.GLTF2.Exporter.Extensions[key] = _glTF_2_0_Extensions__WEBPACK_IMPORTED_MODULE_3__[key];
  4180. keys.push(key);
  4181. }
  4182. for (var key in _glTF_2_0__WEBPACK_IMPORTED_MODULE_4__) {
  4183. // Prevent Reassignment.
  4184. if (keys.indexOf(key) > -1) {
  4185. continue;
  4186. }
  4187. BABYLON.GLTF2.Exporter[key] = _glTF_2_0__WEBPACK_IMPORTED_MODULE_4__[key];
  4188. }
  4189. }
  4190. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
  4191. /***/ }),
  4192. /***/ "./legacy/legacy-objSerializer.ts":
  4193. /*!****************************************!*\
  4194. !*** ./legacy/legacy-objSerializer.ts ***!
  4195. \****************************************/
  4196. /*! exports provided: OBJExport */
  4197. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4198. "use strict";
  4199. __webpack_require__.r(__webpack_exports__);
  4200. /* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _OBJ__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../OBJ */ "./OBJ/index.ts");
  4201. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OBJExport", function() { return _OBJ__WEBPACK_IMPORTED_MODULE_0__["OBJExport"]; });
  4202. /**
  4203. * This is the entry point for the UMD module.
  4204. * The entry point for a future ESM package should be index.ts
  4205. */
  4206. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  4207. if (typeof globalObject !== "undefined") {
  4208. for (var serializer in _OBJ__WEBPACK_IMPORTED_MODULE_0__) {
  4209. globalObject.BABYLON[serializer] = _OBJ__WEBPACK_IMPORTED_MODULE_0__[serializer];
  4210. }
  4211. }
  4212. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
  4213. /***/ }),
  4214. /***/ "./legacy/legacy-stlSerializer.ts":
  4215. /*!****************************************!*\
  4216. !*** ./legacy/legacy-stlSerializer.ts ***!
  4217. \****************************************/
  4218. /*! exports provided: STLExport */
  4219. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4220. "use strict";
  4221. __webpack_require__.r(__webpack_exports__);
  4222. /* WEBPACK VAR INJECTION */(function(global) {/* harmony import */ var _stl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../stl */ "./stl/index.ts");
  4223. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "STLExport", function() { return _stl__WEBPACK_IMPORTED_MODULE_0__["STLExport"]; });
  4224. /**
  4225. * This is the entry point for the UMD module.
  4226. * The entry point for a future ESM package should be index.ts
  4227. */
  4228. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  4229. if (typeof globalObject !== "undefined") {
  4230. for (var serializer in _stl__WEBPACK_IMPORTED_MODULE_0__) {
  4231. globalObject.BABYLON[serializer] = _stl__WEBPACK_IMPORTED_MODULE_0__[serializer];
  4232. }
  4233. }
  4234. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../../node_modules/webpack/buildin/global.js */ "../../node_modules/webpack/buildin/global.js")))
  4235. /***/ }),
  4236. /***/ "./legacy/legacy.ts":
  4237. /*!**************************!*\
  4238. !*** ./legacy/legacy.ts ***!
  4239. \**************************/
  4240. /*! exports provided: __IGLTFExporterExtension, GLTFData, GLTF2Export, _GLTFAnimation, _Exporter, _BinaryWriter, __IGLTFExporterExtensionV2, _GLTFMaterialExporter, _GLTFUtilities, OBJExport, STLExport, KHR_texture_transform, KHR_lights_punctual */
  4241. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4242. "use strict";
  4243. __webpack_require__.r(__webpack_exports__);
  4244. /* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../index */ "./index.ts");
  4245. /* harmony import */ var _legacy_glTF2Serializer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./legacy-glTF2Serializer */ "./legacy/legacy-glTF2Serializer.ts");
  4246. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "__IGLTFExporterExtension", function() { return _legacy_glTF2Serializer__WEBPACK_IMPORTED_MODULE_1__["__IGLTFExporterExtension"]; });
  4247. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTFData", function() { return _legacy_glTF2Serializer__WEBPACK_IMPORTED_MODULE_1__["GLTFData"]; });
  4248. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "GLTF2Export", function() { return _legacy_glTF2Serializer__WEBPACK_IMPORTED_MODULE_1__["GLTF2Export"]; });
  4249. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFAnimation", function() { return _legacy_glTF2Serializer__WEBPACK_IMPORTED_MODULE_1__["_GLTFAnimation"]; });
  4250. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_Exporter", function() { return _legacy_glTF2Serializer__WEBPACK_IMPORTED_MODULE_1__["_Exporter"]; });
  4251. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_BinaryWriter", function() { return _legacy_glTF2Serializer__WEBPACK_IMPORTED_MODULE_1__["_BinaryWriter"]; });
  4252. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "__IGLTFExporterExtensionV2", function() { return _legacy_glTF2Serializer__WEBPACK_IMPORTED_MODULE_1__["__IGLTFExporterExtensionV2"]; });
  4253. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFMaterialExporter", function() { return _legacy_glTF2Serializer__WEBPACK_IMPORTED_MODULE_1__["_GLTFMaterialExporter"]; });
  4254. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "_GLTFUtilities", function() { return _legacy_glTF2Serializer__WEBPACK_IMPORTED_MODULE_1__["_GLTFUtilities"]; });
  4255. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_texture_transform", function() { return _legacy_glTF2Serializer__WEBPACK_IMPORTED_MODULE_1__["KHR_texture_transform"]; });
  4256. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "KHR_lights_punctual", function() { return _legacy_glTF2Serializer__WEBPACK_IMPORTED_MODULE_1__["KHR_lights_punctual"]; });
  4257. /* harmony import */ var _legacy_objSerializer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./legacy-objSerializer */ "./legacy/legacy-objSerializer.ts");
  4258. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "OBJExport", function() { return _legacy_objSerializer__WEBPACK_IMPORTED_MODULE_2__["OBJExport"]; });
  4259. /* harmony import */ var _legacy_stlSerializer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./legacy-stlSerializer */ "./legacy/legacy-stlSerializer.ts");
  4260. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "STLExport", function() { return _legacy_stlSerializer__WEBPACK_IMPORTED_MODULE_3__["STLExport"]; });
  4261. /***/ }),
  4262. /***/ "./stl/index.ts":
  4263. /*!**********************!*\
  4264. !*** ./stl/index.ts ***!
  4265. \**********************/
  4266. /*! exports provided: STLExport */
  4267. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4268. "use strict";
  4269. __webpack_require__.r(__webpack_exports__);
  4270. /* harmony import */ var _stlSerializer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./stlSerializer */ "./stl/stlSerializer.ts");
  4271. /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "STLExport", function() { return _stlSerializer__WEBPACK_IMPORTED_MODULE_0__["STLExport"]; });
  4272. /***/ }),
  4273. /***/ "./stl/stlSerializer.ts":
  4274. /*!******************************!*\
  4275. !*** ./stl/stlSerializer.ts ***!
  4276. \******************************/
  4277. /*! exports provided: STLExport */
  4278. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4279. "use strict";
  4280. __webpack_require__.r(__webpack_exports__);
  4281. /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "STLExport", function() { return STLExport; });
  4282. /* harmony import */ var babylonjs_Meshes_buffer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! babylonjs/Meshes/buffer */ "babylonjs/Maths/math");
  4283. /* harmony import */ var babylonjs_Meshes_buffer__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(babylonjs_Meshes_buffer__WEBPACK_IMPORTED_MODULE_0__);
  4284. /**
  4285. * Class for generating STL data from a Babylon scene.
  4286. */
  4287. var STLExport = /** @class */ (function () {
  4288. function STLExport() {
  4289. }
  4290. /**
  4291. * Exports the geometry of a Mesh array in .STL file format (ASCII)
  4292. * @param meshes list defines the mesh to serialize
  4293. * @param download triggers the automatic download of the file.
  4294. * @param fileName changes the downloads fileName.
  4295. * @param binary changes the STL to a binary type.
  4296. * @param isLittleEndian toggle for binary type exporter.
  4297. * @returns the STL as UTF8 string
  4298. */
  4299. STLExport.CreateSTL = function (meshes, download, fileName, binary, isLittleEndian) {
  4300. //Binary support adapted from https://gist.github.com/paulkaplan/6d5f0ab2c7e8fdc68a61
  4301. if (download === void 0) { download = true; }
  4302. if (fileName === void 0) { fileName = 'STL_Mesh'; }
  4303. if (binary === void 0) { binary = false; }
  4304. if (isLittleEndian === void 0) { isLittleEndian = true; }
  4305. var getFaceData = function (indices, vertices, i) {
  4306. var id = [indices[i] * 3, indices[i + 1] * 3, indices[i + 2] * 3];
  4307. var v = [
  4308. new babylonjs_Meshes_buffer__WEBPACK_IMPORTED_MODULE_0__["Vector3"](vertices[id[0]], vertices[id[0] + 1], vertices[id[0] + 2]),
  4309. new babylonjs_Meshes_buffer__WEBPACK_IMPORTED_MODULE_0__["Vector3"](vertices[id[1]], vertices[id[1] + 1], vertices[id[1] + 2]),
  4310. new babylonjs_Meshes_buffer__WEBPACK_IMPORTED_MODULE_0__["Vector3"](vertices[id[2]], vertices[id[2] + 1], vertices[id[2] + 2])
  4311. ];
  4312. var p1p2 = v[0].subtract(v[1]);
  4313. var p3p2 = v[2].subtract(v[1]);
  4314. var n = (babylonjs_Meshes_buffer__WEBPACK_IMPORTED_MODULE_0__["Vector3"].Cross(p1p2, p3p2)).normalize();
  4315. return { v: v, n: n };
  4316. };
  4317. var writeVector = function (dataview, offset, vector, isLittleEndian) {
  4318. offset = writeFloat(dataview, offset, vector.x, isLittleEndian);
  4319. offset = writeFloat(dataview, offset, vector.y, isLittleEndian);
  4320. return writeFloat(dataview, offset, vector.z, isLittleEndian);
  4321. };
  4322. var writeFloat = function (dataview, offset, value, isLittleEndian) {
  4323. dataview.setFloat32(offset, value, isLittleEndian);
  4324. return offset + 4;
  4325. };
  4326. var data;
  4327. var faceCount = 0;
  4328. var offset = 0;
  4329. if (binary) {
  4330. for (var i = 0; i < meshes.length; i++) {
  4331. var mesh = meshes[i];
  4332. var indices = mesh.getIndices();
  4333. faceCount += indices ? indices.length : 0;
  4334. }
  4335. var bufferSize = 84 + (50 * faceCount);
  4336. var buffer = new ArrayBuffer(bufferSize);
  4337. data = new DataView(buffer);
  4338. offset += 80;
  4339. data.setUint32(offset, faceCount, isLittleEndian);
  4340. offset += 4;
  4341. }
  4342. else {
  4343. data = 'solid exportedMesh\r\n';
  4344. }
  4345. for (var i = 0; i < meshes.length; i++) {
  4346. var mesh = meshes[i];
  4347. mesh.bakeCurrentTransformIntoVertices();
  4348. var vertices = mesh.getVerticesData(babylonjs_Meshes_buffer__WEBPACK_IMPORTED_MODULE_0__["VertexBuffer"].PositionKind) || [];
  4349. var indices = mesh.getIndices() || [];
  4350. for (var i_1 = 0; i_1 < indices.length; i_1 += 3) {
  4351. var fd = getFaceData(indices, vertices, i_1);
  4352. if (binary) {
  4353. offset = writeVector(data, offset, fd.n, isLittleEndian);
  4354. offset = writeVector(data, offset, fd.v[0], isLittleEndian);
  4355. offset = writeVector(data, offset, fd.v[1], isLittleEndian);
  4356. offset = writeVector(data, offset, fd.v[2], isLittleEndian);
  4357. offset += 2;
  4358. }
  4359. else {
  4360. data += 'facet normal ' + fd.n.x + ' ' + fd.n.y + ' ' + fd.n.z + '\r\n';
  4361. data += '\touter loop\r\n';
  4362. data += '\t\tvertex ' + fd.v[0].x + ' ' + fd.v[0].y + ' ' + fd.v[0].z + '\r\n';
  4363. data += '\t\tvertex ' + fd.v[1].x + ' ' + fd.v[1].y + ' ' + fd.v[1].z + '\r\n';
  4364. data += '\t\tvertex ' + fd.v[2].x + ' ' + fd.v[2].y + ' ' + fd.v[2].z + '\r\n';
  4365. data += '\tendloop\r\n';
  4366. data += 'endfacet\r\n';
  4367. }
  4368. }
  4369. }
  4370. if (!binary) {
  4371. data += 'endsolid exportedMesh';
  4372. }
  4373. if (download) {
  4374. var a = document.createElement('a');
  4375. var blob = new Blob([data], { 'type': 'application/octet-stream' });
  4376. a.href = window.URL.createObjectURL(blob);
  4377. if (!fileName) {
  4378. fileName = "STL_Mesh";
  4379. }
  4380. a.download = fileName + ".stl";
  4381. a.click();
  4382. }
  4383. return data;
  4384. };
  4385. return STLExport;
  4386. }());
  4387. /***/ }),
  4388. /***/ "babylonjs/Maths/math":
  4389. /*!****************************************************************************************************!*\
  4390. !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***!
  4391. \****************************************************************************************************/
  4392. /*! no static exports found */
  4393. /***/ (function(module, exports) {
  4394. module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs_Maths_math__;
  4395. /***/ })
  4396. /******/ });
  4397. });
  4398. //# sourceMappingURL=babylonjs.serializers.js.map