babylon.glTFFileLoader.js 252 KB

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