babylon.glTFFileLoader.js 231 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. var GLTFLoaderCoordinateSystemMode;
  5. (function (GLTFLoaderCoordinateSystemMode) {
  6. /**
  7. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  8. */
  9. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  10. /**
  11. * Sets the useRightHandedSystem flag on the scene.
  12. */
  13. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  14. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  15. var GLTFLoaderAnimationStartMode;
  16. (function (GLTFLoaderAnimationStartMode) {
  17. /**
  18. * No animation will start.
  19. */
  20. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  21. /**
  22. * The first animation will start.
  23. */
  24. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  25. /**
  26. * All animations will start.
  27. */
  28. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  29. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  30. var GLTFLoaderState;
  31. (function (GLTFLoaderState) {
  32. GLTFLoaderState[GLTFLoaderState["Loading"] = 0] = "Loading";
  33. GLTFLoaderState[GLTFLoaderState["Ready"] = 1] = "Ready";
  34. GLTFLoaderState[GLTFLoaderState["Complete"] = 2] = "Complete";
  35. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  36. var GLTFFileLoader = /** @class */ (function () {
  37. function GLTFFileLoader() {
  38. // #region Common options
  39. /**
  40. * Raised when the asset has been parsed.
  41. * The data.json property stores the glTF JSON.
  42. * The data.bin property stores the BIN chunk from a glTF binary or null if the input is not a glTF binary.
  43. */
  44. this.onParsedObservable = new BABYLON.Observable();
  45. // #endregion
  46. // #region V2 options
  47. /**
  48. * The coordinate system mode (AUTO, FORCE_RIGHT_HANDED).
  49. */
  50. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  51. /**
  52. * The animation start mode (NONE, FIRST, ALL).
  53. */
  54. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  55. /**
  56. * Set to true to compile materials before raising the success callback.
  57. */
  58. this.compileMaterials = false;
  59. /**
  60. * Set to true to also compile materials with clip planes.
  61. */
  62. this.useClipPlane = false;
  63. /**
  64. * Set to true to compile shadow generators before raising the success callback.
  65. */
  66. this.compileShadowGenerators = false;
  67. /**
  68. * Raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  69. */
  70. this.onMeshLoadedObservable = new BABYLON.Observable();
  71. /**
  72. * Raised when the loader creates a texture after parsing the glTF properties of the texture.
  73. */
  74. this.onTextureLoadedObservable = new BABYLON.Observable();
  75. /**
  76. * Raised when the loader creates a material after parsing the glTF properties of the material.
  77. */
  78. this.onMaterialLoadedObservable = new BABYLON.Observable();
  79. /**
  80. * Raised when the asset is completely loaded, immediately before the loader is disposed.
  81. * For assets with LODs, raised when all of the LODs are complete.
  82. * For assets without LODs, raised when the model is complete, immediately after onSuccess.
  83. */
  84. this.onCompleteObservable = new BABYLON.Observable();
  85. /**
  86. * Raised when the loader is disposed.
  87. */
  88. this.onDisposeObservable = new BABYLON.Observable();
  89. /**
  90. * Raised after a loader extension is created.
  91. * Set additional options for a loader extension in this event.
  92. */
  93. this.onExtensionLoadedObservable = new BABYLON.Observable();
  94. // #endregion
  95. this._loader = null;
  96. this.name = "gltf";
  97. this.extensions = {
  98. ".gltf": { isBinary: false },
  99. ".glb": { isBinary: true }
  100. };
  101. }
  102. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  103. set: function (callback) {
  104. if (this._onParsedObserver) {
  105. this.onParsedObservable.remove(this._onParsedObserver);
  106. }
  107. this._onParsedObserver = this.onParsedObservable.add(callback);
  108. },
  109. enumerable: true,
  110. configurable: true
  111. });
  112. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  113. set: function (callback) {
  114. if (this._onMeshLoadedObserver) {
  115. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  116. }
  117. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  118. },
  119. enumerable: true,
  120. configurable: true
  121. });
  122. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  123. set: function (callback) {
  124. if (this._onTextureLoadedObserver) {
  125. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  126. }
  127. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  128. },
  129. enumerable: true,
  130. configurable: true
  131. });
  132. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  133. set: function (callback) {
  134. if (this._onMaterialLoadedObserver) {
  135. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  136. }
  137. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  138. },
  139. enumerable: true,
  140. configurable: true
  141. });
  142. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  143. set: function (callback) {
  144. if (this._onCompleteObserver) {
  145. this.onCompleteObservable.remove(this._onCompleteObserver);
  146. }
  147. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  148. },
  149. enumerable: true,
  150. configurable: true
  151. });
  152. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  153. set: function (callback) {
  154. if (this._onDisposeObserver) {
  155. this.onDisposeObservable.remove(this._onDisposeObserver);
  156. }
  157. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  158. },
  159. enumerable: true,
  160. configurable: true
  161. });
  162. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  163. set: function (callback) {
  164. if (this._onExtensionLoadedObserver) {
  165. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  166. }
  167. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  168. },
  169. enumerable: true,
  170. configurable: true
  171. });
  172. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  173. /**
  174. * The loader state or null if not active.
  175. */
  176. get: function () {
  177. return this._loader ? this._loader.state : null;
  178. },
  179. enumerable: true,
  180. configurable: true
  181. });
  182. /**
  183. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  184. */
  185. GLTFFileLoader.prototype.dispose = function () {
  186. if (this._loader) {
  187. this._loader.dispose();
  188. this._loader = null;
  189. }
  190. this.onMeshLoadedObservable.clear();
  191. this.onTextureLoadedObservable.clear();
  192. this.onMaterialLoadedObservable.clear();
  193. this.onDisposeObservable.notifyObservers(this);
  194. this.onDisposeObservable.clear();
  195. };
  196. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  197. var _this = this;
  198. return Promise.resolve().then(function () {
  199. var loaderData = _this._parse(data);
  200. _this._loader = _this._getLoader(loaderData);
  201. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  202. });
  203. };
  204. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  205. var _this = this;
  206. return Promise.resolve().then(function () {
  207. var loaderData = _this._parse(data);
  208. _this._loader = _this._getLoader(loaderData);
  209. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  210. });
  211. };
  212. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  213. var _this = this;
  214. return Promise.resolve().then(function () {
  215. var loaderData = _this._parse(data);
  216. _this._loader = _this._getLoader(loaderData);
  217. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  218. var container = new BABYLON.AssetContainer(scene);
  219. Array.prototype.push.apply(container.meshes, result.meshes);
  220. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  221. Array.prototype.push.apply(container.skeletons, result.skeletons);
  222. container.removeAllFromScene();
  223. return container;
  224. });
  225. });
  226. };
  227. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  228. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  229. };
  230. GLTFFileLoader.prototype.createPlugin = function () {
  231. return new GLTFFileLoader();
  232. };
  233. GLTFFileLoader.prototype._parse = function (data) {
  234. var parsedData;
  235. if (data instanceof ArrayBuffer) {
  236. parsedData = GLTFFileLoader._parseBinary(data);
  237. }
  238. else {
  239. parsedData = {
  240. json: JSON.parse(data),
  241. bin: null
  242. };
  243. }
  244. this.onParsedObservable.notifyObservers(parsedData);
  245. this.onParsedObservable.clear();
  246. return parsedData;
  247. };
  248. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  249. var _this = this;
  250. var loaderVersion = { major: 2, minor: 0 };
  251. var asset = loaderData.json.asset || {};
  252. var version = GLTFFileLoader._parseVersion(asset.version);
  253. if (!version) {
  254. throw new Error("Invalid version: " + asset.version);
  255. }
  256. if (asset.minVersion !== undefined) {
  257. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  258. if (!minVersion) {
  259. throw new Error("Invalid minimum version: " + asset.minVersion);
  260. }
  261. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  262. throw new Error("Incompatible minimum version: " + asset.minVersion);
  263. }
  264. }
  265. var createLoaders = {
  266. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  267. 2: GLTFFileLoader.CreateGLTFLoaderV2
  268. };
  269. var createLoader = createLoaders[version.major];
  270. if (!createLoader) {
  271. throw new Error("Unsupported version: " + asset.version);
  272. }
  273. var loader = createLoader();
  274. loader.coordinateSystemMode = this.coordinateSystemMode;
  275. loader.animationStartMode = this.animationStartMode;
  276. loader.compileMaterials = this.compileMaterials;
  277. loader.useClipPlane = this.useClipPlane;
  278. loader.compileShadowGenerators = this.compileShadowGenerators;
  279. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  280. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  281. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  282. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  283. loader.onCompleteObservable.add(function () {
  284. _this.onMeshLoadedObservable.clear();
  285. _this.onTextureLoadedObservable.clear();
  286. _this.onMaterialLoadedObservable.clear();
  287. _this.onCompleteObservable.notifyObservers(_this);
  288. _this.onCompleteObservable.clear();
  289. });
  290. return loader;
  291. };
  292. GLTFFileLoader._parseBinary = function (data) {
  293. var Binary = {
  294. Magic: 0x46546C67
  295. };
  296. var binaryReader = new BinaryReader(data);
  297. var magic = binaryReader.readUint32();
  298. if (magic !== Binary.Magic) {
  299. throw new Error("Unexpected magic: " + magic);
  300. }
  301. var version = binaryReader.readUint32();
  302. switch (version) {
  303. case 1: return GLTFFileLoader._parseV1(binaryReader);
  304. case 2: return GLTFFileLoader._parseV2(binaryReader);
  305. }
  306. throw new Error("Unsupported version: " + version);
  307. };
  308. GLTFFileLoader._parseV1 = function (binaryReader) {
  309. var ContentFormat = {
  310. JSON: 0
  311. };
  312. var length = binaryReader.readUint32();
  313. if (length != binaryReader.getLength()) {
  314. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  315. }
  316. var contentLength = binaryReader.readUint32();
  317. var contentFormat = binaryReader.readUint32();
  318. var content;
  319. switch (contentFormat) {
  320. case ContentFormat.JSON: {
  321. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  322. break;
  323. }
  324. default: {
  325. throw new Error("Unexpected content format: " + contentFormat);
  326. }
  327. }
  328. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  329. var body = binaryReader.readUint8Array(bytesRemaining);
  330. return {
  331. json: content,
  332. bin: body
  333. };
  334. };
  335. GLTFFileLoader._parseV2 = function (binaryReader) {
  336. var ChunkFormat = {
  337. JSON: 0x4E4F534A,
  338. BIN: 0x004E4942
  339. };
  340. var length = binaryReader.readUint32();
  341. if (length !== binaryReader.getLength()) {
  342. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  343. }
  344. // JSON chunk
  345. var chunkLength = binaryReader.readUint32();
  346. var chunkFormat = binaryReader.readUint32();
  347. if (chunkFormat !== ChunkFormat.JSON) {
  348. throw new Error("First chunk format is not JSON");
  349. }
  350. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  351. // Look for BIN chunk
  352. var bin = null;
  353. while (binaryReader.getPosition() < binaryReader.getLength()) {
  354. var chunkLength_1 = binaryReader.readUint32();
  355. var chunkFormat_1 = binaryReader.readUint32();
  356. switch (chunkFormat_1) {
  357. case ChunkFormat.JSON: {
  358. throw new Error("Unexpected JSON chunk");
  359. }
  360. case ChunkFormat.BIN: {
  361. bin = binaryReader.readUint8Array(chunkLength_1);
  362. break;
  363. }
  364. default: {
  365. // ignore unrecognized chunkFormat
  366. binaryReader.skipBytes(chunkLength_1);
  367. break;
  368. }
  369. }
  370. }
  371. return {
  372. json: json,
  373. bin: bin
  374. };
  375. };
  376. GLTFFileLoader._parseVersion = function (version) {
  377. if (version === "1.0" || version === "1.0.1") {
  378. return {
  379. major: 1,
  380. minor: 0
  381. };
  382. }
  383. var match = (version + "").match(/^(\d+)\.(\d+)/);
  384. if (!match) {
  385. return null;
  386. }
  387. return {
  388. major: parseInt(match[1]),
  389. minor: parseInt(match[2])
  390. };
  391. };
  392. GLTFFileLoader._compareVersion = function (a, b) {
  393. if (a.major > b.major)
  394. return 1;
  395. if (a.major < b.major)
  396. return -1;
  397. if (a.minor > b.minor)
  398. return 1;
  399. if (a.minor < b.minor)
  400. return -1;
  401. return 0;
  402. };
  403. GLTFFileLoader._decodeBufferToText = function (buffer) {
  404. var result = "";
  405. var length = buffer.byteLength;
  406. for (var i = 0; i < length; i++) {
  407. result += String.fromCharCode(buffer[i]);
  408. }
  409. return result;
  410. };
  411. // #endregion
  412. // #region V1 options
  413. GLTFFileLoader.IncrementalLoading = true;
  414. GLTFFileLoader.HomogeneousCoordinates = false;
  415. return GLTFFileLoader;
  416. }());
  417. BABYLON.GLTFFileLoader = GLTFFileLoader;
  418. var BinaryReader = /** @class */ (function () {
  419. function BinaryReader(arrayBuffer) {
  420. this._arrayBuffer = arrayBuffer;
  421. this._dataView = new DataView(arrayBuffer);
  422. this._byteOffset = 0;
  423. }
  424. BinaryReader.prototype.getPosition = function () {
  425. return this._byteOffset;
  426. };
  427. BinaryReader.prototype.getLength = function () {
  428. return this._arrayBuffer.byteLength;
  429. };
  430. BinaryReader.prototype.readUint32 = function () {
  431. var value = this._dataView.getUint32(this._byteOffset, true);
  432. this._byteOffset += 4;
  433. return value;
  434. };
  435. BinaryReader.prototype.readUint8Array = function (length) {
  436. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  437. this._byteOffset += length;
  438. return value;
  439. };
  440. BinaryReader.prototype.skipBytes = function (length) {
  441. this._byteOffset += length;
  442. };
  443. return BinaryReader;
  444. }());
  445. if (BABYLON.SceneLoader) {
  446. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  447. }
  448. })(BABYLON || (BABYLON = {}));
  449. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  450. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  451. var BABYLON;
  452. (function (BABYLON) {
  453. var GLTF1;
  454. (function (GLTF1) {
  455. /**
  456. * Enums
  457. */
  458. var EComponentType;
  459. (function (EComponentType) {
  460. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  461. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  462. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  463. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  464. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  465. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  466. var EShaderType;
  467. (function (EShaderType) {
  468. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  469. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  470. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  471. var EParameterType;
  472. (function (EParameterType) {
  473. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  474. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  475. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  476. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  477. EParameterType[EParameterType["INT"] = 5124] = "INT";
  478. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  479. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  480. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  481. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  482. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  483. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  484. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  485. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  486. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  487. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  488. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  489. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  490. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  491. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  492. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  493. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  494. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  495. var ETextureWrapMode;
  496. (function (ETextureWrapMode) {
  497. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  498. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  499. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  500. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  501. var ETextureFilterType;
  502. (function (ETextureFilterType) {
  503. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  504. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  505. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  506. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  507. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  508. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  509. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  510. var ETextureFormat;
  511. (function (ETextureFormat) {
  512. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  513. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  514. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  515. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  516. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  517. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  518. var ECullingType;
  519. (function (ECullingType) {
  520. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  521. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  522. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  523. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  524. var EBlendingFunction;
  525. (function (EBlendingFunction) {
  526. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  527. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  528. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  529. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  530. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  531. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  532. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  533. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  534. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  535. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  536. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  537. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  538. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  539. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  540. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  541. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  542. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  543. })(BABYLON || (BABYLON = {}));
  544. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  545. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  546. var BABYLON;
  547. (function (BABYLON) {
  548. var GLTF1;
  549. (function (GLTF1) {
  550. /**
  551. * Tokenizer. Used for shaders compatibility
  552. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  553. */
  554. var ETokenType;
  555. (function (ETokenType) {
  556. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  557. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  558. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  559. })(ETokenType || (ETokenType = {}));
  560. var Tokenizer = /** @class */ (function () {
  561. function Tokenizer(toParse) {
  562. this._pos = 0;
  563. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  564. this._toParse = toParse;
  565. this._maxPos = toParse.length;
  566. }
  567. Tokenizer.prototype.getNextToken = function () {
  568. if (this.isEnd())
  569. return ETokenType.END_OF_INPUT;
  570. this.currentString = this.read();
  571. this.currentToken = ETokenType.UNKNOWN;
  572. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  573. this.currentToken = ETokenType.IDENTIFIER;
  574. this.currentIdentifier = this.currentString;
  575. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  576. this.currentIdentifier += this.currentString;
  577. this.forward();
  578. }
  579. }
  580. return this.currentToken;
  581. };
  582. Tokenizer.prototype.peek = function () {
  583. return this._toParse[this._pos];
  584. };
  585. Tokenizer.prototype.read = function () {
  586. return this._toParse[this._pos++];
  587. };
  588. Tokenizer.prototype.forward = function () {
  589. this._pos++;
  590. };
  591. Tokenizer.prototype.isEnd = function () {
  592. return this._pos >= this._maxPos;
  593. };
  594. return Tokenizer;
  595. }());
  596. /**
  597. * Values
  598. */
  599. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  600. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  601. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  602. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  603. /**
  604. * Parse
  605. */
  606. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  607. for (var buf in parsedBuffers) {
  608. var parsedBuffer = parsedBuffers[buf];
  609. gltfRuntime.buffers[buf] = parsedBuffer;
  610. gltfRuntime.buffersCount++;
  611. }
  612. };
  613. var parseShaders = function (parsedShaders, gltfRuntime) {
  614. for (var sha in parsedShaders) {
  615. var parsedShader = parsedShaders[sha];
  616. gltfRuntime.shaders[sha] = parsedShader;
  617. gltfRuntime.shaderscount++;
  618. }
  619. };
  620. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  621. for (var object in parsedObjects) {
  622. var parsedObject = parsedObjects[object];
  623. gltfRuntime[runtimeProperty][object] = parsedObject;
  624. }
  625. };
  626. /**
  627. * Utils
  628. */
  629. var normalizeUVs = function (buffer) {
  630. if (!buffer) {
  631. return;
  632. }
  633. for (var i = 0; i < buffer.length / 2; i++) {
  634. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  635. }
  636. };
  637. var getAttribute = function (attributeParameter) {
  638. if (attributeParameter.semantic === "NORMAL") {
  639. return "normal";
  640. }
  641. else if (attributeParameter.semantic === "POSITION") {
  642. return "position";
  643. }
  644. else if (attributeParameter.semantic === "JOINT") {
  645. return "matricesIndices";
  646. }
  647. else if (attributeParameter.semantic === "WEIGHT") {
  648. return "matricesWeights";
  649. }
  650. else if (attributeParameter.semantic === "COLOR") {
  651. return "color";
  652. }
  653. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  654. var channel = Number(attributeParameter.semantic.split("_")[1]);
  655. return "uv" + (channel === 0 ? "" : channel + 1);
  656. }
  657. return null;
  658. };
  659. /**
  660. * Loads and creates animations
  661. */
  662. var loadAnimations = function (gltfRuntime) {
  663. for (var anim in gltfRuntime.animations) {
  664. var animation = gltfRuntime.animations[anim];
  665. if (!animation.channels || !animation.samplers) {
  666. continue;
  667. }
  668. var lastAnimation = null;
  669. for (var i = 0; i < animation.channels.length; i++) {
  670. // Get parameters and load buffers
  671. var channel = animation.channels[i];
  672. var sampler = animation.samplers[channel.sampler];
  673. if (!sampler) {
  674. continue;
  675. }
  676. var inputData = null;
  677. var outputData = null;
  678. if (animation.parameters) {
  679. inputData = animation.parameters[sampler.input];
  680. outputData = animation.parameters[sampler.output];
  681. }
  682. else {
  683. inputData = sampler.input;
  684. outputData = sampler.output;
  685. }
  686. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  687. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  688. var targetID = channel.target.id;
  689. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  690. if (targetNode === null) {
  691. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  692. }
  693. if (targetNode === null) {
  694. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  695. continue;
  696. }
  697. var isBone = targetNode instanceof BABYLON.Bone;
  698. // Get target path (position, rotation or scaling)
  699. var targetPath = channel.target.path;
  700. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  701. if (targetPathIndex !== -1) {
  702. targetPath = babylonAnimationPaths[targetPathIndex];
  703. }
  704. // Determine animation type
  705. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  706. if (!isBone) {
  707. if (targetPath === "rotationQuaternion") {
  708. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  709. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  710. }
  711. else {
  712. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  713. }
  714. }
  715. // Create animation and key frames
  716. var babylonAnimation = null;
  717. var keys = [];
  718. var arrayOffset = 0;
  719. var modifyKey = false;
  720. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  721. babylonAnimation = lastAnimation;
  722. modifyKey = true;
  723. }
  724. if (!modifyKey) {
  725. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  726. }
  727. // For each frame
  728. for (var j = 0; j < bufferInput.length; j++) {
  729. var value = null;
  730. if (targetPath === "rotationQuaternion") {
  731. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  732. arrayOffset += 4;
  733. }
  734. else {
  735. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  736. arrayOffset += 3;
  737. }
  738. if (isBone) {
  739. var bone = targetNode;
  740. var translation = BABYLON.Vector3.Zero();
  741. var rotationQuaternion = new BABYLON.Quaternion();
  742. var scaling = BABYLON.Vector3.Zero();
  743. // Warning on decompose
  744. var mat = bone.getBaseMatrix();
  745. if (modifyKey && lastAnimation) {
  746. mat = lastAnimation.getKeys()[j].value;
  747. }
  748. mat.decompose(scaling, rotationQuaternion, translation);
  749. if (targetPath === "position") {
  750. translation = value;
  751. }
  752. else if (targetPath === "rotationQuaternion") {
  753. rotationQuaternion = value;
  754. }
  755. else {
  756. scaling = value;
  757. }
  758. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  759. }
  760. if (!modifyKey) {
  761. keys.push({
  762. frame: bufferInput[j],
  763. value: value
  764. });
  765. }
  766. else if (lastAnimation) {
  767. lastAnimation.getKeys()[j].value = value;
  768. }
  769. }
  770. // Finish
  771. if (!modifyKey && babylonAnimation) {
  772. babylonAnimation.setKeys(keys);
  773. targetNode.animations.push(babylonAnimation);
  774. }
  775. lastAnimation = babylonAnimation;
  776. gltfRuntime.scene.stopAnimation(targetNode);
  777. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  778. }
  779. }
  780. };
  781. /**
  782. * Returns the bones transformation matrix
  783. */
  784. var configureBoneTransformation = function (node) {
  785. var mat = null;
  786. if (node.translation || node.rotation || node.scale) {
  787. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  788. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  789. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  790. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  791. }
  792. else {
  793. mat = BABYLON.Matrix.FromArray(node.matrix);
  794. }
  795. return mat;
  796. };
  797. /**
  798. * Returns the parent bone
  799. */
  800. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  801. // Try to find
  802. for (var i = 0; i < newSkeleton.bones.length; i++) {
  803. if (newSkeleton.bones[i].name === jointName) {
  804. return newSkeleton.bones[i];
  805. }
  806. }
  807. // Not found, search in gltf nodes
  808. var nodes = gltfRuntime.nodes;
  809. for (var nde in nodes) {
  810. var node = nodes[nde];
  811. if (!node.jointName) {
  812. continue;
  813. }
  814. var children = node.children;
  815. for (var i = 0; i < children.length; i++) {
  816. var child = gltfRuntime.nodes[children[i]];
  817. if (!child.jointName) {
  818. continue;
  819. }
  820. if (child.jointName === jointName) {
  821. var mat = configureBoneTransformation(node);
  822. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  823. bone.id = nde;
  824. return bone;
  825. }
  826. }
  827. }
  828. return null;
  829. };
  830. /**
  831. * Returns the appropriate root node
  832. */
  833. var getNodeToRoot = function (nodesToRoot, id) {
  834. for (var i = 0; i < nodesToRoot.length; i++) {
  835. var nodeToRoot = nodesToRoot[i];
  836. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  837. var child = nodeToRoot.node.children[j];
  838. if (child === id) {
  839. return nodeToRoot.bone;
  840. }
  841. }
  842. }
  843. return null;
  844. };
  845. /**
  846. * Returns the node with the joint name
  847. */
  848. var getJointNode = function (gltfRuntime, jointName) {
  849. var nodes = gltfRuntime.nodes;
  850. var node = nodes[jointName];
  851. if (node) {
  852. return {
  853. node: node,
  854. id: jointName
  855. };
  856. }
  857. for (var nde in nodes) {
  858. node = nodes[nde];
  859. if (node.jointName === jointName) {
  860. return {
  861. node: node,
  862. id: nde
  863. };
  864. }
  865. }
  866. return null;
  867. };
  868. /**
  869. * Checks if a nodes is in joints
  870. */
  871. var nodeIsInJoints = function (skins, id) {
  872. for (var i = 0; i < skins.jointNames.length; i++) {
  873. if (skins.jointNames[i] === id) {
  874. return true;
  875. }
  876. }
  877. return false;
  878. };
  879. /**
  880. * Fills the nodes to root for bones and builds hierarchy
  881. */
  882. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  883. // Creates nodes for root
  884. for (var nde in gltfRuntime.nodes) {
  885. var node = gltfRuntime.nodes[nde];
  886. var id = nde;
  887. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  888. continue;
  889. }
  890. // Create node to root bone
  891. var mat = configureBoneTransformation(node);
  892. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  893. bone.id = id;
  894. nodesToRoot.push({ bone: bone, node: node, id: id });
  895. }
  896. // Parenting
  897. for (var i = 0; i < nodesToRoot.length; i++) {
  898. var nodeToRoot = nodesToRoot[i];
  899. var children = nodeToRoot.node.children;
  900. for (var j = 0; j < children.length; j++) {
  901. var child = null;
  902. for (var k = 0; k < nodesToRoot.length; k++) {
  903. if (nodesToRoot[k].id === children[j]) {
  904. child = nodesToRoot[k];
  905. break;
  906. }
  907. }
  908. if (child) {
  909. child.bone._parent = nodeToRoot.bone;
  910. nodeToRoot.bone.children.push(child.bone);
  911. }
  912. }
  913. }
  914. };
  915. /**
  916. * Imports a skeleton
  917. */
  918. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  919. if (!newSkeleton) {
  920. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  921. }
  922. if (!skins.babylonSkeleton) {
  923. return newSkeleton;
  924. }
  925. // Find the root bones
  926. var nodesToRoot = [];
  927. var nodesToRootToAdd = [];
  928. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  929. newSkeleton.bones = [];
  930. // Joints
  931. for (var i = 0; i < skins.jointNames.length; i++) {
  932. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  933. if (!jointNode) {
  934. continue;
  935. }
  936. var node = jointNode.node;
  937. if (!node) {
  938. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  939. continue;
  940. }
  941. var id = jointNode.id;
  942. // Optimize, if the bone already exists...
  943. var existingBone = gltfRuntime.scene.getBoneByID(id);
  944. if (existingBone) {
  945. newSkeleton.bones.push(existingBone);
  946. continue;
  947. }
  948. // Search for parent bone
  949. var foundBone = false;
  950. var parentBone = null;
  951. for (var j = 0; j < i; j++) {
  952. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  953. if (!jointNode_1) {
  954. continue;
  955. }
  956. var joint = jointNode_1.node;
  957. if (!joint) {
  958. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  959. continue;
  960. }
  961. var children = joint.children;
  962. if (!children) {
  963. continue;
  964. }
  965. foundBone = false;
  966. for (var k = 0; k < children.length; k++) {
  967. if (children[k] === id) {
  968. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  969. foundBone = true;
  970. break;
  971. }
  972. }
  973. if (foundBone) {
  974. break;
  975. }
  976. }
  977. // Create bone
  978. var mat = configureBoneTransformation(node);
  979. if (!parentBone && nodesToRoot.length > 0) {
  980. parentBone = getNodeToRoot(nodesToRoot, id);
  981. if (parentBone) {
  982. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  983. nodesToRootToAdd.push(parentBone);
  984. }
  985. }
  986. }
  987. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  988. bone.id = id;
  989. }
  990. // Polish
  991. var bones = newSkeleton.bones;
  992. newSkeleton.bones = [];
  993. for (var i = 0; i < skins.jointNames.length; i++) {
  994. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  995. if (!jointNode) {
  996. continue;
  997. }
  998. for (var j = 0; j < bones.length; j++) {
  999. if (bones[j].id === jointNode.id) {
  1000. newSkeleton.bones.push(bones[j]);
  1001. break;
  1002. }
  1003. }
  1004. }
  1005. newSkeleton.prepare();
  1006. // Finish
  1007. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  1008. newSkeleton.bones.push(nodesToRootToAdd[i]);
  1009. }
  1010. return newSkeleton;
  1011. };
  1012. /**
  1013. * Imports a mesh and its geometries
  1014. */
  1015. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  1016. if (!newMesh) {
  1017. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1018. newMesh.id = id;
  1019. }
  1020. if (!node.babylonNode) {
  1021. return newMesh;
  1022. }
  1023. var subMaterials = [];
  1024. var vertexData = null;
  1025. var verticesStarts = new Array();
  1026. var verticesCounts = new Array();
  1027. var indexStarts = new Array();
  1028. var indexCounts = new Array();
  1029. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1030. var meshID = meshes[meshIndex];
  1031. var mesh = gltfRuntime.meshes[meshID];
  1032. if (!mesh) {
  1033. continue;
  1034. }
  1035. // Positions, normals and UVs
  1036. for (var i = 0; i < mesh.primitives.length; i++) {
  1037. // Temporary vertex data
  1038. var tempVertexData = new BABYLON.VertexData();
  1039. var primitive = mesh.primitives[i];
  1040. if (primitive.mode !== 4) {
  1041. // continue;
  1042. }
  1043. var attributes = primitive.attributes;
  1044. var accessor = null;
  1045. var buffer = null;
  1046. // Set positions, normal and uvs
  1047. for (var semantic in attributes) {
  1048. // Link accessor and buffer view
  1049. accessor = gltfRuntime.accessors[attributes[semantic]];
  1050. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1051. if (semantic === "NORMAL") {
  1052. tempVertexData.normals = new Float32Array(buffer.length);
  1053. tempVertexData.normals.set(buffer);
  1054. }
  1055. else if (semantic === "POSITION") {
  1056. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  1057. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  1058. for (var j = 0; j < buffer.length; j += 4) {
  1059. tempVertexData.positions[j] = buffer[j];
  1060. tempVertexData.positions[j + 1] = buffer[j + 1];
  1061. tempVertexData.positions[j + 2] = buffer[j + 2];
  1062. }
  1063. }
  1064. else {
  1065. tempVertexData.positions = new Float32Array(buffer.length);
  1066. tempVertexData.positions.set(buffer);
  1067. }
  1068. verticesCounts.push(tempVertexData.positions.length);
  1069. }
  1070. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  1071. var channel = Number(semantic.split("_")[1]);
  1072. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  1073. var uvs = new Float32Array(buffer.length);
  1074. uvs.set(buffer);
  1075. normalizeUVs(uvs);
  1076. tempVertexData.set(uvs, uvKind);
  1077. }
  1078. else if (semantic === "JOINT") {
  1079. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  1080. tempVertexData.matricesIndices.set(buffer);
  1081. }
  1082. else if (semantic === "WEIGHT") {
  1083. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  1084. tempVertexData.matricesWeights.set(buffer);
  1085. }
  1086. else if (semantic === "COLOR") {
  1087. tempVertexData.colors = new Float32Array(buffer.length);
  1088. tempVertexData.colors.set(buffer);
  1089. }
  1090. }
  1091. // Indices
  1092. accessor = gltfRuntime.accessors[primitive.indices];
  1093. if (accessor) {
  1094. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  1095. tempVertexData.indices = new Int32Array(buffer.length);
  1096. tempVertexData.indices.set(buffer);
  1097. indexCounts.push(tempVertexData.indices.length);
  1098. }
  1099. else {
  1100. // Set indices on the fly
  1101. var indices = [];
  1102. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  1103. indices.push(j);
  1104. }
  1105. tempVertexData.indices = new Int32Array(indices);
  1106. indexCounts.push(tempVertexData.indices.length);
  1107. }
  1108. if (!vertexData) {
  1109. vertexData = tempVertexData;
  1110. }
  1111. else {
  1112. vertexData.merge(tempVertexData);
  1113. }
  1114. // Sub material
  1115. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  1116. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  1117. // Update vertices start and index start
  1118. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  1119. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  1120. }
  1121. }
  1122. var material;
  1123. if (subMaterials.length > 1) {
  1124. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  1125. material.subMaterials = subMaterials;
  1126. }
  1127. else {
  1128. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  1129. }
  1130. if (subMaterials.length === 1) {
  1131. material = subMaterials[0];
  1132. }
  1133. if (!newMesh.material) {
  1134. newMesh.material = material;
  1135. }
  1136. // Apply geometry
  1137. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  1138. newMesh.computeWorldMatrix(true);
  1139. // Apply submeshes
  1140. newMesh.subMeshes = [];
  1141. var index = 0;
  1142. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  1143. var meshID = meshes[meshIndex];
  1144. var mesh = gltfRuntime.meshes[meshID];
  1145. if (!mesh) {
  1146. continue;
  1147. }
  1148. for (var i = 0; i < mesh.primitives.length; i++) {
  1149. if (mesh.primitives[i].mode !== 4) {
  1150. //continue;
  1151. }
  1152. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  1153. index++;
  1154. }
  1155. }
  1156. // Finish
  1157. return newMesh;
  1158. };
  1159. /**
  1160. * Configure node transformation from position, rotation and scaling
  1161. */
  1162. var configureNode = function (newNode, position, rotation, scaling) {
  1163. if (newNode.position) {
  1164. newNode.position = position;
  1165. }
  1166. if (newNode.rotationQuaternion || newNode.rotation) {
  1167. newNode.rotationQuaternion = rotation;
  1168. }
  1169. if (newNode.scaling) {
  1170. newNode.scaling = scaling;
  1171. }
  1172. };
  1173. /**
  1174. * Configures node from transformation matrix
  1175. */
  1176. var configureNodeFromMatrix = function (newNode, node, parent) {
  1177. if (node.matrix) {
  1178. var position = new BABYLON.Vector3(0, 0, 0);
  1179. var rotation = new BABYLON.Quaternion();
  1180. var scaling = new BABYLON.Vector3(0, 0, 0);
  1181. var mat = BABYLON.Matrix.FromArray(node.matrix);
  1182. mat.decompose(scaling, rotation, position);
  1183. configureNode(newNode, position, rotation, scaling);
  1184. }
  1185. else if (node.translation && node.rotation && node.scale) {
  1186. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  1187. }
  1188. newNode.computeWorldMatrix(true);
  1189. };
  1190. /**
  1191. * Imports a node
  1192. */
  1193. var importNode = function (gltfRuntime, node, id, parent) {
  1194. var lastNode = null;
  1195. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  1196. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  1197. return null;
  1198. }
  1199. }
  1200. // Meshes
  1201. if (node.skin) {
  1202. if (node.meshes) {
  1203. var skin = gltfRuntime.skins[node.skin];
  1204. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  1205. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  1206. if (newMesh.skeleton === null) {
  1207. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  1208. if (!skin.babylonSkeleton) {
  1209. skin.babylonSkeleton = newMesh.skeleton;
  1210. }
  1211. }
  1212. lastNode = newMesh;
  1213. }
  1214. }
  1215. else if (node.meshes) {
  1216. /**
  1217. * Improve meshes property
  1218. */
  1219. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1220. lastNode = newMesh;
  1221. }
  1222. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1223. var light = gltfRuntime.lights[node.light];
  1224. if (light) {
  1225. if (light.type === "ambient") {
  1226. var ambienLight = light[light.type];
  1227. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1228. hemiLight.name = node.name || "";
  1229. if (ambienLight.color) {
  1230. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1231. }
  1232. lastNode = hemiLight;
  1233. }
  1234. else if (light.type === "directional") {
  1235. var directionalLight = light[light.type];
  1236. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1237. dirLight.name = node.name || "";
  1238. if (directionalLight.color) {
  1239. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1240. }
  1241. lastNode = dirLight;
  1242. }
  1243. else if (light.type === "point") {
  1244. var pointLight = light[light.type];
  1245. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1246. ptLight.name = node.name || "";
  1247. if (pointLight.color) {
  1248. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1249. }
  1250. lastNode = ptLight;
  1251. }
  1252. else if (light.type === "spot") {
  1253. var spotLight = light[light.type];
  1254. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1255. spLight.name = node.name || "";
  1256. if (spotLight.color) {
  1257. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1258. }
  1259. if (spotLight.fallOfAngle) {
  1260. spLight.angle = spotLight.fallOfAngle;
  1261. }
  1262. if (spotLight.fallOffExponent) {
  1263. spLight.exponent = spotLight.fallOffExponent;
  1264. }
  1265. lastNode = spLight;
  1266. }
  1267. }
  1268. }
  1269. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1270. var camera = gltfRuntime.cameras[node.camera];
  1271. if (camera) {
  1272. if (camera.type === "orthographic") {
  1273. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1274. orthoCamera.name = node.name || "";
  1275. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1276. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1277. lastNode = orthoCamera;
  1278. }
  1279. else if (camera.type === "perspective") {
  1280. var perspectiveCamera = camera[camera.type];
  1281. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1282. persCamera.name = node.name || "";
  1283. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1284. if (!perspectiveCamera.aspectRatio) {
  1285. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1286. }
  1287. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1288. persCamera.maxZ = perspectiveCamera.zfar;
  1289. persCamera.minZ = perspectiveCamera.znear;
  1290. }
  1291. lastNode = persCamera;
  1292. }
  1293. }
  1294. }
  1295. // Empty node
  1296. if (!node.jointName) {
  1297. if (node.babylonNode) {
  1298. return node.babylonNode;
  1299. }
  1300. else if (lastNode === null) {
  1301. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  1302. node.babylonNode = dummy;
  1303. lastNode = dummy;
  1304. }
  1305. }
  1306. if (lastNode !== null) {
  1307. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1308. configureNodeFromMatrix(lastNode, node, parent);
  1309. }
  1310. else {
  1311. var translation = node.translation || [0, 0, 0];
  1312. var rotation = node.rotation || [0, 0, 0, 1];
  1313. var scale = node.scale || [1, 1, 1];
  1314. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1315. }
  1316. lastNode.updateCache(true);
  1317. node.babylonNode = lastNode;
  1318. }
  1319. return lastNode;
  1320. };
  1321. /**
  1322. * Traverses nodes and creates them
  1323. */
  1324. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1325. if (meshIncluded === void 0) { meshIncluded = false; }
  1326. var node = gltfRuntime.nodes[id];
  1327. var newNode = null;
  1328. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1329. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1330. meshIncluded = true;
  1331. }
  1332. else {
  1333. meshIncluded = false;
  1334. }
  1335. }
  1336. else {
  1337. meshIncluded = true;
  1338. }
  1339. if (!node.jointName && meshIncluded) {
  1340. newNode = importNode(gltfRuntime, node, id, parent);
  1341. if (newNode !== null) {
  1342. newNode.id = id;
  1343. newNode.parent = parent;
  1344. }
  1345. }
  1346. if (node.children) {
  1347. for (var i = 0; i < node.children.length; i++) {
  1348. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1349. }
  1350. }
  1351. };
  1352. /**
  1353. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1354. */
  1355. var postLoad = function (gltfRuntime) {
  1356. // Nodes
  1357. var currentScene = gltfRuntime.currentScene;
  1358. if (currentScene) {
  1359. for (var i = 0; i < currentScene.nodes.length; i++) {
  1360. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1361. }
  1362. }
  1363. else {
  1364. for (var thing in gltfRuntime.scenes) {
  1365. currentScene = gltfRuntime.scenes[thing];
  1366. for (var i = 0; i < currentScene.nodes.length; i++) {
  1367. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1368. }
  1369. }
  1370. }
  1371. // Set animations
  1372. loadAnimations(gltfRuntime);
  1373. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1374. var skeleton = gltfRuntime.scene.skeletons[i];
  1375. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1376. }
  1377. };
  1378. /**
  1379. * onBind shaderrs callback to set uniforms and matrices
  1380. */
  1381. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1382. var materialValues = material.values || technique.parameters;
  1383. for (var unif in unTreatedUniforms) {
  1384. var uniform = unTreatedUniforms[unif];
  1385. var type = uniform.type;
  1386. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1387. if (uniform.semantic && !uniform.source && !uniform.node) {
  1388. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1389. }
  1390. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1391. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1392. if (source === null) {
  1393. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1394. }
  1395. if (source === null) {
  1396. continue;
  1397. }
  1398. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1399. }
  1400. }
  1401. else {
  1402. var value = materialValues[technique.uniforms[unif]];
  1403. if (!value) {
  1404. continue;
  1405. }
  1406. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1407. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1408. if (texture === null || texture === undefined) {
  1409. continue;
  1410. }
  1411. shaderMaterial.getEffect().setTexture(unif, texture);
  1412. }
  1413. else {
  1414. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1415. }
  1416. }
  1417. }
  1418. onSuccess(shaderMaterial);
  1419. };
  1420. /**
  1421. * Prepare uniforms to send the only one time
  1422. * Loads the appropriate textures
  1423. */
  1424. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1425. var materialValues = material.values || technique.parameters;
  1426. var techniqueUniforms = technique.uniforms;
  1427. /**
  1428. * Prepare values here (not matrices)
  1429. */
  1430. for (var unif in unTreatedUniforms) {
  1431. var uniform = unTreatedUniforms[unif];
  1432. var type = uniform.type;
  1433. var value = materialValues[techniqueUniforms[unif]];
  1434. if (value === undefined) {
  1435. // In case the value is the same for all materials
  1436. value = uniform.value;
  1437. }
  1438. if (!value) {
  1439. continue;
  1440. }
  1441. var onLoadTexture = function (uniformName) {
  1442. return function (texture) {
  1443. if (uniform.value && uniformName) {
  1444. // Static uniform
  1445. shaderMaterial.setTexture(uniformName, texture);
  1446. delete unTreatedUniforms[uniformName];
  1447. }
  1448. };
  1449. };
  1450. // Texture (sampler2D)
  1451. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1452. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1453. }
  1454. else {
  1455. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1456. // Static uniform
  1457. delete unTreatedUniforms[unif];
  1458. }
  1459. }
  1460. }
  1461. };
  1462. /**
  1463. * Shader compilation failed
  1464. */
  1465. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1466. return function (effect, error) {
  1467. shaderMaterial.dispose(true);
  1468. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1469. };
  1470. };
  1471. /**
  1472. * Shader compilation success
  1473. */
  1474. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1475. return function (_) {
  1476. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1477. shaderMaterial.onBind = function (mesh) {
  1478. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1479. };
  1480. };
  1481. };
  1482. /**
  1483. * Returns the appropriate uniform if already handled by babylon
  1484. */
  1485. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1486. for (var unif in technique.uniforms) {
  1487. var uniform = technique.uniforms[unif];
  1488. var uniformParameter = technique.parameters[uniform];
  1489. if (tokenizer.currentIdentifier === unif) {
  1490. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1491. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1492. if (transformIndex !== -1) {
  1493. delete unTreatedUniforms[unif];
  1494. return babylonTransforms[transformIndex];
  1495. }
  1496. }
  1497. }
  1498. }
  1499. return tokenizer.currentIdentifier;
  1500. };
  1501. /**
  1502. * All shaders loaded. Create materials one by one
  1503. */
  1504. var importMaterials = function (gltfRuntime) {
  1505. // Create materials
  1506. for (var mat in gltfRuntime.materials) {
  1507. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1508. }
  1509. };
  1510. /**
  1511. * Implementation of the base glTF spec
  1512. */
  1513. var GLTFLoaderBase = /** @class */ (function () {
  1514. function GLTFLoaderBase() {
  1515. }
  1516. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1517. var gltfRuntime = {
  1518. extensions: {},
  1519. accessors: {},
  1520. buffers: {},
  1521. bufferViews: {},
  1522. meshes: {},
  1523. lights: {},
  1524. cameras: {},
  1525. nodes: {},
  1526. images: {},
  1527. textures: {},
  1528. shaders: {},
  1529. programs: {},
  1530. samplers: {},
  1531. techniques: {},
  1532. materials: {},
  1533. animations: {},
  1534. skins: {},
  1535. extensionsUsed: [],
  1536. scenes: {},
  1537. buffersCount: 0,
  1538. shaderscount: 0,
  1539. scene: scene,
  1540. rootUrl: rootUrl,
  1541. loadedBufferCount: 0,
  1542. loadedBufferViews: {},
  1543. loadedShaderCount: 0,
  1544. importOnlyMeshes: false,
  1545. dummyNodes: []
  1546. };
  1547. // Parse
  1548. if (parsedData.extensions) {
  1549. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1550. }
  1551. if (parsedData.extensionsUsed) {
  1552. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1553. }
  1554. if (parsedData.buffers) {
  1555. parseBuffers(parsedData.buffers, gltfRuntime);
  1556. }
  1557. if (parsedData.bufferViews) {
  1558. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1559. }
  1560. if (parsedData.accessors) {
  1561. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1562. }
  1563. if (parsedData.meshes) {
  1564. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1565. }
  1566. if (parsedData.lights) {
  1567. parseObject(parsedData.lights, "lights", gltfRuntime);
  1568. }
  1569. if (parsedData.cameras) {
  1570. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1571. }
  1572. if (parsedData.nodes) {
  1573. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1574. }
  1575. if (parsedData.images) {
  1576. parseObject(parsedData.images, "images", gltfRuntime);
  1577. }
  1578. if (parsedData.textures) {
  1579. parseObject(parsedData.textures, "textures", gltfRuntime);
  1580. }
  1581. if (parsedData.shaders) {
  1582. parseShaders(parsedData.shaders, gltfRuntime);
  1583. }
  1584. if (parsedData.programs) {
  1585. parseObject(parsedData.programs, "programs", gltfRuntime);
  1586. }
  1587. if (parsedData.samplers) {
  1588. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1589. }
  1590. if (parsedData.techniques) {
  1591. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1592. }
  1593. if (parsedData.materials) {
  1594. parseObject(parsedData.materials, "materials", gltfRuntime);
  1595. }
  1596. if (parsedData.animations) {
  1597. parseObject(parsedData.animations, "animations", gltfRuntime);
  1598. }
  1599. if (parsedData.skins) {
  1600. parseObject(parsedData.skins, "skins", gltfRuntime);
  1601. }
  1602. if (parsedData.scenes) {
  1603. gltfRuntime.scenes = parsedData.scenes;
  1604. }
  1605. if (parsedData.scene && parsedData.scenes) {
  1606. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1607. }
  1608. return gltfRuntime;
  1609. };
  1610. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1611. var buffer = gltfRuntime.buffers[id];
  1612. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  1613. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  1614. }
  1615. else {
  1616. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1617. if (request) {
  1618. onError(request.status + " " + request.statusText);
  1619. }
  1620. });
  1621. }
  1622. };
  1623. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1624. var texture = gltfRuntime.textures[id];
  1625. if (!texture || !texture.source) {
  1626. onError("");
  1627. return;
  1628. }
  1629. if (texture.babylonTexture) {
  1630. onSuccess(null);
  1631. return;
  1632. }
  1633. var source = gltfRuntime.images[texture.source];
  1634. if (BABYLON.Tools.IsBase64(source.uri)) {
  1635. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  1636. }
  1637. else {
  1638. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1639. if (request) {
  1640. onError(request.status + " " + request.statusText);
  1641. }
  1642. });
  1643. }
  1644. };
  1645. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1646. var texture = gltfRuntime.textures[id];
  1647. if (texture.babylonTexture) {
  1648. onSuccess(texture.babylonTexture);
  1649. return;
  1650. }
  1651. var sampler = gltfRuntime.samplers[texture.sampler];
  1652. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1653. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1654. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1655. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1656. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1657. var blob = new Blob([buffer]);
  1658. var blobURL = URL.createObjectURL(blob);
  1659. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1660. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1661. if (sampler.wrapS !== undefined) {
  1662. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1663. }
  1664. if (sampler.wrapT !== undefined) {
  1665. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1666. }
  1667. newTexture.name = id;
  1668. texture.babylonTexture = newTexture;
  1669. onSuccess(newTexture);
  1670. };
  1671. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1672. var shader = gltfRuntime.shaders[id];
  1673. if (BABYLON.Tools.IsBase64(shader.uri)) {
  1674. var shaderString = atob(shader.uri.split(",")[1]);
  1675. onSuccess(shaderString);
  1676. }
  1677. else {
  1678. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1679. if (request) {
  1680. onError(request.status + " " + request.statusText);
  1681. }
  1682. });
  1683. }
  1684. };
  1685. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1686. var material = gltfRuntime.materials[id];
  1687. if (!material.technique) {
  1688. if (onError) {
  1689. onError("No technique found.");
  1690. }
  1691. return;
  1692. }
  1693. var technique = gltfRuntime.techniques[material.technique];
  1694. if (!technique) {
  1695. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1696. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1697. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1698. onSuccess(defaultMaterial);
  1699. return;
  1700. }
  1701. var program = gltfRuntime.programs[technique.program];
  1702. var states = technique.states;
  1703. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1704. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1705. var newVertexShader = "";
  1706. var newPixelShader = "";
  1707. var vertexTokenizer = new Tokenizer(vertexShader);
  1708. var pixelTokenizer = new Tokenizer(pixelShader);
  1709. var unTreatedUniforms = {};
  1710. var uniforms = [];
  1711. var attributes = [];
  1712. var samplers = [];
  1713. // Fill uniform, sampler2D and attributes
  1714. for (var unif in technique.uniforms) {
  1715. var uniform = technique.uniforms[unif];
  1716. var uniformParameter = technique.parameters[uniform];
  1717. unTreatedUniforms[unif] = uniformParameter;
  1718. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1719. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1720. if (transformIndex !== -1) {
  1721. uniforms.push(babylonTransforms[transformIndex]);
  1722. delete unTreatedUniforms[unif];
  1723. }
  1724. else {
  1725. uniforms.push(unif);
  1726. }
  1727. }
  1728. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1729. samplers.push(unif);
  1730. }
  1731. else {
  1732. uniforms.push(unif);
  1733. }
  1734. }
  1735. for (var attr in technique.attributes) {
  1736. var attribute = technique.attributes[attr];
  1737. var attributeParameter = technique.parameters[attribute];
  1738. if (attributeParameter.semantic) {
  1739. attributes.push(getAttribute(attributeParameter));
  1740. }
  1741. }
  1742. // Configure vertex shader
  1743. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1744. var tokenType = vertexTokenizer.currentToken;
  1745. if (tokenType !== ETokenType.IDENTIFIER) {
  1746. newVertexShader += vertexTokenizer.currentString;
  1747. continue;
  1748. }
  1749. var foundAttribute = false;
  1750. for (var attr in technique.attributes) {
  1751. var attribute = technique.attributes[attr];
  1752. var attributeParameter = technique.parameters[attribute];
  1753. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1754. newVertexShader += getAttribute(attributeParameter);
  1755. foundAttribute = true;
  1756. break;
  1757. }
  1758. }
  1759. if (foundAttribute) {
  1760. continue;
  1761. }
  1762. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1763. }
  1764. // Configure pixel shader
  1765. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1766. var tokenType = pixelTokenizer.currentToken;
  1767. if (tokenType !== ETokenType.IDENTIFIER) {
  1768. newPixelShader += pixelTokenizer.currentString;
  1769. continue;
  1770. }
  1771. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1772. }
  1773. // Create shader material
  1774. var shaderPath = {
  1775. vertex: program.vertexShader + id,
  1776. fragment: program.fragmentShader + id
  1777. };
  1778. var options = {
  1779. attributes: attributes,
  1780. uniforms: uniforms,
  1781. samplers: samplers,
  1782. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1783. };
  1784. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1785. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1786. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1787. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1788. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1789. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1790. if (states && states.functions) {
  1791. var functions = states.functions;
  1792. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1793. shaderMaterial.backFaceCulling = false;
  1794. }
  1795. var blendFunc = functions.blendFuncSeparate;
  1796. if (blendFunc) {
  1797. if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1798. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1799. }
  1800. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1801. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1802. }
  1803. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1804. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1805. }
  1806. else if (blendFunc[0] === GLTF1.EBlendingFunction.ZERO && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1807. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1808. }
  1809. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1810. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1811. }
  1812. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1813. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1814. }
  1815. }
  1816. }
  1817. };
  1818. return GLTFLoaderBase;
  1819. }());
  1820. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1821. /**
  1822. * glTF V1 Loader
  1823. */
  1824. var GLTFLoader = /** @class */ (function () {
  1825. function GLTFLoader() {
  1826. // #region Stubs for IGLTFLoader interface
  1827. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  1828. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  1829. this.compileMaterials = false;
  1830. this.useClipPlane = false;
  1831. this.compileShadowGenerators = false;
  1832. this.onDisposeObservable = new BABYLON.Observable();
  1833. this.onMeshLoadedObservable = new BABYLON.Observable();
  1834. this.onTextureLoadedObservable = new BABYLON.Observable();
  1835. this.onMaterialLoadedObservable = new BABYLON.Observable();
  1836. this.onCompleteObservable = new BABYLON.Observable();
  1837. this.onExtensionLoadedObservable = new BABYLON.Observable();
  1838. this.state = null;
  1839. }
  1840. GLTFLoader.RegisterExtension = function (extension) {
  1841. if (GLTFLoader.Extensions[extension.name]) {
  1842. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1843. return;
  1844. }
  1845. GLTFLoader.Extensions[extension.name] = extension;
  1846. };
  1847. GLTFLoader.prototype.dispose = function () { };
  1848. // #endregion
  1849. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1850. var _this = this;
  1851. scene.useRightHandedSystem = true;
  1852. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1853. gltfRuntime.importOnlyMeshes = true;
  1854. if (meshesNames === "") {
  1855. gltfRuntime.importMeshesNames = [];
  1856. }
  1857. else if (typeof meshesNames === "string") {
  1858. gltfRuntime.importMeshesNames = [meshesNames];
  1859. }
  1860. else if (meshesNames && !(meshesNames instanceof Array)) {
  1861. gltfRuntime.importMeshesNames = [meshesNames];
  1862. }
  1863. else {
  1864. gltfRuntime.importMeshesNames = [];
  1865. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1866. }
  1867. // Create nodes
  1868. _this._createNodes(gltfRuntime);
  1869. var meshes = new Array();
  1870. var skeletons = new Array();
  1871. // Fill arrays of meshes and skeletons
  1872. for (var nde in gltfRuntime.nodes) {
  1873. var node = gltfRuntime.nodes[nde];
  1874. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1875. meshes.push(node.babylonNode);
  1876. }
  1877. }
  1878. for (var skl in gltfRuntime.skins) {
  1879. var skin = gltfRuntime.skins[skl];
  1880. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1881. skeletons.push(skin.babylonSkeleton);
  1882. }
  1883. }
  1884. // Load buffers, shaders, materials, etc.
  1885. _this._loadBuffersAsync(gltfRuntime, function () {
  1886. _this._loadShadersAsync(gltfRuntime, function () {
  1887. importMaterials(gltfRuntime);
  1888. postLoad(gltfRuntime);
  1889. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1890. onSuccess(meshes, [], skeletons);
  1891. }
  1892. });
  1893. }, onProgress);
  1894. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1895. onSuccess(meshes, [], skeletons);
  1896. }
  1897. }, onError);
  1898. return true;
  1899. };
  1900. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1901. var _this = this;
  1902. return new Promise(function (resolve, reject) {
  1903. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  1904. resolve({
  1905. meshes: meshes,
  1906. particleSystems: particleSystems,
  1907. skeletons: skeletons
  1908. });
  1909. }, onProgress, function (message) {
  1910. reject(new Error(message));
  1911. });
  1912. });
  1913. };
  1914. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1915. var _this = this;
  1916. scene.useRightHandedSystem = true;
  1917. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1918. // Load runtime extensios
  1919. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1920. // Create nodes
  1921. _this._createNodes(gltfRuntime);
  1922. // Load buffers, shaders, materials, etc.
  1923. _this._loadBuffersAsync(gltfRuntime, function () {
  1924. _this._loadShadersAsync(gltfRuntime, function () {
  1925. importMaterials(gltfRuntime);
  1926. postLoad(gltfRuntime);
  1927. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1928. onSuccess();
  1929. }
  1930. });
  1931. });
  1932. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1933. onSuccess();
  1934. }
  1935. }, onError);
  1936. }, onError);
  1937. };
  1938. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1939. var _this = this;
  1940. return new Promise(function (resolve, reject) {
  1941. _this._loadAsync(scene, data, rootUrl, function () {
  1942. resolve();
  1943. }, onProgress, function (message) {
  1944. reject(new Error(message));
  1945. });
  1946. });
  1947. };
  1948. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1949. var hasShaders = false;
  1950. var processShader = function (sha, shader) {
  1951. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1952. gltfRuntime.loadedShaderCount++;
  1953. if (shaderString) {
  1954. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1955. }
  1956. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1957. onload();
  1958. }
  1959. }, function () {
  1960. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1961. });
  1962. };
  1963. for (var sha in gltfRuntime.shaders) {
  1964. hasShaders = true;
  1965. var shader = gltfRuntime.shaders[sha];
  1966. if (shader) {
  1967. processShader.bind(this, sha, shader)();
  1968. }
  1969. else {
  1970. BABYLON.Tools.Error("No shader named: " + sha);
  1971. }
  1972. }
  1973. if (!hasShaders) {
  1974. onload();
  1975. }
  1976. };
  1977. ;
  1978. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  1979. var hasBuffers = false;
  1980. var processBuffer = function (buf, buffer) {
  1981. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1982. gltfRuntime.loadedBufferCount++;
  1983. if (bufferView) {
  1984. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1985. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1986. }
  1987. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1988. }
  1989. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1990. onLoad();
  1991. }
  1992. }, function () {
  1993. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1994. });
  1995. };
  1996. for (var buf in gltfRuntime.buffers) {
  1997. hasBuffers = true;
  1998. var buffer = gltfRuntime.buffers[buf];
  1999. if (buffer) {
  2000. processBuffer.bind(this, buf, buffer)();
  2001. }
  2002. else {
  2003. BABYLON.Tools.Error("No buffer named: " + buf);
  2004. }
  2005. }
  2006. if (!hasBuffers) {
  2007. onLoad();
  2008. }
  2009. };
  2010. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  2011. var currentScene = gltfRuntime.currentScene;
  2012. if (currentScene) {
  2013. // Only one scene even if multiple scenes are defined
  2014. for (var i = 0; i < currentScene.nodes.length; i++) {
  2015. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2016. }
  2017. }
  2018. else {
  2019. // Load all scenes
  2020. for (var thing in gltfRuntime.scenes) {
  2021. currentScene = gltfRuntime.scenes[thing];
  2022. for (var i = 0; i < currentScene.nodes.length; i++) {
  2023. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  2024. }
  2025. }
  2026. }
  2027. };
  2028. GLTFLoader.Extensions = {};
  2029. return GLTFLoader;
  2030. }());
  2031. GLTF1.GLTFLoader = GLTFLoader;
  2032. ;
  2033. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  2034. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2035. })(BABYLON || (BABYLON = {}));
  2036. //# sourceMappingURL=babylon.glTFLoader.js.map
  2037. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2038. var BABYLON;
  2039. (function (BABYLON) {
  2040. var GLTF1;
  2041. (function (GLTF1) {
  2042. /**
  2043. * Utils functions for GLTF
  2044. */
  2045. var GLTFUtils = /** @class */ (function () {
  2046. function GLTFUtils() {
  2047. }
  2048. /**
  2049. * Sets the given "parameter" matrix
  2050. * @param scene: the {BABYLON.Scene} object
  2051. * @param source: the source node where to pick the matrix
  2052. * @param parameter: the GLTF technique parameter
  2053. * @param uniformName: the name of the shader's uniform
  2054. * @param shaderMaterial: the shader material
  2055. */
  2056. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2057. var mat = null;
  2058. if (parameter.semantic === "MODEL") {
  2059. mat = source.getWorldMatrix();
  2060. }
  2061. else if (parameter.semantic === "PROJECTION") {
  2062. mat = scene.getProjectionMatrix();
  2063. }
  2064. else if (parameter.semantic === "VIEW") {
  2065. mat = scene.getViewMatrix();
  2066. }
  2067. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2068. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2069. }
  2070. else if (parameter.semantic === "MODELVIEW") {
  2071. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2072. }
  2073. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2074. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2075. }
  2076. else if (parameter.semantic === "MODELINVERSE") {
  2077. mat = source.getWorldMatrix().invert();
  2078. }
  2079. else if (parameter.semantic === "VIEWINVERSE") {
  2080. mat = scene.getViewMatrix().invert();
  2081. }
  2082. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2083. mat = scene.getProjectionMatrix().invert();
  2084. }
  2085. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2086. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2087. }
  2088. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2089. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2090. }
  2091. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2092. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  2093. }
  2094. else {
  2095. debugger;
  2096. }
  2097. if (mat) {
  2098. switch (parameter.type) {
  2099. case GLTF1.EParameterType.FLOAT_MAT2:
  2100. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  2101. break;
  2102. case GLTF1.EParameterType.FLOAT_MAT3:
  2103. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  2104. break;
  2105. case GLTF1.EParameterType.FLOAT_MAT4:
  2106. shaderMaterial.setMatrix(uniformName, mat);
  2107. break;
  2108. default: break;
  2109. }
  2110. }
  2111. };
  2112. /**
  2113. * Sets the given "parameter" matrix
  2114. * @param shaderMaterial: the shader material
  2115. * @param uniform: the name of the shader's uniform
  2116. * @param value: the value of the uniform
  2117. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2118. */
  2119. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2120. switch (type) {
  2121. case GLTF1.EParameterType.FLOAT:
  2122. shaderMaterial.setFloat(uniform, value);
  2123. return true;
  2124. case GLTF1.EParameterType.FLOAT_VEC2:
  2125. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  2126. return true;
  2127. case GLTF1.EParameterType.FLOAT_VEC3:
  2128. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  2129. return true;
  2130. case GLTF1.EParameterType.FLOAT_VEC4:
  2131. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  2132. return true;
  2133. default: return false;
  2134. }
  2135. };
  2136. /**
  2137. * Returns the wrap mode of the texture
  2138. * @param mode: the mode value
  2139. */
  2140. GLTFUtils.GetWrapMode = function (mode) {
  2141. switch (mode) {
  2142. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  2143. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  2144. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2145. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  2146. }
  2147. };
  2148. /**
  2149. * Returns the byte stride giving an accessor
  2150. * @param accessor: the GLTF accessor objet
  2151. */
  2152. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2153. // Needs this function since "byteStride" isn't requiered in glTF format
  2154. var type = accessor.type;
  2155. switch (type) {
  2156. case "VEC2": return 2;
  2157. case "VEC3": return 3;
  2158. case "VEC4": return 4;
  2159. case "MAT2": return 4;
  2160. case "MAT3": return 9;
  2161. case "MAT4": return 16;
  2162. default: return 1;
  2163. }
  2164. };
  2165. /**
  2166. * Returns the texture filter mode giving a mode value
  2167. * @param mode: the filter mode value
  2168. */
  2169. GLTFUtils.GetTextureFilterMode = function (mode) {
  2170. switch (mode) {
  2171. case GLTF1.ETextureFilterType.LINEAR:
  2172. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2173. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  2174. case GLTF1.ETextureFilterType.NEAREST:
  2175. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  2176. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  2177. }
  2178. };
  2179. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2180. var byteOffset = bufferView.byteOffset + byteOffset;
  2181. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2182. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2183. throw new Error("Buffer access is out of range");
  2184. }
  2185. var buffer = loadedBufferView.buffer;
  2186. byteOffset += loadedBufferView.byteOffset;
  2187. switch (componentType) {
  2188. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2189. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2190. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2191. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2192. default: return new Float32Array(buffer, byteOffset, byteLength);
  2193. }
  2194. };
  2195. /**
  2196. * Returns a buffer from its accessor
  2197. * @param gltfRuntime: the GLTF runtime
  2198. * @param accessor: the GLTF accessor
  2199. */
  2200. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2201. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2202. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2203. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2204. };
  2205. /**
  2206. * Decodes a buffer view into a string
  2207. * @param view: the buffer view
  2208. */
  2209. GLTFUtils.DecodeBufferToText = function (view) {
  2210. var result = "";
  2211. var length = view.byteLength;
  2212. for (var i = 0; i < length; ++i) {
  2213. result += String.fromCharCode(view[i]);
  2214. }
  2215. return result;
  2216. };
  2217. /**
  2218. * Returns the default material of gltf. Related to
  2219. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2220. * @param scene: the Babylon.js scene
  2221. */
  2222. GLTFUtils.GetDefaultMaterial = function (scene) {
  2223. if (!GLTFUtils._DefaultMaterial) {
  2224. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2225. "precision highp float;",
  2226. "",
  2227. "uniform mat4 worldView;",
  2228. "uniform mat4 projection;",
  2229. "",
  2230. "attribute vec3 position;",
  2231. "",
  2232. "void main(void)",
  2233. "{",
  2234. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2235. "}"
  2236. ].join("\n");
  2237. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2238. "precision highp float;",
  2239. "",
  2240. "uniform vec4 u_emission;",
  2241. "",
  2242. "void main(void)",
  2243. "{",
  2244. " gl_FragColor = u_emission;",
  2245. "}"
  2246. ].join("\n");
  2247. var shaderPath = {
  2248. vertex: "GLTFDefaultMaterial",
  2249. fragment: "GLTFDefaultMaterial"
  2250. };
  2251. var options = {
  2252. attributes: ["position"],
  2253. uniforms: ["worldView", "projection", "u_emission"],
  2254. samplers: new Array(),
  2255. needAlphaBlending: false
  2256. };
  2257. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2258. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  2259. }
  2260. return GLTFUtils._DefaultMaterial;
  2261. };
  2262. // The GLTF default material
  2263. GLTFUtils._DefaultMaterial = null;
  2264. return GLTFUtils;
  2265. }());
  2266. GLTF1.GLTFUtils = GLTFUtils;
  2267. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2268. })(BABYLON || (BABYLON = {}));
  2269. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2270. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2271. var BABYLON;
  2272. (function (BABYLON) {
  2273. var GLTF1;
  2274. (function (GLTF1) {
  2275. var GLTFLoaderExtension = /** @class */ (function () {
  2276. function GLTFLoaderExtension(name) {
  2277. this._name = name;
  2278. }
  2279. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2280. get: function () {
  2281. return this._name;
  2282. },
  2283. enumerable: true,
  2284. configurable: true
  2285. });
  2286. /**
  2287. * Defines an override for loading the runtime
  2288. * Return true to stop further extensions from loading the runtime
  2289. */
  2290. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2291. return false;
  2292. };
  2293. /**
  2294. * Defines an onverride for creating gltf runtime
  2295. * Return true to stop further extensions from creating the runtime
  2296. */
  2297. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2298. return false;
  2299. };
  2300. /**
  2301. * Defines an override for loading buffers
  2302. * Return true to stop further extensions from loading this buffer
  2303. */
  2304. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2305. return false;
  2306. };
  2307. /**
  2308. * Defines an override for loading texture buffers
  2309. * Return true to stop further extensions from loading this texture data
  2310. */
  2311. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2312. return false;
  2313. };
  2314. /**
  2315. * Defines an override for creating textures
  2316. * Return true to stop further extensions from loading this texture
  2317. */
  2318. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2319. return false;
  2320. };
  2321. /**
  2322. * Defines an override for loading shader strings
  2323. * Return true to stop further extensions from loading this shader data
  2324. */
  2325. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2326. return false;
  2327. };
  2328. /**
  2329. * Defines an override for loading materials
  2330. * Return true to stop further extensions from loading this material
  2331. */
  2332. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2333. return false;
  2334. };
  2335. // ---------
  2336. // Utilities
  2337. // ---------
  2338. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2339. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2340. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2341. }, function () {
  2342. setTimeout(function () {
  2343. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2344. });
  2345. });
  2346. };
  2347. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2348. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2349. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2350. }, function () {
  2351. setTimeout(function () {
  2352. onSuccess();
  2353. });
  2354. });
  2355. };
  2356. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2357. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2358. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2359. }, function () {
  2360. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2361. });
  2362. };
  2363. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2364. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  2365. };
  2366. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2367. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2368. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2369. }, function () {
  2370. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2371. });
  2372. };
  2373. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2374. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2375. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2376. }, function () {
  2377. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2378. });
  2379. };
  2380. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2381. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2382. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2383. }, function () {
  2384. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2385. });
  2386. };
  2387. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2388. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2389. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2390. }, function () {
  2391. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2392. });
  2393. };
  2394. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2395. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2396. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2397. if (func(loaderExtension)) {
  2398. return;
  2399. }
  2400. }
  2401. defaultFunc();
  2402. };
  2403. return GLTFLoaderExtension;
  2404. }());
  2405. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2406. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2407. })(BABYLON || (BABYLON = {}));
  2408. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2409. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2410. var __extends = (this && this.__extends) || (function () {
  2411. var extendStatics = Object.setPrototypeOf ||
  2412. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2413. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2414. return function (d, b) {
  2415. extendStatics(d, b);
  2416. function __() { this.constructor = d; }
  2417. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2418. };
  2419. })();
  2420. var BABYLON;
  2421. (function (BABYLON) {
  2422. var GLTF1;
  2423. (function (GLTF1) {
  2424. var BinaryExtensionBufferName = "binary_glTF";
  2425. ;
  2426. ;
  2427. var GLTFBinaryExtension = /** @class */ (function (_super) {
  2428. __extends(GLTFBinaryExtension, _super);
  2429. function GLTFBinaryExtension() {
  2430. return _super.call(this, "KHR_binary_glTF") || this;
  2431. }
  2432. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2433. var extensionsUsed = data.json.extensionsUsed;
  2434. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  2435. return false;
  2436. }
  2437. this._bin = data.bin;
  2438. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2439. return true;
  2440. };
  2441. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2442. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2443. return false;
  2444. }
  2445. if (id !== BinaryExtensionBufferName) {
  2446. return false;
  2447. }
  2448. onSuccess(this._bin);
  2449. return true;
  2450. };
  2451. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2452. var texture = gltfRuntime.textures[id];
  2453. var source = gltfRuntime.images[texture.source];
  2454. if (!source.extensions || !(this.name in source.extensions)) {
  2455. return false;
  2456. }
  2457. var sourceExt = source.extensions[this.name];
  2458. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2459. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2460. onSuccess(buffer);
  2461. return true;
  2462. };
  2463. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2464. var shader = gltfRuntime.shaders[id];
  2465. if (!shader.extensions || !(this.name in shader.extensions)) {
  2466. return false;
  2467. }
  2468. var binaryExtensionShader = shader.extensions[this.name];
  2469. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2470. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2471. setTimeout(function () {
  2472. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2473. onSuccess(shaderString);
  2474. });
  2475. return true;
  2476. };
  2477. return GLTFBinaryExtension;
  2478. }(GLTF1.GLTFLoaderExtension));
  2479. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2480. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2481. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2482. })(BABYLON || (BABYLON = {}));
  2483. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2484. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2485. var __extends = (this && this.__extends) || (function () {
  2486. var extendStatics = Object.setPrototypeOf ||
  2487. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2488. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2489. return function (d, b) {
  2490. extendStatics(d, b);
  2491. function __() { this.constructor = d; }
  2492. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2493. };
  2494. })();
  2495. var BABYLON;
  2496. (function (BABYLON) {
  2497. var GLTF1;
  2498. (function (GLTF1) {
  2499. ;
  2500. ;
  2501. ;
  2502. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2503. __extends(GLTFMaterialsCommonExtension, _super);
  2504. function GLTFMaterialsCommonExtension() {
  2505. return _super.call(this, "KHR_materials_common") || this;
  2506. }
  2507. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2508. if (!gltfRuntime.extensions)
  2509. return false;
  2510. var extension = gltfRuntime.extensions[this.name];
  2511. if (!extension)
  2512. return false;
  2513. // Create lights
  2514. var lights = extension.lights;
  2515. if (lights) {
  2516. for (var thing in lights) {
  2517. var light = lights[thing];
  2518. switch (light.type) {
  2519. case "ambient":
  2520. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2521. var ambient = light.ambient;
  2522. if (ambient) {
  2523. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2524. }
  2525. break;
  2526. case "point":
  2527. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2528. var point = light.point;
  2529. if (point) {
  2530. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2531. }
  2532. break;
  2533. case "directional":
  2534. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2535. var directional = light.directional;
  2536. if (directional) {
  2537. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2538. }
  2539. break;
  2540. case "spot":
  2541. var spot = light.spot;
  2542. if (spot) {
  2543. var spotLight = new BABYLON.SpotLight(light.name, new BABYLON.Vector3(0, 10, 0), new BABYLON.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2544. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2545. }
  2546. break;
  2547. default:
  2548. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2549. break;
  2550. }
  2551. }
  2552. }
  2553. return false;
  2554. };
  2555. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2556. var material = gltfRuntime.materials[id];
  2557. if (!material || !material.extensions)
  2558. return false;
  2559. var extension = material.extensions[this.name];
  2560. if (!extension)
  2561. return false;
  2562. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2563. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2564. if (extension.technique === "CONSTANT") {
  2565. standardMaterial.disableLighting = true;
  2566. }
  2567. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2568. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2569. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2570. // Ambient
  2571. if (typeof extension.values.ambient === "string") {
  2572. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2573. }
  2574. else {
  2575. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2576. }
  2577. // Diffuse
  2578. if (typeof extension.values.diffuse === "string") {
  2579. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2580. }
  2581. else {
  2582. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2583. }
  2584. // Emission
  2585. if (typeof extension.values.emission === "string") {
  2586. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2587. }
  2588. else {
  2589. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2590. }
  2591. // Specular
  2592. if (typeof extension.values.specular === "string") {
  2593. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2594. }
  2595. else {
  2596. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2597. }
  2598. return true;
  2599. };
  2600. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2601. // Create buffer from texture url
  2602. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2603. // Create texture from buffer
  2604. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2605. }, onError);
  2606. };
  2607. return GLTFMaterialsCommonExtension;
  2608. }(GLTF1.GLTFLoaderExtension));
  2609. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2610. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2611. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2612. })(BABYLON || (BABYLON = {}));
  2613. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  2614. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2615. var BABYLON;
  2616. (function (BABYLON) {
  2617. var GLTF2;
  2618. (function (GLTF2) {
  2619. var ArrayItem = /** @class */ (function () {
  2620. function ArrayItem() {
  2621. }
  2622. ArrayItem.Assign = function (values) {
  2623. if (values) {
  2624. for (var index = 0; index < values.length; index++) {
  2625. values[index]._index = index;
  2626. }
  2627. }
  2628. };
  2629. return ArrayItem;
  2630. }());
  2631. GLTF2.ArrayItem = ArrayItem;
  2632. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2633. })(BABYLON || (BABYLON = {}));
  2634. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  2635. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2636. /// <reference path="../../../../dist/babylon.glTF2Interface.d.ts"/>
  2637. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  2638. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2639. var BABYLON;
  2640. (function (BABYLON) {
  2641. var GLTF2;
  2642. (function (GLTF2) {
  2643. var GLTFLoader = /** @class */ (function () {
  2644. function GLTFLoader() {
  2645. this._completePromises = new Array();
  2646. this._disposed = false;
  2647. this._state = null;
  2648. this._extensions = {};
  2649. this._defaultSampler = {};
  2650. this._requests = new Array();
  2651. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  2652. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  2653. this.compileMaterials = false;
  2654. this.useClipPlane = false;
  2655. this.compileShadowGenerators = false;
  2656. this.onDisposeObservable = new BABYLON.Observable();
  2657. this.onMeshLoadedObservable = new BABYLON.Observable();
  2658. this.onTextureLoadedObservable = new BABYLON.Observable();
  2659. this.onMaterialLoadedObservable = new BABYLON.Observable();
  2660. this.onExtensionLoadedObservable = new BABYLON.Observable();
  2661. this.onCompleteObservable = new BABYLON.Observable();
  2662. }
  2663. GLTFLoader._Register = function (name, factory) {
  2664. if (GLTFLoader._Factories[name]) {
  2665. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  2666. return;
  2667. }
  2668. GLTFLoader._Factories[name] = factory;
  2669. // Keep the order of registration so that extensions registered first are called first.
  2670. GLTFLoader._Names.push(name);
  2671. };
  2672. Object.defineProperty(GLTFLoader.prototype, "state", {
  2673. get: function () {
  2674. return this._state;
  2675. },
  2676. enumerable: true,
  2677. configurable: true
  2678. });
  2679. GLTFLoader.prototype.dispose = function () {
  2680. if (this._disposed) {
  2681. return;
  2682. }
  2683. this._disposed = true;
  2684. this.onDisposeObservable.notifyObservers(this);
  2685. this.onDisposeObservable.clear();
  2686. this._clear();
  2687. };
  2688. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  2689. var _this = this;
  2690. return Promise.resolve().then(function () {
  2691. var nodes = null;
  2692. if (meshesNames) {
  2693. var nodeMap_1 = {};
  2694. if (_this._gltf.nodes) {
  2695. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  2696. var node = _a[_i];
  2697. if (node.name) {
  2698. nodeMap_1[node.name] = node;
  2699. }
  2700. }
  2701. }
  2702. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  2703. nodes = names.map(function (name) {
  2704. var node = nodeMap_1[name];
  2705. if (!node) {
  2706. throw new Error("Failed to find node " + name);
  2707. }
  2708. return node;
  2709. });
  2710. }
  2711. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  2712. return {
  2713. meshes: _this._getMeshes(),
  2714. particleSystems: [],
  2715. skeletons: _this._getSkeletons(),
  2716. };
  2717. });
  2718. });
  2719. };
  2720. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  2721. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  2722. };
  2723. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  2724. var _this = this;
  2725. return Promise.resolve().then(function () {
  2726. _this._loadExtensions();
  2727. _this._babylonScene = scene;
  2728. _this._rootUrl = rootUrl;
  2729. _this._progressCallback = onProgress;
  2730. _this._state = BABYLON.GLTFLoaderState.Loading;
  2731. _this._loadData(data);
  2732. _this._checkExtensions();
  2733. var promises = new Array();
  2734. if (nodes) {
  2735. promises.push(_this._loadNodesAsync(nodes));
  2736. }
  2737. else {
  2738. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  2739. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  2740. }
  2741. if (_this.compileMaterials) {
  2742. promises.push(_this._compileMaterialsAsync());
  2743. }
  2744. if (_this.compileShadowGenerators) {
  2745. promises.push(_this._compileShadowGeneratorsAsync());
  2746. }
  2747. return Promise.all(promises).then(function () {
  2748. _this._state = BABYLON.GLTFLoaderState.Ready;
  2749. _this._startAnimations();
  2750. BABYLON.Tools.SetImmediate(function () {
  2751. if (!_this._disposed) {
  2752. Promise.all(_this._completePromises).then(function () {
  2753. _this._state = BABYLON.GLTFLoaderState.Complete;
  2754. _this.onCompleteObservable.notifyObservers(_this);
  2755. _this.onCompleteObservable.clear();
  2756. _this._clear();
  2757. }).catch(function (error) {
  2758. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2759. _this._clear();
  2760. });
  2761. }
  2762. });
  2763. });
  2764. }).catch(function (error) {
  2765. BABYLON.Tools.Error("glTF Loader: " + error.message);
  2766. _this._clear();
  2767. throw error;
  2768. });
  2769. };
  2770. GLTFLoader.prototype._loadExtensions = function () {
  2771. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  2772. var name_1 = _a[_i];
  2773. var extension = GLTFLoader._Factories[name_1](this);
  2774. this._extensions[name_1] = extension;
  2775. this.onExtensionLoadedObservable.notifyObservers(extension);
  2776. }
  2777. this.onExtensionLoadedObservable.clear();
  2778. };
  2779. GLTFLoader.prototype._loadData = function (data) {
  2780. this._gltf = data.json;
  2781. this._setupData();
  2782. if (data.bin) {
  2783. var buffers = this._gltf.buffers;
  2784. if (buffers && buffers[0] && !buffers[0].uri) {
  2785. var binaryBuffer = buffers[0];
  2786. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  2787. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  2788. }
  2789. binaryBuffer._data = Promise.resolve(data.bin);
  2790. }
  2791. else {
  2792. BABYLON.Tools.Warn("Unexpected BIN chunk");
  2793. }
  2794. }
  2795. };
  2796. GLTFLoader.prototype._setupData = function () {
  2797. GLTF2.ArrayItem.Assign(this._gltf.accessors);
  2798. GLTF2.ArrayItem.Assign(this._gltf.animations);
  2799. GLTF2.ArrayItem.Assign(this._gltf.buffers);
  2800. GLTF2.ArrayItem.Assign(this._gltf.bufferViews);
  2801. GLTF2.ArrayItem.Assign(this._gltf.cameras);
  2802. GLTF2.ArrayItem.Assign(this._gltf.images);
  2803. GLTF2.ArrayItem.Assign(this._gltf.materials);
  2804. GLTF2.ArrayItem.Assign(this._gltf.meshes);
  2805. GLTF2.ArrayItem.Assign(this._gltf.nodes);
  2806. GLTF2.ArrayItem.Assign(this._gltf.samplers);
  2807. GLTF2.ArrayItem.Assign(this._gltf.scenes);
  2808. GLTF2.ArrayItem.Assign(this._gltf.skins);
  2809. GLTF2.ArrayItem.Assign(this._gltf.textures);
  2810. if (this._gltf.nodes) {
  2811. var nodeParents = {};
  2812. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  2813. var node = _a[_i];
  2814. if (node.children) {
  2815. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  2816. var index = _c[_b];
  2817. nodeParents[index] = node._index;
  2818. }
  2819. }
  2820. }
  2821. var rootNode = this._createRootNode();
  2822. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  2823. var node = _e[_d];
  2824. var parentIndex = nodeParents[node._index];
  2825. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  2826. }
  2827. }
  2828. };
  2829. GLTFLoader.prototype._checkExtensions = function () {
  2830. if (this._gltf.extensionsRequired) {
  2831. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  2832. var name_2 = _a[_i];
  2833. var extension = this._extensions[name_2];
  2834. if (!extension || !extension.enabled) {
  2835. throw new Error("Require extension " + name_2 + " is not available");
  2836. }
  2837. }
  2838. }
  2839. };
  2840. GLTFLoader.prototype._createRootNode = function () {
  2841. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  2842. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  2843. switch (this.coordinateSystemMode) {
  2844. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  2845. if (!this._babylonScene.useRightHandedSystem) {
  2846. rootNode.rotation = [0, 1, 0, 0];
  2847. rootNode.scale = [1, 1, -1];
  2848. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  2849. }
  2850. break;
  2851. }
  2852. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  2853. this._babylonScene.useRightHandedSystem = true;
  2854. break;
  2855. }
  2856. default: {
  2857. throw new Error("Invalid coordinate system mode " + this.coordinateSystemMode);
  2858. }
  2859. }
  2860. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  2861. return rootNode;
  2862. };
  2863. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  2864. var promises = new Array();
  2865. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  2866. var node = nodes_1[_i];
  2867. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  2868. }
  2869. promises.push(this._loadAnimationsAsync());
  2870. return Promise.all(promises).then(function () { });
  2871. };
  2872. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  2873. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  2874. if (promise) {
  2875. return promise;
  2876. }
  2877. var promises = new Array();
  2878. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  2879. var index = _a[_i];
  2880. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  2881. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  2882. }
  2883. promises.push(this._loadAnimationsAsync());
  2884. return Promise.all(promises).then(function () { });
  2885. };
  2886. GLTFLoader.prototype._getMeshes = function () {
  2887. var meshes = new Array();
  2888. // Root mesh is always first.
  2889. meshes.push(this._rootBabylonMesh);
  2890. var nodes = this._gltf.nodes;
  2891. if (nodes) {
  2892. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  2893. var node = nodes_2[_i];
  2894. if (node._babylonMesh) {
  2895. meshes.push(node._babylonMesh);
  2896. }
  2897. if (node._primitiveBabylonMeshes) {
  2898. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  2899. var babylonMesh = _b[_a];
  2900. meshes.push(babylonMesh);
  2901. }
  2902. }
  2903. }
  2904. }
  2905. return meshes;
  2906. };
  2907. GLTFLoader.prototype._getSkeletons = function () {
  2908. var skeletons = new Array();
  2909. var skins = this._gltf.skins;
  2910. if (skins) {
  2911. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  2912. var skin = skins_1[_i];
  2913. if (skin._babylonSkeleton) {
  2914. skeletons.push(skin._babylonSkeleton);
  2915. }
  2916. }
  2917. }
  2918. return skeletons;
  2919. };
  2920. GLTFLoader.prototype._startAnimations = function () {
  2921. var animations = this._gltf.animations;
  2922. if (!animations) {
  2923. return;
  2924. }
  2925. switch (this.animationStartMode) {
  2926. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  2927. // do nothing
  2928. break;
  2929. }
  2930. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  2931. var animation = animations[0];
  2932. animation._babylonAnimationGroup.start(true);
  2933. break;
  2934. }
  2935. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  2936. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  2937. var animation = animations_1[_i];
  2938. animation._babylonAnimationGroup.start(true);
  2939. }
  2940. break;
  2941. }
  2942. default: {
  2943. BABYLON.Tools.Error("Invalid animation start mode " + this.animationStartMode);
  2944. return;
  2945. }
  2946. }
  2947. };
  2948. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  2949. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  2950. if (promise) {
  2951. return promise;
  2952. }
  2953. if (node._babylonMesh) {
  2954. throw new Error(context + ": Invalid recursive node hierarchy");
  2955. }
  2956. var promises = new Array();
  2957. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  2958. node._babylonMesh = babylonMesh;
  2959. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  2960. node._babylonAnimationTargets.push(babylonMesh);
  2961. GLTFLoader._LoadTransform(node, babylonMesh);
  2962. if (node.mesh != undefined) {
  2963. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  2964. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh));
  2965. }
  2966. if (node.children) {
  2967. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  2968. var index = _a[_i];
  2969. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  2970. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  2971. }
  2972. }
  2973. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  2974. return Promise.all(promises).then(function () { });
  2975. };
  2976. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh) {
  2977. // TODO: instancing
  2978. var promises = new Array();
  2979. var primitives = mesh.primitives;
  2980. if (!primitives || primitives.length === 0) {
  2981. throw new Error(context + ": Primitives are missing");
  2982. }
  2983. GLTF2.ArrayItem.Assign(primitives);
  2984. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  2985. var primitive = primitives_1[_i];
  2986. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive));
  2987. }
  2988. if (node.skin != undefined) {
  2989. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  2990. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  2991. }
  2992. return Promise.all(promises).then(function () {
  2993. if (node._primitiveBabylonMeshes) {
  2994. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  2995. var primitiveBabylonMesh = _a[_i];
  2996. primitiveBabylonMesh._refreshBoundingInfo(true);
  2997. }
  2998. }
  2999. });
  3000. };
  3001. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive) {
  3002. var _this = this;
  3003. var promises = new Array();
  3004. var babylonMesh = new BABYLON.Mesh((mesh.name || node._babylonMesh.name) + "_" + primitive._index, this._babylonScene, node._babylonMesh);
  3005. babylonMesh.setEnabled(false);
  3006. node._primitiveBabylonMeshes = node._primitiveBabylonMeshes || [];
  3007. node._primitiveBabylonMeshes[primitive._index] = babylonMesh;
  3008. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  3009. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonVertexData) {
  3010. new BABYLON.Geometry(babylonMesh.name, _this._babylonScene, babylonVertexData, false, babylonMesh);
  3011. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonVertexData);
  3012. }));
  3013. if (primitive.material == undefined) {
  3014. babylonMesh.material = this._getDefaultMaterial();
  3015. }
  3016. else {
  3017. var material = GLTFLoader._GetProperty(context + "/material", this._gltf.materials, primitive.material);
  3018. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh));
  3019. }
  3020. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  3021. return Promise.all(promises).then(function () {
  3022. babylonMesh.setEnabled(true);
  3023. });
  3024. };
  3025. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  3026. var _this = this;
  3027. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  3028. if (promise) {
  3029. return promise;
  3030. }
  3031. var attributes = primitive.attributes;
  3032. if (!attributes) {
  3033. throw new Error(context + ": Attributes are missing");
  3034. }
  3035. if (primitive.mode != undefined && primitive.mode !== 4 /* TRIANGLES */) {
  3036. // TODO: handle other primitive modes
  3037. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  3038. }
  3039. var promises = new Array();
  3040. var babylonVertexData = new BABYLON.VertexData();
  3041. if (primitive.indices == undefined) {
  3042. var positionAccessorIndex = attributes["POSITION"];
  3043. if (positionAccessorIndex != undefined) {
  3044. var accessor = GLTFLoader._GetProperty(context + "/attributes/POSITION", this._gltf.accessors, positionAccessorIndex);
  3045. babylonVertexData.indices = new Uint32Array(accessor.count);
  3046. for (var i = 0; i < babylonVertexData.indices.length; i++) {
  3047. babylonVertexData.indices[i] = i;
  3048. }
  3049. }
  3050. }
  3051. else {
  3052. var indicesAccessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  3053. promises.push(this._loadAccessorAsync("#/accessors/" + indicesAccessor._index, indicesAccessor).then(function (data) {
  3054. babylonVertexData.indices = data;
  3055. }));
  3056. }
  3057. var loadAttribute = function (attribute, kind) {
  3058. if (attributes[attribute] == undefined) {
  3059. return;
  3060. }
  3061. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  3062. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  3063. babylonMesh._delayInfo.push(kind);
  3064. }
  3065. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3066. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3067. var attributeData = GLTFLoader._ConvertToFloat32Array(context, accessor, data);
  3068. if (attribute === "COLOR_0") {
  3069. // Assume vertex color has alpha on the mesh. The alphaMode of the material controls whether the material should use alpha or not.
  3070. babylonMesh.hasVertexAlpha = true;
  3071. if (accessor.type === "VEC3") {
  3072. attributeData = GLTFLoader._ConvertVec3ToVec4(context, attributeData);
  3073. }
  3074. }
  3075. babylonVertexData.set(attributeData, kind);
  3076. }));
  3077. };
  3078. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  3079. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  3080. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  3081. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  3082. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  3083. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  3084. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  3085. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  3086. return Promise.all(promises).then(function () {
  3087. return babylonVertexData;
  3088. });
  3089. };
  3090. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  3091. if (!primitive.targets) {
  3092. return;
  3093. }
  3094. if (node._numMorphTargets == undefined) {
  3095. node._numMorphTargets = primitive.targets.length;
  3096. }
  3097. else if (primitive.targets.length !== node._numMorphTargets) {
  3098. throw new Error(context + ": Primitives do not have the same number of targets");
  3099. }
  3100. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  3101. for (var index = 0; index < primitive.targets.length; index++) {
  3102. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  3103. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  3104. // TODO: tell the target whether it has positions, normals, tangents
  3105. }
  3106. };
  3107. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonVertexData) {
  3108. if (!primitive.targets) {
  3109. return Promise.resolve();
  3110. }
  3111. var promises = new Array();
  3112. var morphTargetManager = babylonMesh.morphTargetManager;
  3113. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  3114. var babylonMorphTarget = morphTargetManager.getTarget(index);
  3115. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonVertexData, primitive.targets[index], babylonMorphTarget));
  3116. }
  3117. return Promise.all(promises).then(function () { });
  3118. };
  3119. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonVertexData, attributes, babylonMorphTarget) {
  3120. var _this = this;
  3121. var promises = new Array();
  3122. var loadAttribute = function (attribute, setData) {
  3123. if (attributes[attribute] == undefined) {
  3124. return;
  3125. }
  3126. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  3127. promises.push(_this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3128. setData(data);
  3129. }));
  3130. };
  3131. loadAttribute("POSITION", function (data) {
  3132. if (babylonVertexData.positions) {
  3133. for (var i = 0; i < data.length; i++) {
  3134. data[i] += babylonVertexData.positions[i];
  3135. }
  3136. babylonMorphTarget.setPositions(data);
  3137. }
  3138. });
  3139. loadAttribute("NORMAL", function (data) {
  3140. if (babylonVertexData.normals) {
  3141. for (var i = 0; i < data.length; i++) {
  3142. data[i] += babylonVertexData.normals[i];
  3143. }
  3144. babylonMorphTarget.setNormals(data);
  3145. }
  3146. });
  3147. loadAttribute("TANGENT", function (data) {
  3148. if (babylonVertexData.tangents) {
  3149. // Tangent data for morph targets is stored as xyz delta.
  3150. // The vertexData.tangent is stored as xyzw.
  3151. // So we need to skip every fourth vertexData.tangent.
  3152. for (var i = 0, j = 0; i < data.length; i++) {
  3153. data[i] += babylonVertexData.tangents[j++];
  3154. if ((i + 1) % 3 == 0) {
  3155. j++;
  3156. }
  3157. }
  3158. babylonMorphTarget.setTangents(data);
  3159. }
  3160. });
  3161. return Promise.all(promises).then(function () { });
  3162. };
  3163. GLTFLoader._ConvertToFloat32Array = function (context, accessor, data) {
  3164. if (accessor.componentType == 5126 /* FLOAT */) {
  3165. return data;
  3166. }
  3167. var factor = 1;
  3168. if (accessor.normalized) {
  3169. switch (accessor.componentType) {
  3170. case 5121 /* UNSIGNED_BYTE */: {
  3171. factor = 1 / 255;
  3172. break;
  3173. }
  3174. case 5123 /* UNSIGNED_SHORT */: {
  3175. factor = 1 / 65535;
  3176. break;
  3177. }
  3178. default: {
  3179. throw new Error(context + ": Invalid component type " + accessor.componentType);
  3180. }
  3181. }
  3182. }
  3183. var result = new Float32Array(accessor.count * GLTFLoader._GetNumComponents(context, accessor.type));
  3184. for (var i = 0; i < result.length; i++) {
  3185. result[i] = data[i] * factor;
  3186. }
  3187. return result;
  3188. };
  3189. GLTFLoader._ConvertVec3ToVec4 = function (context, data) {
  3190. var result = new Float32Array(data.length / 3 * 4);
  3191. var offset = 0;
  3192. for (var i = 0; i < result.length; i++) {
  3193. if ((i + 1) % 4 === 0) {
  3194. result[i] = 1;
  3195. }
  3196. else {
  3197. result[i] = data[offset++];
  3198. }
  3199. }
  3200. return result;
  3201. };
  3202. GLTFLoader._LoadTransform = function (node, babylonNode) {
  3203. var position = BABYLON.Vector3.Zero();
  3204. var rotation = BABYLON.Quaternion.Identity();
  3205. var scaling = BABYLON.Vector3.One();
  3206. if (node.matrix) {
  3207. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  3208. matrix.decompose(scaling, rotation, position);
  3209. }
  3210. else {
  3211. if (node.translation)
  3212. position = BABYLON.Vector3.FromArray(node.translation);
  3213. if (node.rotation)
  3214. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  3215. if (node.scale)
  3216. scaling = BABYLON.Vector3.FromArray(node.scale);
  3217. }
  3218. babylonNode.position = position;
  3219. babylonNode.rotationQuaternion = rotation;
  3220. babylonNode.scaling = scaling;
  3221. };
  3222. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  3223. var _this = this;
  3224. var assignSkeleton = function () {
  3225. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  3226. var babylonMesh = _a[_i];
  3227. babylonMesh.skeleton = skin._babylonSkeleton;
  3228. }
  3229. node._babylonMesh.parent = _this._rootBabylonMesh;
  3230. node._babylonMesh.position = BABYLON.Vector3.Zero();
  3231. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  3232. node._babylonMesh.scaling = BABYLON.Vector3.One();
  3233. };
  3234. if (skin._loaded) {
  3235. return skin._loaded.then(function () {
  3236. assignSkeleton();
  3237. });
  3238. }
  3239. // TODO: split into two parts so that bones are created before inverseBindMatricesData is loaded (for compiling materials).
  3240. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  3241. var skeletonId = "skeleton" + skin._index;
  3242. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, _this._babylonScene);
  3243. skin._babylonSkeleton = babylonSkeleton;
  3244. _this._loadBones(context, skin, inverseBindMatricesData);
  3245. assignSkeleton();
  3246. }));
  3247. };
  3248. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  3249. if (skin.inverseBindMatrices == undefined) {
  3250. return Promise.resolve(null);
  3251. }
  3252. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  3253. return this._loadAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  3254. return data;
  3255. });
  3256. };
  3257. GLTFLoader.prototype._createBone = function (node, skin, parent, localMatrix, baseMatrix, index) {
  3258. var babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, parent, localMatrix, null, baseMatrix, index);
  3259. node._babylonAnimationTargets = node._babylonAnimationTargets || [];
  3260. node._babylonAnimationTargets.push(babylonBone);
  3261. return babylonBone;
  3262. };
  3263. GLTFLoader.prototype._loadBones = function (context, skin, inverseBindMatricesData) {
  3264. var babylonBones = {};
  3265. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  3266. var index = _a[_i];
  3267. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  3268. this._loadBone(node, skin, inverseBindMatricesData, babylonBones);
  3269. }
  3270. };
  3271. GLTFLoader.prototype._loadBone = function (node, skin, inverseBindMatricesData, babylonBones) {
  3272. var babylonBone = babylonBones[node._index];
  3273. if (babylonBone) {
  3274. return babylonBone;
  3275. }
  3276. var boneIndex = skin.joints.indexOf(node._index);
  3277. var baseMatrix = BABYLON.Matrix.Identity();
  3278. if (inverseBindMatricesData && boneIndex !== -1) {
  3279. baseMatrix = BABYLON.Matrix.FromArray(inverseBindMatricesData, boneIndex * 16);
  3280. baseMatrix.invertToRef(baseMatrix);
  3281. }
  3282. var babylonParentBone = null;
  3283. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  3284. babylonParentBone = this._loadBone(node._parent, skin, inverseBindMatricesData, babylonBones);
  3285. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  3286. }
  3287. babylonBone = this._createBone(node, skin, babylonParentBone, this._getNodeMatrix(node), baseMatrix, boneIndex);
  3288. babylonBones[node._index] = babylonBone;
  3289. return babylonBone;
  3290. };
  3291. GLTFLoader.prototype._getNodeMatrix = function (node) {
  3292. return node.matrix ?
  3293. BABYLON.Matrix.FromArray(node.matrix) :
  3294. BABYLON.Matrix.Compose(node.scale ? BABYLON.Vector3.FromArray(node.scale) : BABYLON.Vector3.One(), node.rotation ? BABYLON.Quaternion.FromArray(node.rotation) : BABYLON.Quaternion.Identity(), node.translation ? BABYLON.Vector3.FromArray(node.translation) : BABYLON.Vector3.Zero());
  3295. };
  3296. GLTFLoader.prototype._loadAnimationsAsync = function () {
  3297. var animations = this._gltf.animations;
  3298. if (!animations) {
  3299. return Promise.resolve();
  3300. }
  3301. var promises = new Array();
  3302. for (var index = 0; index < animations.length; index++) {
  3303. var animation = animations[index];
  3304. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  3305. }
  3306. return Promise.all(promises).then(function () { });
  3307. };
  3308. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  3309. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  3310. animation._babylonAnimationGroup = babylonAnimationGroup;
  3311. var promises = new Array();
  3312. GLTF2.ArrayItem.Assign(animation.channels);
  3313. GLTF2.ArrayItem.Assign(animation.samplers);
  3314. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  3315. var channel = _a[_i];
  3316. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  3317. }
  3318. return Promise.all(promises).then(function () {
  3319. babylonAnimationGroup.normalize();
  3320. });
  3321. };
  3322. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  3323. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  3324. if (!targetNode._babylonMesh) {
  3325. return Promise.resolve();
  3326. }
  3327. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  3328. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  3329. var targetPath;
  3330. var animationType;
  3331. switch (channel.target.path) {
  3332. case "translation" /* TRANSLATION */: {
  3333. targetPath = "position";
  3334. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3335. break;
  3336. }
  3337. case "rotation" /* ROTATION */: {
  3338. targetPath = "rotationQuaternion";
  3339. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  3340. break;
  3341. }
  3342. case "scale" /* SCALE */: {
  3343. targetPath = "scaling";
  3344. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  3345. break;
  3346. }
  3347. case "weights" /* WEIGHTS */: {
  3348. targetPath = "influence";
  3349. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  3350. break;
  3351. }
  3352. default: {
  3353. throw new Error(context + ": Invalid target path " + channel.target.path);
  3354. }
  3355. }
  3356. var outputBufferOffset = 0;
  3357. var getNextOutputValue;
  3358. switch (targetPath) {
  3359. case "position": {
  3360. getNextOutputValue = function () {
  3361. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3362. outputBufferOffset += 3;
  3363. return value;
  3364. };
  3365. break;
  3366. }
  3367. case "rotationQuaternion": {
  3368. getNextOutputValue = function () {
  3369. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  3370. outputBufferOffset += 4;
  3371. return value;
  3372. };
  3373. break;
  3374. }
  3375. case "scaling": {
  3376. getNextOutputValue = function () {
  3377. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  3378. outputBufferOffset += 3;
  3379. return value;
  3380. };
  3381. break;
  3382. }
  3383. case "influence": {
  3384. getNextOutputValue = function () {
  3385. var value = new Array(targetNode._numMorphTargets);
  3386. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  3387. value[i] = data.output[outputBufferOffset++];
  3388. }
  3389. return value;
  3390. };
  3391. break;
  3392. }
  3393. }
  3394. var getNextKey;
  3395. switch (data.interpolation) {
  3396. case "STEP" /* STEP */: {
  3397. getNextKey = function (frameIndex) { return ({
  3398. frame: data.input[frameIndex],
  3399. value: getNextOutputValue(),
  3400. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  3401. }); };
  3402. break;
  3403. }
  3404. case "LINEAR" /* LINEAR */: {
  3405. getNextKey = function (frameIndex) { return ({
  3406. frame: data.input[frameIndex],
  3407. value: getNextOutputValue()
  3408. }); };
  3409. break;
  3410. }
  3411. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3412. getNextKey = function (frameIndex) { return ({
  3413. frame: data.input[frameIndex],
  3414. inTangent: getNextOutputValue(),
  3415. value: getNextOutputValue(),
  3416. outTangent: getNextOutputValue()
  3417. }); };
  3418. break;
  3419. }
  3420. }
  3421. var keys;
  3422. if (data.input.length === 1) {
  3423. var key = getNextKey(0);
  3424. keys = [
  3425. { frame: key.frame, value: key.value },
  3426. { frame: key.frame + 1, value: key.value }
  3427. ];
  3428. }
  3429. else {
  3430. keys = new Array(data.input.length);
  3431. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  3432. keys[frameIndex] = getNextKey(frameIndex);
  3433. }
  3434. }
  3435. if (targetPath === "influence") {
  3436. var _loop_1 = function (targetIndex) {
  3437. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3438. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3439. babylonAnimation.setKeys(keys.map(function (key) { return ({
  3440. frame: key.frame,
  3441. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  3442. value: key.value[targetIndex],
  3443. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  3444. }); }));
  3445. for (var _i = 0, _a = targetNode._primitiveBabylonMeshes; _i < _a.length; _i++) {
  3446. var babylonMesh = _a[_i];
  3447. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  3448. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, morphTarget);
  3449. }
  3450. };
  3451. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  3452. _loop_1(targetIndex);
  3453. }
  3454. }
  3455. else {
  3456. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  3457. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  3458. babylonAnimation.setKeys(keys);
  3459. if (targetNode._babylonAnimationTargets) {
  3460. for (var _i = 0, _a = targetNode._babylonAnimationTargets; _i < _a.length; _i++) {
  3461. var target = _a[_i];
  3462. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, target);
  3463. }
  3464. }
  3465. }
  3466. });
  3467. };
  3468. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  3469. if (sampler._data) {
  3470. return sampler._data;
  3471. }
  3472. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  3473. switch (interpolation) {
  3474. case "STEP" /* STEP */:
  3475. case "LINEAR" /* LINEAR */:
  3476. case "CUBICSPLINE" /* CUBICSPLINE */: {
  3477. break;
  3478. }
  3479. default: {
  3480. throw new Error(context + ": Invalid interpolation " + sampler.interpolation);
  3481. }
  3482. }
  3483. var inputData;
  3484. var outputData;
  3485. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  3486. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  3487. sampler._data = Promise.all([
  3488. this._loadAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor).then(function (data) {
  3489. inputData = data;
  3490. }),
  3491. this._loadAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor).then(function (data) {
  3492. outputData = data;
  3493. })
  3494. ]).then(function () {
  3495. return {
  3496. input: inputData,
  3497. interpolation: interpolation,
  3498. output: outputData,
  3499. };
  3500. });
  3501. return sampler._data;
  3502. };
  3503. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  3504. if (buffer._data) {
  3505. return buffer._data;
  3506. }
  3507. if (!buffer.uri) {
  3508. throw new Error(context + ": Uri is missing");
  3509. }
  3510. buffer._data = this._loadUriAsync(context, buffer.uri);
  3511. return buffer._data;
  3512. };
  3513. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  3514. if (bufferView._data) {
  3515. return bufferView._data;
  3516. }
  3517. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  3518. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (bufferData) {
  3519. try {
  3520. return new Uint8Array(bufferData.buffer, bufferData.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  3521. }
  3522. catch (e) {
  3523. throw new Error(context + ": " + e.message);
  3524. }
  3525. });
  3526. return bufferView._data;
  3527. };
  3528. GLTFLoader.prototype._loadAccessorAsync = function (context, accessor) {
  3529. var _this = this;
  3530. if (accessor.sparse) {
  3531. throw new Error(context + ": Sparse accessors are not currently supported");
  3532. }
  3533. if (accessor._data) {
  3534. return accessor._data;
  3535. }
  3536. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  3537. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (bufferViewData) {
  3538. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  3539. var byteOffset = accessor.byteOffset || 0;
  3540. var byteStride = bufferView.byteStride;
  3541. if (byteStride === 0) {
  3542. BABYLON.Tools.Warn(context + ": Byte stride of 0 is not valid");
  3543. }
  3544. try {
  3545. switch (accessor.componentType) {
  3546. case 5120 /* BYTE */: {
  3547. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3548. }
  3549. case 5121 /* UNSIGNED_BYTE */: {
  3550. return _this._buildArrayBuffer(Uint8Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3551. }
  3552. case 5122 /* SHORT */: {
  3553. return _this._buildArrayBuffer(Int16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3554. }
  3555. case 5123 /* UNSIGNED_SHORT */: {
  3556. return _this._buildArrayBuffer(Uint16Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3557. }
  3558. case 5125 /* UNSIGNED_INT */: {
  3559. return _this._buildArrayBuffer(Uint32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3560. }
  3561. case 5126 /* FLOAT */: {
  3562. return _this._buildArrayBuffer(Float32Array, bufferViewData, byteOffset, accessor.count, numComponents, byteStride);
  3563. }
  3564. default: {
  3565. throw new Error(context + ": Invalid component type " + accessor.componentType);
  3566. }
  3567. }
  3568. }
  3569. catch (e) {
  3570. throw new Error(context + ": " + e);
  3571. }
  3572. });
  3573. return accessor._data;
  3574. };
  3575. GLTFLoader.prototype._buildArrayBuffer = function (typedArray, data, byteOffset, count, numComponents, byteStride) {
  3576. byteOffset += data.byteOffset;
  3577. var targetLength = count * numComponents;
  3578. if (!byteStride || byteStride === numComponents * typedArray.BYTES_PER_ELEMENT) {
  3579. return new typedArray(data.buffer, byteOffset, targetLength);
  3580. }
  3581. var elementStride = byteStride / typedArray.BYTES_PER_ELEMENT;
  3582. var sourceBuffer = new typedArray(data.buffer, byteOffset, elementStride * count);
  3583. var targetBuffer = new typedArray(targetLength);
  3584. var sourceIndex = 0;
  3585. var targetIndex = 0;
  3586. while (targetIndex < targetLength) {
  3587. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  3588. targetBuffer[targetIndex] = sourceBuffer[sourceIndex + componentIndex];
  3589. targetIndex++;
  3590. }
  3591. sourceIndex += elementStride;
  3592. }
  3593. return targetBuffer;
  3594. };
  3595. GLTFLoader.prototype._getDefaultMaterial = function () {
  3596. var id = "__gltf_default";
  3597. var babylonMaterial = this._babylonScene.getMaterialByName(id);
  3598. if (!babylonMaterial) {
  3599. babylonMaterial = new BABYLON.PBRMaterial(id, this._babylonScene);
  3600. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3601. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  3602. babylonMaterial.metallic = 1;
  3603. babylonMaterial.roughness = 1;
  3604. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3605. }
  3606. return babylonMaterial;
  3607. };
  3608. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material) {
  3609. var promises = new Array();
  3610. var babylonMaterial = material._babylonMaterial;
  3611. // Ensure metallic workflow
  3612. babylonMaterial.metallic = 1;
  3613. babylonMaterial.roughness = 1;
  3614. var properties = material.pbrMetallicRoughness;
  3615. if (properties) {
  3616. if (properties.baseColorFactor) {
  3617. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  3618. babylonMaterial.alpha = properties.baseColorFactor[3];
  3619. }
  3620. else {
  3621. babylonMaterial.albedoColor = BABYLON.Color3.White();
  3622. }
  3623. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  3624. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  3625. if (properties.baseColorTexture) {
  3626. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  3627. babylonMaterial.albedoTexture = texture;
  3628. }));
  3629. }
  3630. if (properties.metallicRoughnessTexture) {
  3631. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  3632. babylonMaterial.metallicTexture = texture;
  3633. }));
  3634. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  3635. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  3636. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  3637. }
  3638. }
  3639. this._loadMaterialAlphaProperties(context, material);
  3640. return Promise.all(promises).then(function () { });
  3641. };
  3642. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  3643. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh);
  3644. if (promise) {
  3645. return promise;
  3646. }
  3647. material._babylonMeshes = material._babylonMeshes || [];
  3648. material._babylonMeshes.push(babylonMesh);
  3649. if (material._loaded) {
  3650. babylonMesh.material = material._babylonMaterial;
  3651. return material._loaded;
  3652. }
  3653. var promises = new Array();
  3654. var babylonMaterial = this._createMaterial(material);
  3655. material._babylonMaterial = babylonMaterial;
  3656. promises.push(this._loadMaterialBasePropertiesAsync(context, material));
  3657. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material));
  3658. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  3659. babylonMesh.material = babylonMaterial;
  3660. return (material._loaded = Promise.all(promises).then(function () { }));
  3661. };
  3662. GLTFLoader.prototype._createMaterial = function (material) {
  3663. var babylonMaterial = new BABYLON.PBRMaterial(material.name || "material" + material._index, this._babylonScene);
  3664. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  3665. return babylonMaterial;
  3666. };
  3667. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material) {
  3668. var promises = new Array();
  3669. var babylonMaterial = material._babylonMaterial;
  3670. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  3671. if (material.doubleSided) {
  3672. babylonMaterial.backFaceCulling = false;
  3673. babylonMaterial.twoSidedLighting = true;
  3674. }
  3675. if (material.normalTexture) {
  3676. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  3677. babylonMaterial.bumpTexture = texture;
  3678. }));
  3679. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  3680. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  3681. if (material.normalTexture.scale != undefined) {
  3682. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  3683. }
  3684. }
  3685. if (material.occlusionTexture) {
  3686. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  3687. babylonMaterial.ambientTexture = texture;
  3688. }));
  3689. babylonMaterial.useAmbientInGrayScale = true;
  3690. if (material.occlusionTexture.strength != undefined) {
  3691. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  3692. }
  3693. }
  3694. if (material.emissiveTexture) {
  3695. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  3696. babylonMaterial.emissiveTexture = texture;
  3697. }));
  3698. }
  3699. return Promise.all(promises).then(function () { });
  3700. };
  3701. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material) {
  3702. var babylonMaterial = material._babylonMaterial;
  3703. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  3704. switch (alphaMode) {
  3705. case "OPAQUE" /* OPAQUE */: {
  3706. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  3707. break;
  3708. }
  3709. case "MASK" /* MASK */: {
  3710. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  3711. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  3712. if (babylonMaterial.alpha) {
  3713. if (babylonMaterial.alpha === 0) {
  3714. babylonMaterial.alphaCutOff = 1;
  3715. }
  3716. else {
  3717. babylonMaterial.alphaCutOff /= babylonMaterial.alpha;
  3718. }
  3719. babylonMaterial.alpha = 1;
  3720. }
  3721. if (babylonMaterial.albedoTexture) {
  3722. babylonMaterial.albedoTexture.hasAlpha = true;
  3723. }
  3724. break;
  3725. }
  3726. case "BLEND" /* BLEND */: {
  3727. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  3728. if (babylonMaterial.albedoTexture) {
  3729. babylonMaterial.albedoTexture.hasAlpha = true;
  3730. babylonMaterial.useAlphaFromAlbedoTexture = true;
  3731. }
  3732. break;
  3733. }
  3734. default: {
  3735. throw new Error(context + ": Invalid alpha mode " + material.alphaMode);
  3736. }
  3737. }
  3738. };
  3739. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  3740. var _this = this;
  3741. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  3742. context = "#/textures/" + textureInfo.index;
  3743. var promises = new Array();
  3744. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  3745. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  3746. var deferred = new BABYLON.Deferred();
  3747. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  3748. if (!_this._disposed) {
  3749. deferred.resolve();
  3750. }
  3751. }, function (message, exception) {
  3752. if (!_this._disposed) {
  3753. deferred.reject(new Error(context + ": " + (exception && exception.message) ? exception.message : message || "Failed to load texture"));
  3754. }
  3755. });
  3756. promises.push(deferred.promise);
  3757. babylonTexture.name = texture.name || "texture" + texture._index;
  3758. babylonTexture.wrapU = samplerData.wrapU;
  3759. babylonTexture.wrapV = samplerData.wrapV;
  3760. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  3761. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  3762. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  3763. babylonTexture.updateURL(objectURL);
  3764. }));
  3765. assign(babylonTexture);
  3766. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  3767. return Promise.all(promises).then(function () { });
  3768. };
  3769. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  3770. if (!sampler._data) {
  3771. sampler._data = {
  3772. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  3773. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  3774. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  3775. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  3776. };
  3777. }
  3778. ;
  3779. return sampler._data;
  3780. };
  3781. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  3782. if (image._objectURL) {
  3783. return image._objectURL;
  3784. }
  3785. var promise;
  3786. if (image.uri) {
  3787. promise = this._loadUriAsync(context, image.uri);
  3788. }
  3789. else {
  3790. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  3791. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  3792. }
  3793. image._objectURL = promise.then(function (data) {
  3794. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  3795. });
  3796. return image._objectURL;
  3797. };
  3798. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  3799. var _this = this;
  3800. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  3801. if (promise) {
  3802. return promise;
  3803. }
  3804. if (!GLTFLoader._ValidateUri(uri)) {
  3805. throw new Error(context + ": Uri '" + uri + "' is invalid");
  3806. }
  3807. if (BABYLON.Tools.IsBase64(uri)) {
  3808. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  3809. }
  3810. return new Promise(function (resolve, reject) {
  3811. var request = BABYLON.Tools.LoadFile(_this._rootUrl + uri, function (data) {
  3812. if (!_this._disposed) {
  3813. resolve(new Uint8Array(data));
  3814. }
  3815. }, function (event) {
  3816. if (!_this._disposed) {
  3817. try {
  3818. if (request && _this._state === BABYLON.GLTFLoaderState.Loading) {
  3819. request._lengthComputable = event.lengthComputable;
  3820. request._loaded = event.loaded;
  3821. request._total = event.total;
  3822. _this._onProgress();
  3823. }
  3824. }
  3825. catch (e) {
  3826. reject(e);
  3827. }
  3828. }
  3829. }, _this._babylonScene.database, true, function (request, exception) {
  3830. if (!_this._disposed) {
  3831. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  3832. }
  3833. });
  3834. _this._requests.push(request);
  3835. });
  3836. };
  3837. GLTFLoader.prototype._onProgress = function () {
  3838. if (!this._progressCallback) {
  3839. return;
  3840. }
  3841. var lengthComputable = true;
  3842. var loaded = 0;
  3843. var total = 0;
  3844. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3845. var request = _a[_i];
  3846. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  3847. return;
  3848. }
  3849. lengthComputable = lengthComputable && request._lengthComputable;
  3850. loaded += request._loaded;
  3851. total += request._total;
  3852. }
  3853. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  3854. };
  3855. GLTFLoader._GetProperty = function (context, array, index) {
  3856. if (!array || index == undefined || !array[index]) {
  3857. throw new Error(context + ": Failed to find index " + index);
  3858. }
  3859. return array[index];
  3860. };
  3861. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  3862. // Set defaults if undefined
  3863. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  3864. switch (mode) {
  3865. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  3866. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  3867. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3868. default:
  3869. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode " + mode);
  3870. return BABYLON.Texture.WRAP_ADDRESSMODE;
  3871. }
  3872. };
  3873. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  3874. // Set defaults if undefined
  3875. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  3876. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  3877. if (magFilter === 9729 /* LINEAR */) {
  3878. switch (minFilter) {
  3879. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  3880. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  3881. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  3882. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  3883. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  3884. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  3885. default:
  3886. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  3887. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  3888. }
  3889. }
  3890. else {
  3891. if (magFilter !== 9728 /* NEAREST */) {
  3892. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter " + magFilter);
  3893. }
  3894. switch (minFilter) {
  3895. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  3896. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  3897. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  3898. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  3899. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  3900. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  3901. default:
  3902. BABYLON.Tools.Warn(context + ": Invalid texture minification filter " + minFilter);
  3903. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  3904. }
  3905. }
  3906. };
  3907. GLTFLoader._GetNumComponents = function (context, type) {
  3908. switch (type) {
  3909. case "SCALAR": return 1;
  3910. case "VEC2": return 2;
  3911. case "VEC3": return 3;
  3912. case "VEC4": return 4;
  3913. case "MAT2": return 4;
  3914. case "MAT3": return 9;
  3915. case "MAT4": return 16;
  3916. }
  3917. throw new Error(context + ": Invalid type " + type);
  3918. };
  3919. GLTFLoader._ValidateUri = function (uri) {
  3920. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  3921. };
  3922. GLTFLoader.prototype._compileMaterialsAsync = function () {
  3923. var promises = new Array();
  3924. if (this._gltf.materials) {
  3925. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  3926. var material = _a[_i];
  3927. var babylonMaterial = material._babylonMaterial;
  3928. var babylonMeshes = material._babylonMeshes;
  3929. if (babylonMaterial && babylonMeshes) {
  3930. for (var _b = 0, babylonMeshes_1 = babylonMeshes; _b < babylonMeshes_1.length; _b++) {
  3931. var babylonMesh = babylonMeshes_1[_b];
  3932. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  3933. if (this.useClipPlane) {
  3934. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  3935. }
  3936. }
  3937. }
  3938. }
  3939. }
  3940. return Promise.all(promises).then(function () { });
  3941. };
  3942. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  3943. var promises = new Array();
  3944. var lights = this._babylonScene.lights;
  3945. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  3946. var light = lights_1[_i];
  3947. var generator = light.getShadowGenerator();
  3948. if (generator) {
  3949. promises.push(generator.forceCompilationAsync());
  3950. }
  3951. }
  3952. return Promise.all(promises).then(function () { });
  3953. };
  3954. GLTFLoader.prototype._clear = function () {
  3955. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3956. var request = _a[_i];
  3957. request.abort();
  3958. }
  3959. this._requests.length = 0;
  3960. if (this._gltf && this._gltf.images) {
  3961. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  3962. var image = _c[_b];
  3963. if (image._objectURL) {
  3964. image._objectURL.then(function (value) {
  3965. URL.revokeObjectURL(value);
  3966. });
  3967. image._objectURL = undefined;
  3968. }
  3969. }
  3970. }
  3971. delete this._gltf;
  3972. delete this._babylonScene;
  3973. this._completePromises.length = 0;
  3974. for (var name_3 in this._extensions) {
  3975. this._extensions[name_3].dispose();
  3976. }
  3977. this._extensions = {};
  3978. delete this._rootBabylonMesh;
  3979. delete this._progressCallback;
  3980. this.onMeshLoadedObservable.clear();
  3981. this.onTextureLoadedObservable.clear();
  3982. this.onMaterialLoadedObservable.clear();
  3983. };
  3984. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  3985. for (var _i = 0, _a = GLTFLoader._Names; _i < _a.length; _i++) {
  3986. var name_4 = _a[_i];
  3987. var extension = this._extensions[name_4];
  3988. if (extension.enabled) {
  3989. var promise = actionAsync(extension);
  3990. if (promise) {
  3991. return promise;
  3992. }
  3993. }
  3994. }
  3995. return null;
  3996. };
  3997. GLTFLoader._Names = new Array();
  3998. GLTFLoader._Factories = {};
  3999. return GLTFLoader;
  4000. }());
  4001. GLTF2.GLTFLoader = GLTFLoader;
  4002. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  4003. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4004. })(BABYLON || (BABYLON = {}));
  4005. //# sourceMappingURL=babylon.glTFLoader.js.map
  4006. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  4007. var BABYLON;
  4008. (function (BABYLON) {
  4009. var GLTF2;
  4010. (function (GLTF2) {
  4011. var GLTFLoaderExtension = /** @class */ (function () {
  4012. function GLTFLoaderExtension(loader) {
  4013. this.enabled = true;
  4014. this._loader = loader;
  4015. }
  4016. GLTFLoaderExtension.prototype.dispose = function () {
  4017. delete this._loader;
  4018. };
  4019. // #region Overridable Methods
  4020. /** Override this method to modify the default behavior for loading scenes. */
  4021. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  4022. /** Override this method to modify the default behavior for loading nodes. */
  4023. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  4024. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  4025. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  4026. /** Override this method to modify the default behavior for loading materials. */
  4027. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh) { return null; };
  4028. /** Override this method to modify the default behavior for loading uris. */
  4029. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  4030. // #endregion
  4031. /** Helper method called by a loader extension to load an glTF extension. */
  4032. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  4033. if (!property.extensions) {
  4034. return null;
  4035. }
  4036. var extensions = property.extensions;
  4037. var extension = extensions[this.name];
  4038. if (!extension) {
  4039. return null;
  4040. }
  4041. // Clear out the extension before executing the action to avoid recursing into the same property.
  4042. delete extensions[this.name];
  4043. try {
  4044. return actionAsync(context + "/extensions/" + this.name, extension);
  4045. }
  4046. finally {
  4047. // Restore the extension after executing the action.
  4048. extensions[this.name] = extension;
  4049. }
  4050. };
  4051. /** Helper method called by the loader to allow extensions to override loading scenes. */
  4052. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  4053. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  4054. };
  4055. /** Helper method called by the loader to allow extensions to override loading nodes. */
  4056. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  4057. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  4058. };
  4059. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  4060. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  4061. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  4062. };
  4063. /** Helper method called by the loader to allow extensions to override loading materials. */
  4064. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh) {
  4065. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh); });
  4066. };
  4067. /** Helper method called by the loader to allow extensions to override loading uris. */
  4068. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  4069. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  4070. };
  4071. return GLTFLoaderExtension;
  4072. }());
  4073. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  4074. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4075. })(BABYLON || (BABYLON = {}));
  4076. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  4077. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4078. var __extends = (this && this.__extends) || (function () {
  4079. var extendStatics = Object.setPrototypeOf ||
  4080. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4081. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4082. return function (d, b) {
  4083. extendStatics(d, b);
  4084. function __() { this.constructor = d; }
  4085. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4086. };
  4087. })();
  4088. var BABYLON;
  4089. (function (BABYLON) {
  4090. var GLTF2;
  4091. (function (GLTF2) {
  4092. var Extensions;
  4093. (function (Extensions) {
  4094. // https://github.com/sbtron/glTF/tree/MSFT_lod/extensions/Vendor/MSFT_lod
  4095. var NAME = "MSFT_lod";
  4096. var MSFT_lod = /** @class */ (function (_super) {
  4097. __extends(MSFT_lod, _super);
  4098. function MSFT_lod() {
  4099. var _this = _super !== null && _super.apply(this, arguments) || this;
  4100. _this.name = NAME;
  4101. /**
  4102. * Maximum number of LODs to load, starting from the lowest LOD.
  4103. */
  4104. _this.maxLODsToLoad = Number.MAX_VALUE;
  4105. _this._loadingNodeLOD = null;
  4106. _this._loadNodeSignals = {};
  4107. _this._loadingMaterialLOD = null;
  4108. _this._loadMaterialSignals = {};
  4109. return _this;
  4110. }
  4111. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  4112. var _this = this;
  4113. return this._loadExtensionAsync(context, node, function (context, extension) {
  4114. var firstPromise;
  4115. var nodeLODs = _this._getLODs(context, node, _this._loader._gltf.nodes, extension.ids);
  4116. var _loop_1 = function (indexLOD) {
  4117. var nodeLOD = nodeLODs[indexLOD];
  4118. if (indexLOD !== 0) {
  4119. _this._loadingNodeLOD = nodeLOD;
  4120. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  4121. }
  4122. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  4123. if (indexLOD !== 0) {
  4124. var previousNodeLOD = nodeLODs[indexLOD - 1];
  4125. previousNodeLOD._babylonMesh.setEnabled(false);
  4126. }
  4127. if (indexLOD !== nodeLODs.length - 1) {
  4128. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  4129. _this._loadNodeSignals[nodeIndex].resolve();
  4130. delete _this._loadNodeSignals[nodeIndex];
  4131. }
  4132. });
  4133. if (indexLOD === 0) {
  4134. firstPromise = promise;
  4135. }
  4136. else {
  4137. _this._loader._completePromises.push(promise);
  4138. _this._loadingNodeLOD = null;
  4139. }
  4140. };
  4141. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  4142. _loop_1(indexLOD);
  4143. }
  4144. return firstPromise;
  4145. });
  4146. };
  4147. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  4148. var _this = this;
  4149. // Don't load material LODs if already loading a node LOD.
  4150. if (this._loadingNodeLOD) {
  4151. return null;
  4152. }
  4153. return this._loadExtensionAsync(context, material, function (context, extension) {
  4154. var firstPromise;
  4155. var materialLODs = _this._getLODs(context, material, _this._loader._gltf.materials, extension.ids);
  4156. var _loop_2 = function (indexLOD) {
  4157. var materialLOD = materialLODs[indexLOD];
  4158. if (indexLOD !== 0) {
  4159. _this._loadingMaterialLOD = materialLOD;
  4160. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  4161. }
  4162. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh).then(function () {
  4163. if (indexLOD !== materialLODs.length - 1) {
  4164. var materialIndex = materialLODs[indexLOD + 1]._index;
  4165. _this._loadMaterialSignals[materialIndex].resolve();
  4166. delete _this._loadMaterialSignals[materialIndex];
  4167. }
  4168. });
  4169. if (indexLOD === 0) {
  4170. firstPromise = promise;
  4171. }
  4172. else {
  4173. _this._loader._completePromises.push(promise);
  4174. _this._loadingMaterialLOD = null;
  4175. }
  4176. };
  4177. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  4178. _loop_2(indexLOD);
  4179. }
  4180. return firstPromise;
  4181. });
  4182. };
  4183. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  4184. var _this = this;
  4185. // Defer the loading of uris if loading a material or node LOD.
  4186. if (this._loadingMaterialLOD) {
  4187. var index = this._loadingMaterialLOD._index;
  4188. return this._loadMaterialSignals[index].promise.then(function () {
  4189. return _this._loader._loadUriAsync(context, uri);
  4190. });
  4191. }
  4192. else if (this._loadingNodeLOD) {
  4193. var index = this._loadingNodeLOD._index;
  4194. return this._loadNodeSignals[index].promise.then(function () {
  4195. return _this._loader._loadUriAsync(context, uri);
  4196. });
  4197. }
  4198. return null;
  4199. };
  4200. /**
  4201. * Gets an array of LOD properties from lowest to highest.
  4202. */
  4203. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  4204. if (this.maxLODsToLoad <= 0) {
  4205. throw new Error("maxLODsToLoad must be greater than zero");
  4206. }
  4207. var properties = new Array();
  4208. for (var i = ids.length - 1; i >= 0; i--) {
  4209. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  4210. if (properties.length === this.maxLODsToLoad) {
  4211. return properties;
  4212. }
  4213. }
  4214. properties.push(property);
  4215. return properties;
  4216. };
  4217. return MSFT_lod;
  4218. }(GLTF2.GLTFLoaderExtension));
  4219. Extensions.MSFT_lod = MSFT_lod;
  4220. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  4221. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4222. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4223. })(BABYLON || (BABYLON = {}));
  4224. //# sourceMappingURL=MSFT_lod.js.map
  4225. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4226. var __extends = (this && this.__extends) || (function () {
  4227. var extendStatics = Object.setPrototypeOf ||
  4228. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4229. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4230. return function (d, b) {
  4231. extendStatics(d, b);
  4232. function __() { this.constructor = d; }
  4233. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4234. };
  4235. })();
  4236. var BABYLON;
  4237. (function (BABYLON) {
  4238. var GLTF2;
  4239. (function (GLTF2) {
  4240. var Extensions;
  4241. (function (Extensions) {
  4242. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression
  4243. var NAME = "KHR_draco_mesh_compression";
  4244. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  4245. __extends(KHR_draco_mesh_compression, _super);
  4246. function KHR_draco_mesh_compression(loader) {
  4247. var _this = _super.call(this, loader) || this;
  4248. _this.name = NAME;
  4249. _this._dracoCompression = null;
  4250. // Disable extension if decoder is not available.
  4251. if (!BABYLON.DracoCompression.DecoderUrl) {
  4252. _this.enabled = false;
  4253. }
  4254. return _this;
  4255. }
  4256. KHR_draco_mesh_compression.prototype.dispose = function () {
  4257. if (this._dracoCompression) {
  4258. this._dracoCompression.dispose();
  4259. }
  4260. _super.prototype.dispose.call(this);
  4261. };
  4262. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  4263. var _this = this;
  4264. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  4265. if (primitive.mode != undefined) {
  4266. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  4267. primitive.mode !== 4 /* TRIANGLES */) {
  4268. throw new Error(context + ": Unsupported mode " + primitive.mode);
  4269. }
  4270. // TODO: handle triangle strips
  4271. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  4272. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  4273. }
  4274. }
  4275. var attributes = {};
  4276. var loadAttribute = function (name, kind) {
  4277. var uniqueId = extension.attributes[name];
  4278. if (uniqueId == undefined) {
  4279. return;
  4280. }
  4281. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  4282. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  4283. babylonMesh._delayInfo.push(kind);
  4284. }
  4285. attributes[kind] = uniqueId;
  4286. };
  4287. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  4288. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  4289. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  4290. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  4291. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  4292. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  4293. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  4294. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  4295. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  4296. return _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  4297. try {
  4298. if (!_this._dracoCompression) {
  4299. _this._dracoCompression = new BABYLON.DracoCompression();
  4300. }
  4301. return _this._dracoCompression.decodeMeshAsync(data, attributes);
  4302. }
  4303. catch (e) {
  4304. throw new Error(context + ": " + e.message);
  4305. }
  4306. });
  4307. });
  4308. };
  4309. return KHR_draco_mesh_compression;
  4310. }(GLTF2.GLTFLoaderExtension));
  4311. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  4312. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  4313. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4314. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4315. })(BABYLON || (BABYLON = {}));
  4316. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  4317. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4318. var __extends = (this && this.__extends) || (function () {
  4319. var extendStatics = Object.setPrototypeOf ||
  4320. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4321. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4322. return function (d, b) {
  4323. extendStatics(d, b);
  4324. function __() { this.constructor = d; }
  4325. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4326. };
  4327. })();
  4328. var BABYLON;
  4329. (function (BABYLON) {
  4330. var GLTF2;
  4331. (function (GLTF2) {
  4332. var Extensions;
  4333. (function (Extensions) {
  4334. // https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness
  4335. var NAME = "KHR_materials_pbrSpecularGlossiness";
  4336. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  4337. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  4338. function KHR_materials_pbrSpecularGlossiness() {
  4339. var _this = _super !== null && _super.apply(this, arguments) || this;
  4340. _this.name = NAME;
  4341. return _this;
  4342. }
  4343. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh) {
  4344. var _this = this;
  4345. return this._loadExtensionAsync(context, material, function (context, extension) {
  4346. material._babylonMeshes = material._babylonMeshes || [];
  4347. material._babylonMeshes.push(babylonMesh);
  4348. if (material._loaded) {
  4349. babylonMesh.material = material._babylonMaterial;
  4350. return material._loaded;
  4351. }
  4352. var promises = new Array();
  4353. var babylonMaterial = _this._loader._createMaterial(material);
  4354. material._babylonMaterial = babylonMaterial;
  4355. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material));
  4356. promises.push(_this._loadSpecularGlossinessPropertiesAsync(_this._loader, context, material, extension));
  4357. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4358. babylonMesh.material = babylonMaterial;
  4359. return (material._loaded = Promise.all(promises).then(function () { }));
  4360. });
  4361. };
  4362. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (loader, context, material, properties) {
  4363. var promises = new Array();
  4364. var babylonMaterial = material._babylonMaterial;
  4365. if (properties.diffuseFactor) {
  4366. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  4367. babylonMaterial.alpha = properties.diffuseFactor[3];
  4368. }
  4369. else {
  4370. babylonMaterial.albedoColor = BABYLON.Color3.White();
  4371. }
  4372. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  4373. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  4374. if (properties.diffuseTexture) {
  4375. promises.push(loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  4376. babylonMaterial.albedoTexture = texture;
  4377. }));
  4378. }
  4379. if (properties.specularGlossinessTexture) {
  4380. promises.push(loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  4381. babylonMaterial.reflectivityTexture = texture;
  4382. }));
  4383. babylonMaterial.reflectivityTexture.hasAlpha = true;
  4384. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  4385. }
  4386. loader._loadMaterialAlphaProperties(context, material);
  4387. return Promise.all(promises).then(function () { });
  4388. };
  4389. return KHR_materials_pbrSpecularGlossiness;
  4390. }(GLTF2.GLTFLoaderExtension));
  4391. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  4392. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  4393. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4394. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4395. })(BABYLON || (BABYLON = {}));
  4396. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  4397. /// <reference path="../../../../../dist/preview release/babylon.d.ts"/>
  4398. var __extends = (this && this.__extends) || (function () {
  4399. var extendStatics = Object.setPrototypeOf ||
  4400. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4401. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4402. return function (d, b) {
  4403. extendStatics(d, b);
  4404. function __() { this.constructor = d; }
  4405. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4406. };
  4407. })();
  4408. var BABYLON;
  4409. (function (BABYLON) {
  4410. var GLTF2;
  4411. (function (GLTF2) {
  4412. var Extensions;
  4413. (function (Extensions) {
  4414. // https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights
  4415. var NAME = "KHR_lights";
  4416. var LightType;
  4417. (function (LightType) {
  4418. LightType["AMBIENT"] = "ambient";
  4419. LightType["DIRECTIONAL"] = "directional";
  4420. LightType["POINT"] = "point";
  4421. LightType["SPOT"] = "spot";
  4422. })(LightType || (LightType = {}));
  4423. var KHR_lights = /** @class */ (function (_super) {
  4424. __extends(KHR_lights, _super);
  4425. function KHR_lights() {
  4426. var _this = _super !== null && _super.apply(this, arguments) || this;
  4427. _this.name = NAME;
  4428. return _this;
  4429. }
  4430. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  4431. var _this = this;
  4432. return this._loadExtensionAsync(context, scene, function (context, extension) {
  4433. var promise = _this._loader._loadSceneAsync(context, scene);
  4434. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  4435. if (light.type !== LightType.AMBIENT) {
  4436. throw new Error(context + ": Only ambient lights are allowed on a scene");
  4437. }
  4438. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  4439. return promise;
  4440. });
  4441. };
  4442. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  4443. var _this = this;
  4444. return this._loadExtensionAsync(context, node, function (context, extension) {
  4445. var promise = _this._loader._loadNodeAsync(context, node);
  4446. var babylonLight;
  4447. var light = GLTF2.GLTFLoader._GetProperty(context, _this._lights, extension.light);
  4448. var name = node._babylonMesh.name;
  4449. switch (light.type) {
  4450. case LightType.AMBIENT: {
  4451. throw new Error(context + ": Ambient lights are not allowed on a node");
  4452. }
  4453. case LightType.DIRECTIONAL: {
  4454. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  4455. break;
  4456. }
  4457. case LightType.POINT: {
  4458. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  4459. break;
  4460. }
  4461. case LightType.SPOT: {
  4462. var spotLight = light;
  4463. // TODO: support inner and outer cone angles
  4464. //const innerConeAngle = spotLight.innerConeAngle || 0;
  4465. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  4466. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  4467. break;
  4468. }
  4469. default: {
  4470. throw new Error(context + ": Invalid light type " + light.type);
  4471. }
  4472. }
  4473. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  4474. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  4475. babylonLight.parent = node._babylonMesh;
  4476. return promise;
  4477. });
  4478. };
  4479. Object.defineProperty(KHR_lights.prototype, "_lights", {
  4480. get: function () {
  4481. var extensions = this._loader._gltf.extensions;
  4482. if (!extensions || !extensions[this.name]) {
  4483. throw new Error("#/extensions: " + this.name + " not found");
  4484. }
  4485. var extension = extensions[this.name];
  4486. return extension.lights;
  4487. },
  4488. enumerable: true,
  4489. configurable: true
  4490. });
  4491. return KHR_lights;
  4492. }(GLTF2.GLTFLoaderExtension));
  4493. Extensions.KHR_lights = KHR_lights;
  4494. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  4495. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  4496. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  4497. })(BABYLON || (BABYLON = {}));
  4498. //# sourceMappingURL=KHR_lights.js.map