babylon.glTFFileLoader.js 263 KB

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