babylon.glTFFileLoader.js 286 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory(require("babylonjs"));
  4. else if(typeof define === 'function' && define.amd)
  5. define("babylonjs-loaders", ["babylonjs"], factory);
  6. else if(typeof exports === 'object')
  7. exports["babylonjs-loaders"] = factory(require("babylonjs"));
  8. else
  9. root["LOADERS"] = factory(root["BABYLON"]);
  10. })(window, function(__WEBPACK_EXTERNAL_MODULE_babylonjs__) {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  50. /******/ }
  51. /******/ };
  52. /******/
  53. /******/ // define __esModule on exports
  54. /******/ __webpack_require__.r = function(exports) {
  55. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  56. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  57. /******/ }
  58. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  59. /******/ };
  60. /******/
  61. /******/ // create a fake namespace object
  62. /******/ // mode & 1: value is a module id, require it
  63. /******/ // mode & 2: merge all properties of value into the ns
  64. /******/ // mode & 4: return value when already ns object
  65. /******/ // mode & 8|1: behave like require
  66. /******/ __webpack_require__.t = function(value, mode) {
  67. /******/ if(mode & 1) value = __webpack_require__(value);
  68. /******/ if(mode & 8) return value;
  69. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  70. /******/ var ns = Object.create(null);
  71. /******/ __webpack_require__.r(ns);
  72. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  73. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  74. /******/ return ns;
  75. /******/ };
  76. /******/
  77. /******/ // getDefaultExport function for compatibility with non-harmony modules
  78. /******/ __webpack_require__.n = function(module) {
  79. /******/ var getter = module && module.__esModule ?
  80. /******/ function getDefault() { return module['default']; } :
  81. /******/ function getModuleExports() { return module; };
  82. /******/ __webpack_require__.d(getter, 'a', getter);
  83. /******/ return getter;
  84. /******/ };
  85. /******/
  86. /******/ // Object.prototype.hasOwnProperty.call
  87. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  88. /******/
  89. /******/ // __webpack_public_path__
  90. /******/ __webpack_require__.p = "";
  91. /******/
  92. /******/
  93. /******/ // Load entry module and return exports
  94. /******/ return __webpack_require__(__webpack_require__.s = "./legacy/legacy-glTFFileLoader.ts");
  95. /******/ })
  96. /************************************************************************/
  97. /******/ ({
  98. /***/ "../node_modules/webpack/buildin/global.js":
  99. /*!*************************************************!*\
  100. !*** ../node_modules/webpack/buildin/global.js ***!
  101. \*************************************************/
  102. /*! no static exports found */
  103. /***/ (function(module, exports) {
  104. var g;
  105. // This works in non-strict mode
  106. g = (function() {
  107. return this;
  108. })();
  109. try {
  110. // This works if eval is allowed (see CSP)
  111. g = g || Function("return this")() || (1, eval)("this");
  112. } catch (e) {
  113. // This works if the window reference is available
  114. if (typeof window === "object") g = window;
  115. }
  116. // g can still be undefined, but nothing to do about it...
  117. // We return undefined, instead of nothing here, so it's
  118. // easier to handle this case. if(!global) { ...}
  119. module.exports = g;
  120. /***/ }),
  121. /***/ "./legacy/legacy-glTF.ts":
  122. /*!*******************************!*\
  123. !*** ./legacy/legacy-glTF.ts ***!
  124. \*******************************/
  125. /*! no static exports found */
  126. /***/ (function(module, exports, __webpack_require__) {
  127. "use strict";
  128. /* WEBPACK VAR INJECTION */(function(global) {
  129. function __export(m) {
  130. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  131. }
  132. Object.defineProperty(exports, "__esModule", { value: true });
  133. var FileLoader = __webpack_require__(/*! ../src/glTF/glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  134. /**
  135. * This is the entry point for the UMD module.
  136. * The entry point for a future ESM package should be index.ts
  137. */
  138. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  139. if (typeof globalObject !== "undefined") {
  140. globalObject.BABYLON = globalObject.BABYLON || {};
  141. for (var key in FileLoader) {
  142. globalObject.BABYLON[key] = FileLoader[key];
  143. }
  144. }
  145. __export(__webpack_require__(/*! ../src/glTF/glTFFileLoader */ "./src/glTF/glTFFileLoader.ts"));
  146. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
  147. /***/ }),
  148. /***/ "./legacy/legacy-glTF1.ts":
  149. /*!********************************!*\
  150. !*** ./legacy/legacy-glTF1.ts ***!
  151. \********************************/
  152. /*! no static exports found */
  153. /***/ (function(module, exports, __webpack_require__) {
  154. "use strict";
  155. /* WEBPACK VAR INJECTION */(function(global) {
  156. Object.defineProperty(exports, "__esModule", { value: true });
  157. var GLTF1 = __webpack_require__(/*! ../src/glTF/1.0 */ "./src/glTF/1.0/index.ts");
  158. exports.GLTF1 = GLTF1;
  159. /**
  160. * This is the entry point for the UMD module.
  161. * The entry point for a future ESM package should be index.ts
  162. */
  163. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  164. if (typeof globalObject !== "undefined") {
  165. globalObject.BABYLON = globalObject.BABYLON || {};
  166. globalObject.BABYLON.GLTF1 = globalObject.BABYLON.GLTF1 || {};
  167. for (var key in GLTF1) {
  168. globalObject.BABYLON.GLTF1[key] = GLTF1[key];
  169. }
  170. }
  171. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
  172. /***/ }),
  173. /***/ "./legacy/legacy-glTF2.ts":
  174. /*!********************************!*\
  175. !*** ./legacy/legacy-glTF2.ts ***!
  176. \********************************/
  177. /*! no static exports found */
  178. /***/ (function(module, exports, __webpack_require__) {
  179. "use strict";
  180. /* WEBPACK VAR INJECTION */(function(global) {
  181. Object.defineProperty(exports, "__esModule", { value: true });
  182. var Extensions = __webpack_require__(/*! ../src/glTF/2.0/Extensions */ "./src/glTF/2.0/Extensions/index.ts");
  183. var Interfaces = __webpack_require__(/*! ../src/glTF/2.0/glTFLoaderInterfaces */ "./src/glTF/2.0/glTFLoaderInterfaces.ts");
  184. var GLTF2 = __webpack_require__(/*! ../src/glTF/2.0 */ "./src/glTF/2.0/index.ts");
  185. exports.GLTF2 = GLTF2;
  186. /**
  187. * This is the entry point for the UMD module.
  188. * The entry point for a future ESM package should be index.ts
  189. */
  190. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : undefined);
  191. if (typeof globalObject !== "undefined") {
  192. globalObject.BABYLON = globalObject.BABYLON || {};
  193. var BABYLON = globalObject.BABYLON;
  194. BABYLON.GLTF2 = BABYLON.GLTF2 || {};
  195. BABYLON.GLTF2.Loader = BABYLON.GLTF2.Loader || {};
  196. BABYLON.GLTF2.Loader.Extensions = BABYLON.GLTF2.Loader.Extensions || {};
  197. var keys = [];
  198. for (var key in Extensions) {
  199. BABYLON.GLTF2.Loader.Extensions[key] = Extensions[key];
  200. keys.push(key);
  201. }
  202. for (var key in Interfaces) {
  203. BABYLON.GLTF2.Loader[key] = Interfaces[key];
  204. keys.push(key);
  205. }
  206. for (var key in GLTF2) {
  207. // Prevent Reassignment.
  208. if (keys.indexOf(key) > -1) {
  209. continue;
  210. }
  211. BABYLON.GLTF2[key] = GLTF2[key];
  212. }
  213. }
  214. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../node_modules/webpack/buildin/global.js */ "../node_modules/webpack/buildin/global.js")))
  215. /***/ }),
  216. /***/ "./legacy/legacy-glTFFileLoader.ts":
  217. /*!*****************************************!*\
  218. !*** ./legacy/legacy-glTFFileLoader.ts ***!
  219. \*****************************************/
  220. /*! no static exports found */
  221. /***/ (function(module, exports, __webpack_require__) {
  222. "use strict";
  223. function __export(m) {
  224. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  225. }
  226. Object.defineProperty(exports, "__esModule", { value: true });
  227. __export(__webpack_require__(/*! ./legacy-glTF */ "./legacy/legacy-glTF.ts"));
  228. __export(__webpack_require__(/*! ./legacy-glTF1 */ "./legacy/legacy-glTF1.ts"));
  229. __export(__webpack_require__(/*! ./legacy-glTF2 */ "./legacy/legacy-glTF2.ts"));
  230. /***/ }),
  231. /***/ "./src/glTF/1.0/glTFBinaryExtension.ts":
  232. /*!*********************************************!*\
  233. !*** ./src/glTF/1.0/glTFBinaryExtension.ts ***!
  234. \*********************************************/
  235. /*! no static exports found */
  236. /***/ (function(module, exports, __webpack_require__) {
  237. "use strict";
  238. var __extends = (this && this.__extends) || (function () {
  239. var extendStatics = function (d, b) {
  240. extendStatics = Object.setPrototypeOf ||
  241. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  242. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  243. return extendStatics(d, b);
  244. }
  245. return function (d, b) {
  246. extendStatics(d, b);
  247. function __() { this.constructor = d; }
  248. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  249. };
  250. })();
  251. Object.defineProperty(exports, "__esModule", { value: true });
  252. var glTFLoaderExtension_1 = __webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts");
  253. var glTFLoaderUtils_1 = __webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts");
  254. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  255. var glTFLoader_1 = __webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts");
  256. var BinaryExtensionBufferName = "binary_glTF";
  257. /** @hidden */
  258. var GLTFBinaryExtension = /** @class */ (function (_super) {
  259. __extends(GLTFBinaryExtension, _super);
  260. function GLTFBinaryExtension() {
  261. return _super.call(this, "KHR_binary_glTF") || this;
  262. }
  263. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  264. var extensionsUsed = data.json.extensionsUsed;
  265. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  266. return false;
  267. }
  268. this._bin = data.bin;
  269. onSuccess(glTFLoader_1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  270. return true;
  271. };
  272. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  273. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  274. return false;
  275. }
  276. if (id !== BinaryExtensionBufferName) {
  277. return false;
  278. }
  279. onSuccess(this._bin);
  280. return true;
  281. };
  282. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  283. var texture = gltfRuntime.textures[id];
  284. var source = gltfRuntime.images[texture.source];
  285. if (!source.extensions || !(this.name in source.extensions)) {
  286. return false;
  287. }
  288. var sourceExt = source.extensions[this.name];
  289. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  290. var buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE);
  291. onSuccess(buffer);
  292. return true;
  293. };
  294. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  295. var shader = gltfRuntime.shaders[id];
  296. if (!shader.extensions || !(this.name in shader.extensions)) {
  297. return false;
  298. }
  299. var binaryExtensionShader = shader.extensions[this.name];
  300. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  301. var shaderBytes = glTFLoaderUtils_1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE);
  302. setTimeout(function () {
  303. var shaderString = glTFLoaderUtils_1.GLTFUtils.DecodeBufferToText(shaderBytes);
  304. onSuccess(shaderString);
  305. });
  306. return true;
  307. };
  308. return GLTFBinaryExtension;
  309. }(glTFLoaderExtension_1.GLTFLoaderExtension));
  310. exports.GLTFBinaryExtension = GLTFBinaryExtension;
  311. glTFLoader_1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  312. /***/ }),
  313. /***/ "./src/glTF/1.0/glTFLoader.ts":
  314. /*!************************************!*\
  315. !*** ./src/glTF/1.0/glTFLoader.ts ***!
  316. \************************************/
  317. /*! no static exports found */
  318. /***/ (function(module, exports, __webpack_require__) {
  319. "use strict";
  320. Object.defineProperty(exports, "__esModule", { value: true });
  321. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  322. var glTFLoaderUtils_1 = __webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts");
  323. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  324. var glTFFileLoader_1 = __webpack_require__(/*! ../glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  325. var glTFLoaderExtension_1 = __webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts");
  326. /**
  327. * Tokenizer. Used for shaders compatibility
  328. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  329. */
  330. var ETokenType;
  331. (function (ETokenType) {
  332. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  333. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  334. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  335. })(ETokenType || (ETokenType = {}));
  336. var Tokenizer = /** @class */ (function () {
  337. function Tokenizer(toParse) {
  338. this._pos = 0;
  339. this.currentToken = ETokenType.UNKNOWN;
  340. this.currentIdentifier = "";
  341. this.currentString = "";
  342. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  343. this._toParse = toParse;
  344. this._maxPos = toParse.length;
  345. }
  346. Tokenizer.prototype.getNextToken = function () {
  347. if (this.isEnd()) {
  348. return ETokenType.END_OF_INPUT;
  349. }
  350. this.currentString = this.read();
  351. this.currentToken = ETokenType.UNKNOWN;
  352. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  353. this.currentToken = ETokenType.IDENTIFIER;
  354. this.currentIdentifier = this.currentString;
  355. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  356. this.currentIdentifier += this.currentString;
  357. this.forward();
  358. }
  359. }
  360. return this.currentToken;
  361. };
  362. Tokenizer.prototype.peek = function () {
  363. return this._toParse[this._pos];
  364. };
  365. Tokenizer.prototype.read = function () {
  366. return this._toParse[this._pos++];
  367. };
  368. Tokenizer.prototype.forward = function () {
  369. this._pos++;
  370. };
  371. Tokenizer.prototype.isEnd = function () {
  372. return this._pos >= this._maxPos;
  373. };
  374. return Tokenizer;
  375. }());
  376. /**
  377. * Values
  378. */
  379. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  380. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  381. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  382. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  383. /**
  384. * Parse
  385. */
  386. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  387. for (var buf in parsedBuffers) {
  388. var parsedBuffer = parsedBuffers[buf];
  389. gltfRuntime.buffers[buf] = parsedBuffer;
  390. gltfRuntime.buffersCount++;
  391. }
  392. };
  393. var parseShaders = function (parsedShaders, gltfRuntime) {
  394. for (var sha in parsedShaders) {
  395. var parsedShader = parsedShaders[sha];
  396. gltfRuntime.shaders[sha] = parsedShader;
  397. gltfRuntime.shaderscount++;
  398. }
  399. };
  400. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  401. for (var object in parsedObjects) {
  402. var parsedObject = parsedObjects[object];
  403. gltfRuntime[runtimeProperty][object] = parsedObject;
  404. }
  405. };
  406. /**
  407. * Utils
  408. */
  409. var normalizeUVs = function (buffer) {
  410. if (!buffer) {
  411. return;
  412. }
  413. for (var i = 0; i < buffer.length / 2; i++) {
  414. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  415. }
  416. };
  417. var getAttribute = function (attributeParameter) {
  418. if (attributeParameter.semantic === "NORMAL") {
  419. return "normal";
  420. }
  421. else if (attributeParameter.semantic === "POSITION") {
  422. return "position";
  423. }
  424. else if (attributeParameter.semantic === "JOINT") {
  425. return "matricesIndices";
  426. }
  427. else if (attributeParameter.semantic === "WEIGHT") {
  428. return "matricesWeights";
  429. }
  430. else if (attributeParameter.semantic === "COLOR") {
  431. return "color";
  432. }
  433. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  434. var channel = Number(attributeParameter.semantic.split("_")[1]);
  435. return "uv" + (channel === 0 ? "" : channel + 1);
  436. }
  437. return null;
  438. };
  439. /**
  440. * Loads and creates animations
  441. */
  442. var loadAnimations = function (gltfRuntime) {
  443. for (var anim in gltfRuntime.animations) {
  444. var animation = gltfRuntime.animations[anim];
  445. if (!animation.channels || !animation.samplers) {
  446. continue;
  447. }
  448. var lastAnimation = null;
  449. for (var i = 0; i < animation.channels.length; i++) {
  450. // Get parameters and load buffers
  451. var channel = animation.channels[i];
  452. var sampler = animation.samplers[channel.sampler];
  453. if (!sampler) {
  454. continue;
  455. }
  456. var inputData = null;
  457. var outputData = null;
  458. if (animation.parameters) {
  459. inputData = animation.parameters[sampler.input];
  460. outputData = animation.parameters[sampler.output];
  461. }
  462. else {
  463. inputData = sampler.input;
  464. outputData = sampler.output;
  465. }
  466. var bufferInput = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  467. var bufferOutput = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  468. var targetID = channel.target.id;
  469. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  470. if (targetNode === null) {
  471. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  472. }
  473. if (targetNode === null) {
  474. babylonjs_1.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  475. continue;
  476. }
  477. var isBone = targetNode instanceof babylonjs_1.Bone;
  478. // Get target path (position, rotation or scaling)
  479. var targetPath = channel.target.path;
  480. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  481. if (targetPathIndex !== -1) {
  482. targetPath = babylonAnimationPaths[targetPathIndex];
  483. }
  484. // Determine animation type
  485. var animationType = babylonjs_1.Animation.ANIMATIONTYPE_MATRIX;
  486. if (!isBone) {
  487. if (targetPath === "rotationQuaternion") {
  488. animationType = babylonjs_1.Animation.ANIMATIONTYPE_QUATERNION;
  489. targetNode.rotationQuaternion = new babylonjs_1.Quaternion();
  490. }
  491. else {
  492. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  493. }
  494. }
  495. // Create animation and key frames
  496. var babylonAnimation = null;
  497. var keys = [];
  498. var arrayOffset = 0;
  499. var modifyKey = false;
  500. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  501. babylonAnimation = lastAnimation;
  502. modifyKey = true;
  503. }
  504. if (!modifyKey) {
  505. babylonAnimation = new babylonjs_1.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, babylonjs_1.Animation.ANIMATIONLOOPMODE_CYCLE);
  506. }
  507. // For each frame
  508. for (var j = 0; j < bufferInput.length; j++) {
  509. var value = null;
  510. if (targetPath === "rotationQuaternion") { // VEC4
  511. value = babylonjs_1.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  512. arrayOffset += 4;
  513. }
  514. else { // Position and scaling are VEC3
  515. value = babylonjs_1.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  516. arrayOffset += 3;
  517. }
  518. if (isBone) {
  519. var bone = targetNode;
  520. var translation = babylonjs_1.Vector3.Zero();
  521. var rotationQuaternion = new babylonjs_1.Quaternion();
  522. var scaling = babylonjs_1.Vector3.Zero();
  523. // Warning on decompose
  524. var mat = bone.getBaseMatrix();
  525. if (modifyKey && lastAnimation) {
  526. mat = lastAnimation.getKeys()[j].value;
  527. }
  528. mat.decompose(scaling, rotationQuaternion, translation);
  529. if (targetPath === "position") {
  530. translation = value;
  531. }
  532. else if (targetPath === "rotationQuaternion") {
  533. rotationQuaternion = value;
  534. }
  535. else {
  536. scaling = value;
  537. }
  538. value = babylonjs_1.Matrix.Compose(scaling, rotationQuaternion, translation);
  539. }
  540. if (!modifyKey) {
  541. keys.push({
  542. frame: bufferInput[j],
  543. value: value
  544. });
  545. }
  546. else if (lastAnimation) {
  547. lastAnimation.getKeys()[j].value = value;
  548. }
  549. }
  550. // Finish
  551. if (!modifyKey && babylonAnimation) {
  552. babylonAnimation.setKeys(keys);
  553. targetNode.animations.push(babylonAnimation);
  554. }
  555. lastAnimation = babylonAnimation;
  556. gltfRuntime.scene.stopAnimation(targetNode);
  557. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  558. }
  559. }
  560. };
  561. /**
  562. * Returns the bones transformation matrix
  563. */
  564. var configureBoneTransformation = function (node) {
  565. var mat = null;
  566. if (node.translation || node.rotation || node.scale) {
  567. var scale = babylonjs_1.Vector3.FromArray(node.scale || [1, 1, 1]);
  568. var rotation = babylonjs_1.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  569. var position = babylonjs_1.Vector3.FromArray(node.translation || [0, 0, 0]);
  570. mat = babylonjs_1.Matrix.Compose(scale, rotation, position);
  571. }
  572. else {
  573. mat = babylonjs_1.Matrix.FromArray(node.matrix);
  574. }
  575. return mat;
  576. };
  577. /**
  578. * Returns the parent bone
  579. */
  580. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  581. // Try to find
  582. for (var i = 0; i < newSkeleton.bones.length; i++) {
  583. if (newSkeleton.bones[i].name === jointName) {
  584. return newSkeleton.bones[i];
  585. }
  586. }
  587. // Not found, search in gltf nodes
  588. var nodes = gltfRuntime.nodes;
  589. for (var nde in nodes) {
  590. var node = nodes[nde];
  591. if (!node.jointName) {
  592. continue;
  593. }
  594. var children = node.children;
  595. for (var i = 0; i < children.length; i++) {
  596. var child = gltfRuntime.nodes[children[i]];
  597. if (!child.jointName) {
  598. continue;
  599. }
  600. if (child.jointName === jointName) {
  601. var mat = configureBoneTransformation(node);
  602. var bone = new babylonjs_1.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  603. bone.id = nde;
  604. return bone;
  605. }
  606. }
  607. }
  608. return null;
  609. };
  610. /**
  611. * Returns the appropriate root node
  612. */
  613. var getNodeToRoot = function (nodesToRoot, id) {
  614. for (var i = 0; i < nodesToRoot.length; i++) {
  615. var nodeToRoot = nodesToRoot[i];
  616. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  617. var child = nodeToRoot.node.children[j];
  618. if (child === id) {
  619. return nodeToRoot.bone;
  620. }
  621. }
  622. }
  623. return null;
  624. };
  625. /**
  626. * Returns the node with the joint name
  627. */
  628. var getJointNode = function (gltfRuntime, jointName) {
  629. var nodes = gltfRuntime.nodes;
  630. var node = nodes[jointName];
  631. if (node) {
  632. return {
  633. node: node,
  634. id: jointName
  635. };
  636. }
  637. for (var nde in nodes) {
  638. node = nodes[nde];
  639. if (node.jointName === jointName) {
  640. return {
  641. node: node,
  642. id: nde
  643. };
  644. }
  645. }
  646. return null;
  647. };
  648. /**
  649. * Checks if a nodes is in joints
  650. */
  651. var nodeIsInJoints = function (skins, id) {
  652. for (var i = 0; i < skins.jointNames.length; i++) {
  653. if (skins.jointNames[i] === id) {
  654. return true;
  655. }
  656. }
  657. return false;
  658. };
  659. /**
  660. * Fills the nodes to root for bones and builds hierarchy
  661. */
  662. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  663. // Creates nodes for root
  664. for (var nde in gltfRuntime.nodes) {
  665. var node = gltfRuntime.nodes[nde];
  666. var id = nde;
  667. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  668. continue;
  669. }
  670. // Create node to root bone
  671. var mat = configureBoneTransformation(node);
  672. var bone = new babylonjs_1.Bone(node.name || "", newSkeleton, null, mat);
  673. bone.id = id;
  674. nodesToRoot.push({ bone: bone, node: node, id: id });
  675. }
  676. // Parenting
  677. for (var i = 0; i < nodesToRoot.length; i++) {
  678. var nodeToRoot = nodesToRoot[i];
  679. var children = nodeToRoot.node.children;
  680. for (var j = 0; j < children.length; j++) {
  681. var child = null;
  682. for (var k = 0; k < nodesToRoot.length; k++) {
  683. if (nodesToRoot[k].id === children[j]) {
  684. child = nodesToRoot[k];
  685. break;
  686. }
  687. }
  688. if (child) {
  689. child.bone._parent = nodeToRoot.bone;
  690. nodeToRoot.bone.children.push(child.bone);
  691. }
  692. }
  693. }
  694. };
  695. /**
  696. * Imports a skeleton
  697. */
  698. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  699. if (!newSkeleton) {
  700. newSkeleton = new babylonjs_1.Skeleton(skins.name || "", "", gltfRuntime.scene);
  701. }
  702. if (!skins.babylonSkeleton) {
  703. return newSkeleton;
  704. }
  705. // Find the root bones
  706. var nodesToRoot = [];
  707. var nodesToRootToAdd = [];
  708. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  709. newSkeleton.bones = [];
  710. // Joints
  711. for (var i = 0; i < skins.jointNames.length; i++) {
  712. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  713. if (!jointNode) {
  714. continue;
  715. }
  716. var node = jointNode.node;
  717. if (!node) {
  718. babylonjs_1.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  719. continue;
  720. }
  721. var id = jointNode.id;
  722. // Optimize, if the bone already exists...
  723. var existingBone = gltfRuntime.scene.getBoneByID(id);
  724. if (existingBone) {
  725. newSkeleton.bones.push(existingBone);
  726. continue;
  727. }
  728. // Search for parent bone
  729. var foundBone = false;
  730. var parentBone = null;
  731. for (var j = 0; j < i; j++) {
  732. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  733. if (!jointNode_1) {
  734. continue;
  735. }
  736. var joint = jointNode_1.node;
  737. if (!joint) {
  738. babylonjs_1.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  739. continue;
  740. }
  741. var children = joint.children;
  742. if (!children) {
  743. continue;
  744. }
  745. foundBone = false;
  746. for (var k = 0; k < children.length; k++) {
  747. if (children[k] === id) {
  748. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  749. foundBone = true;
  750. break;
  751. }
  752. }
  753. if (foundBone) {
  754. break;
  755. }
  756. }
  757. // Create bone
  758. var mat = configureBoneTransformation(node);
  759. if (!parentBone && nodesToRoot.length > 0) {
  760. parentBone = getNodeToRoot(nodesToRoot, id);
  761. if (parentBone) {
  762. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  763. nodesToRootToAdd.push(parentBone);
  764. }
  765. }
  766. }
  767. var bone = new babylonjs_1.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  768. bone.id = id;
  769. }
  770. // Polish
  771. var bones = newSkeleton.bones;
  772. newSkeleton.bones = [];
  773. for (var i = 0; i < skins.jointNames.length; i++) {
  774. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  775. if (!jointNode) {
  776. continue;
  777. }
  778. for (var j = 0; j < bones.length; j++) {
  779. if (bones[j].id === jointNode.id) {
  780. newSkeleton.bones.push(bones[j]);
  781. break;
  782. }
  783. }
  784. }
  785. newSkeleton.prepare();
  786. // Finish
  787. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  788. newSkeleton.bones.push(nodesToRootToAdd[i]);
  789. }
  790. return newSkeleton;
  791. };
  792. /**
  793. * Imports a mesh and its geometries
  794. */
  795. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  796. if (!newMesh) {
  797. newMesh = new babylonjs_1.Mesh(node.name || "", gltfRuntime.scene);
  798. newMesh.id = id;
  799. }
  800. if (!node.babylonNode) {
  801. return newMesh;
  802. }
  803. var subMaterials = [];
  804. var vertexData = null;
  805. var verticesStarts = new Array();
  806. var verticesCounts = new Array();
  807. var indexStarts = new Array();
  808. var indexCounts = new Array();
  809. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  810. var meshID = meshes[meshIndex];
  811. var mesh = gltfRuntime.meshes[meshID];
  812. if (!mesh) {
  813. continue;
  814. }
  815. // Positions, normals and UVs
  816. for (var i = 0; i < mesh.primitives.length; i++) {
  817. // Temporary vertex data
  818. var tempVertexData = new babylonjs_1.VertexData();
  819. var primitive = mesh.primitives[i];
  820. if (primitive.mode !== 4) {
  821. // continue;
  822. }
  823. var attributes = primitive.attributes;
  824. var accessor = null;
  825. var buffer = null;
  826. // Set positions, normal and uvs
  827. for (var semantic in attributes) {
  828. // Link accessor and buffer view
  829. accessor = gltfRuntime.accessors[attributes[semantic]];
  830. buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  831. if (semantic === "NORMAL") {
  832. tempVertexData.normals = new Float32Array(buffer.length);
  833. tempVertexData.normals.set(buffer);
  834. }
  835. else if (semantic === "POSITION") {
  836. if (glTFFileLoader_1.GLTFFileLoader.HomogeneousCoordinates) {
  837. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  838. for (var j = 0; j < buffer.length; j += 4) {
  839. tempVertexData.positions[j] = buffer[j];
  840. tempVertexData.positions[j + 1] = buffer[j + 1];
  841. tempVertexData.positions[j + 2] = buffer[j + 2];
  842. }
  843. }
  844. else {
  845. tempVertexData.positions = new Float32Array(buffer.length);
  846. tempVertexData.positions.set(buffer);
  847. }
  848. verticesCounts.push(tempVertexData.positions.length);
  849. }
  850. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  851. var channel = Number(semantic.split("_")[1]);
  852. var uvKind = babylonjs_1.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  853. var uvs = new Float32Array(buffer.length);
  854. uvs.set(buffer);
  855. normalizeUVs(uvs);
  856. tempVertexData.set(uvs, uvKind);
  857. }
  858. else if (semantic === "JOINT") {
  859. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  860. tempVertexData.matricesIndices.set(buffer);
  861. }
  862. else if (semantic === "WEIGHT") {
  863. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  864. tempVertexData.matricesWeights.set(buffer);
  865. }
  866. else if (semantic === "COLOR") {
  867. tempVertexData.colors = new Float32Array(buffer.length);
  868. tempVertexData.colors.set(buffer);
  869. }
  870. }
  871. // Indices
  872. accessor = gltfRuntime.accessors[primitive.indices];
  873. if (accessor) {
  874. buffer = glTFLoaderUtils_1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  875. tempVertexData.indices = new Int32Array(buffer.length);
  876. tempVertexData.indices.set(buffer);
  877. indexCounts.push(tempVertexData.indices.length);
  878. }
  879. else {
  880. // Set indices on the fly
  881. var indices = [];
  882. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  883. indices.push(j);
  884. }
  885. tempVertexData.indices = new Int32Array(indices);
  886. indexCounts.push(tempVertexData.indices.length);
  887. }
  888. if (!vertexData) {
  889. vertexData = tempVertexData;
  890. }
  891. else {
  892. vertexData.merge(tempVertexData);
  893. }
  894. // Sub material
  895. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  896. subMaterials.push(material_1 === null ? glTFLoaderUtils_1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  897. // Update vertices start and index start
  898. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  899. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  900. }
  901. }
  902. var material;
  903. if (subMaterials.length > 1) {
  904. material = new babylonjs_1.MultiMaterial("multimat" + id, gltfRuntime.scene);
  905. material.subMaterials = subMaterials;
  906. }
  907. else {
  908. material = new babylonjs_1.StandardMaterial("multimat" + id, gltfRuntime.scene);
  909. }
  910. if (subMaterials.length === 1) {
  911. material = subMaterials[0];
  912. }
  913. if (!newMesh.material) {
  914. newMesh.material = material;
  915. }
  916. // Apply geometry
  917. new babylonjs_1.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  918. newMesh.computeWorldMatrix(true);
  919. // Apply submeshes
  920. newMesh.subMeshes = [];
  921. var index = 0;
  922. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  923. var meshID = meshes[meshIndex];
  924. var mesh = gltfRuntime.meshes[meshID];
  925. if (!mesh) {
  926. continue;
  927. }
  928. for (var i = 0; i < mesh.primitives.length; i++) {
  929. if (mesh.primitives[i].mode !== 4) {
  930. //continue;
  931. }
  932. babylonjs_1.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  933. index++;
  934. }
  935. }
  936. // Finish
  937. return newMesh;
  938. };
  939. /**
  940. * Configure node transformation from position, rotation and scaling
  941. */
  942. var configureNode = function (newNode, position, rotation, scaling) {
  943. if (newNode.position) {
  944. newNode.position = position;
  945. }
  946. if (newNode.rotationQuaternion || newNode.rotation) {
  947. newNode.rotationQuaternion = rotation;
  948. }
  949. if (newNode.scaling) {
  950. newNode.scaling = scaling;
  951. }
  952. };
  953. /**
  954. * Configures node from transformation matrix
  955. */
  956. var configureNodeFromMatrix = function (newNode, node, parent) {
  957. if (node.matrix) {
  958. var position = new babylonjs_1.Vector3(0, 0, 0);
  959. var rotation = new babylonjs_1.Quaternion();
  960. var scaling = new babylonjs_1.Vector3(0, 0, 0);
  961. var mat = babylonjs_1.Matrix.FromArray(node.matrix);
  962. mat.decompose(scaling, rotation, position);
  963. configureNode(newNode, position, rotation, scaling);
  964. }
  965. else if (node.translation && node.rotation && node.scale) {
  966. configureNode(newNode, babylonjs_1.Vector3.FromArray(node.translation), babylonjs_1.Quaternion.FromArray(node.rotation), babylonjs_1.Vector3.FromArray(node.scale));
  967. }
  968. newNode.computeWorldMatrix(true);
  969. };
  970. /**
  971. * Imports a node
  972. */
  973. var importNode = function (gltfRuntime, node, id, parent) {
  974. var lastNode = null;
  975. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  976. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  977. return null;
  978. }
  979. }
  980. // Meshes
  981. if (node.skin) {
  982. if (node.meshes) {
  983. var skin = gltfRuntime.skins[node.skin];
  984. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  985. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  986. if (newMesh.skeleton === null) {
  987. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  988. if (!skin.babylonSkeleton) {
  989. skin.babylonSkeleton = newMesh.skeleton;
  990. }
  991. }
  992. lastNode = newMesh;
  993. }
  994. }
  995. else if (node.meshes) {
  996. /**
  997. * Improve meshes property
  998. */
  999. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  1000. lastNode = newMesh;
  1001. }
  1002. // Lights
  1003. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1004. var light = gltfRuntime.lights[node.light];
  1005. if (light) {
  1006. if (light.type === "ambient") {
  1007. var ambienLight = light[light.type];
  1008. var hemiLight = new babylonjs_1.HemisphericLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  1009. hemiLight.name = node.name || "";
  1010. if (ambienLight.color) {
  1011. hemiLight.diffuse = babylonjs_1.Color3.FromArray(ambienLight.color);
  1012. }
  1013. lastNode = hemiLight;
  1014. }
  1015. else if (light.type === "directional") {
  1016. var directionalLight = light[light.type];
  1017. var dirLight = new babylonjs_1.DirectionalLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  1018. dirLight.name = node.name || "";
  1019. if (directionalLight.color) {
  1020. dirLight.diffuse = babylonjs_1.Color3.FromArray(directionalLight.color);
  1021. }
  1022. lastNode = dirLight;
  1023. }
  1024. else if (light.type === "point") {
  1025. var pointLight = light[light.type];
  1026. var ptLight = new babylonjs_1.PointLight(node.light, babylonjs_1.Vector3.Zero(), gltfRuntime.scene);
  1027. ptLight.name = node.name || "";
  1028. if (pointLight.color) {
  1029. ptLight.diffuse = babylonjs_1.Color3.FromArray(pointLight.color);
  1030. }
  1031. lastNode = ptLight;
  1032. }
  1033. else if (light.type === "spot") {
  1034. var spotLight = light[light.type];
  1035. var spLight = new babylonjs_1.SpotLight(node.light, babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1036. spLight.name = node.name || "";
  1037. if (spotLight.color) {
  1038. spLight.diffuse = babylonjs_1.Color3.FromArray(spotLight.color);
  1039. }
  1040. if (spotLight.fallOfAngle) {
  1041. spLight.angle = spotLight.fallOfAngle;
  1042. }
  1043. if (spotLight.fallOffExponent) {
  1044. spLight.exponent = spotLight.fallOffExponent;
  1045. }
  1046. lastNode = spLight;
  1047. }
  1048. }
  1049. }
  1050. // Cameras
  1051. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1052. var camera = gltfRuntime.cameras[node.camera];
  1053. if (camera) {
  1054. if (camera.type === "orthographic") {
  1055. var orthoCamera = new babylonjs_1.FreeCamera(node.camera, babylonjs_1.Vector3.Zero(), gltfRuntime.scene, false);
  1056. orthoCamera.name = node.name || "";
  1057. orthoCamera.mode = babylonjs_1.Camera.ORTHOGRAPHIC_CAMERA;
  1058. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1059. lastNode = orthoCamera;
  1060. }
  1061. else if (camera.type === "perspective") {
  1062. var perspectiveCamera = camera[camera.type];
  1063. var persCamera = new babylonjs_1.FreeCamera(node.camera, babylonjs_1.Vector3.Zero(), gltfRuntime.scene, false);
  1064. persCamera.name = node.name || "";
  1065. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1066. if (!perspectiveCamera.aspectRatio) {
  1067. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1068. }
  1069. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1070. persCamera.maxZ = perspectiveCamera.zfar;
  1071. persCamera.minZ = perspectiveCamera.znear;
  1072. }
  1073. lastNode = persCamera;
  1074. }
  1075. }
  1076. }
  1077. // Empty node
  1078. if (!node.jointName) {
  1079. if (node.babylonNode) {
  1080. return node.babylonNode;
  1081. }
  1082. else if (lastNode === null) {
  1083. var dummy = new babylonjs_1.Mesh(node.name || "", gltfRuntime.scene);
  1084. node.babylonNode = dummy;
  1085. lastNode = dummy;
  1086. }
  1087. }
  1088. if (lastNode !== null) {
  1089. if (node.matrix && lastNode instanceof babylonjs_1.Mesh) {
  1090. configureNodeFromMatrix(lastNode, node, parent);
  1091. }
  1092. else {
  1093. var translation = node.translation || [0, 0, 0];
  1094. var rotation = node.rotation || [0, 0, 0, 1];
  1095. var scale = node.scale || [1, 1, 1];
  1096. configureNode(lastNode, babylonjs_1.Vector3.FromArray(translation), babylonjs_1.Quaternion.FromArray(rotation), babylonjs_1.Vector3.FromArray(scale));
  1097. }
  1098. lastNode.updateCache(true);
  1099. node.babylonNode = lastNode;
  1100. }
  1101. return lastNode;
  1102. };
  1103. /**
  1104. * Traverses nodes and creates them
  1105. */
  1106. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1107. if (meshIncluded === void 0) { meshIncluded = false; }
  1108. var node = gltfRuntime.nodes[id];
  1109. var newNode = null;
  1110. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  1111. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1112. meshIncluded = true;
  1113. }
  1114. else {
  1115. meshIncluded = false;
  1116. }
  1117. }
  1118. else {
  1119. meshIncluded = true;
  1120. }
  1121. if (!node.jointName && meshIncluded) {
  1122. newNode = importNode(gltfRuntime, node, id, parent);
  1123. if (newNode !== null) {
  1124. newNode.id = id;
  1125. newNode.parent = parent;
  1126. }
  1127. }
  1128. if (node.children) {
  1129. for (var i = 0; i < node.children.length; i++) {
  1130. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1131. }
  1132. }
  1133. };
  1134. /**
  1135. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1136. */
  1137. var postLoad = function (gltfRuntime) {
  1138. // Nodes
  1139. var currentScene = gltfRuntime.currentScene;
  1140. if (currentScene) {
  1141. for (var i = 0; i < currentScene.nodes.length; i++) {
  1142. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1143. }
  1144. }
  1145. else {
  1146. for (var thing in gltfRuntime.scenes) {
  1147. currentScene = gltfRuntime.scenes[thing];
  1148. for (var i = 0; i < currentScene.nodes.length; i++) {
  1149. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1150. }
  1151. }
  1152. }
  1153. // Set animations
  1154. loadAnimations(gltfRuntime);
  1155. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1156. var skeleton = gltfRuntime.scene.skeletons[i];
  1157. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1158. }
  1159. };
  1160. /**
  1161. * onBind shaderrs callback to set uniforms and matrices
  1162. */
  1163. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1164. var materialValues = material.values || technique.parameters;
  1165. for (var unif in unTreatedUniforms) {
  1166. var uniform = unTreatedUniforms[unif];
  1167. var type = uniform.type;
  1168. if (type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT2 || type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT3 || type === glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT4) {
  1169. if (uniform.semantic && !uniform.source && !uniform.node) {
  1170. glTFLoaderUtils_1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1171. }
  1172. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1173. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  1174. if (source === null) {
  1175. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  1176. }
  1177. if (source === null) {
  1178. continue;
  1179. }
  1180. glTFLoaderUtils_1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1181. }
  1182. }
  1183. else {
  1184. var value = materialValues[technique.uniforms[unif]];
  1185. if (!value) {
  1186. continue;
  1187. }
  1188. if (type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  1189. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1190. if (texture === null || texture === undefined) {
  1191. continue;
  1192. }
  1193. shaderMaterial.getEffect().setTexture(unif, texture);
  1194. }
  1195. else {
  1196. glTFLoaderUtils_1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  1197. }
  1198. }
  1199. }
  1200. onSuccess(shaderMaterial);
  1201. };
  1202. /**
  1203. * Prepare uniforms to send the only one time
  1204. * Loads the appropriate textures
  1205. */
  1206. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1207. var materialValues = material.values || technique.parameters;
  1208. var techniqueUniforms = technique.uniforms;
  1209. /**
  1210. * Prepare values here (not matrices)
  1211. */
  1212. for (var unif in unTreatedUniforms) {
  1213. var uniform = unTreatedUniforms[unif];
  1214. var type = uniform.type;
  1215. var value = materialValues[techniqueUniforms[unif]];
  1216. if (value === undefined) {
  1217. // In case the value is the same for all materials
  1218. value = uniform.value;
  1219. }
  1220. if (!value) {
  1221. continue;
  1222. }
  1223. var onLoadTexture = function (uniformName) {
  1224. return function (texture) {
  1225. if (uniform.value && uniformName) {
  1226. // Static uniform
  1227. shaderMaterial.setTexture(uniformName, texture);
  1228. delete unTreatedUniforms[uniformName];
  1229. }
  1230. };
  1231. };
  1232. // Texture (sampler2D)
  1233. if (type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  1234. glTFLoaderExtension_1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1235. }
  1236. // Others
  1237. else {
  1238. if (uniform.value && glTFLoaderUtils_1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1239. // Static uniform
  1240. delete unTreatedUniforms[unif];
  1241. }
  1242. }
  1243. }
  1244. };
  1245. /**
  1246. * Shader compilation failed
  1247. */
  1248. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1249. return function (effect, error) {
  1250. shaderMaterial.dispose(true);
  1251. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1252. };
  1253. };
  1254. /**
  1255. * Shader compilation success
  1256. */
  1257. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1258. return function (_) {
  1259. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1260. shaderMaterial.onBind = function (mesh) {
  1261. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1262. };
  1263. };
  1264. };
  1265. /**
  1266. * Returns the appropriate uniform if already handled by babylon
  1267. */
  1268. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1269. for (var unif in technique.uniforms) {
  1270. var uniform = technique.uniforms[unif];
  1271. var uniformParameter = technique.parameters[uniform];
  1272. if (tokenizer.currentIdentifier === unif) {
  1273. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1274. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1275. if (transformIndex !== -1) {
  1276. delete unTreatedUniforms[unif];
  1277. return babylonTransforms[transformIndex];
  1278. }
  1279. }
  1280. }
  1281. }
  1282. return tokenizer.currentIdentifier;
  1283. };
  1284. /**
  1285. * All shaders loaded. Create materials one by one
  1286. */
  1287. var importMaterials = function (gltfRuntime) {
  1288. // Create materials
  1289. for (var mat in gltfRuntime.materials) {
  1290. glTFLoaderExtension_1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1291. }
  1292. };
  1293. /**
  1294. * Implementation of the base glTF spec
  1295. * @hidden
  1296. */
  1297. var GLTFLoaderBase = /** @class */ (function () {
  1298. function GLTFLoaderBase() {
  1299. }
  1300. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1301. var gltfRuntime = {
  1302. extensions: {},
  1303. accessors: {},
  1304. buffers: {},
  1305. bufferViews: {},
  1306. meshes: {},
  1307. lights: {},
  1308. cameras: {},
  1309. nodes: {},
  1310. images: {},
  1311. textures: {},
  1312. shaders: {},
  1313. programs: {},
  1314. samplers: {},
  1315. techniques: {},
  1316. materials: {},
  1317. animations: {},
  1318. skins: {},
  1319. extensionsUsed: [],
  1320. scenes: {},
  1321. buffersCount: 0,
  1322. shaderscount: 0,
  1323. scene: scene,
  1324. rootUrl: rootUrl,
  1325. loadedBufferCount: 0,
  1326. loadedBufferViews: {},
  1327. loadedShaderCount: 0,
  1328. importOnlyMeshes: false,
  1329. dummyNodes: []
  1330. };
  1331. // Parse
  1332. if (parsedData.extensions) {
  1333. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1334. }
  1335. if (parsedData.extensionsUsed) {
  1336. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1337. }
  1338. if (parsedData.buffers) {
  1339. parseBuffers(parsedData.buffers, gltfRuntime);
  1340. }
  1341. if (parsedData.bufferViews) {
  1342. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1343. }
  1344. if (parsedData.accessors) {
  1345. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1346. }
  1347. if (parsedData.meshes) {
  1348. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1349. }
  1350. if (parsedData.lights) {
  1351. parseObject(parsedData.lights, "lights", gltfRuntime);
  1352. }
  1353. if (parsedData.cameras) {
  1354. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1355. }
  1356. if (parsedData.nodes) {
  1357. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1358. }
  1359. if (parsedData.images) {
  1360. parseObject(parsedData.images, "images", gltfRuntime);
  1361. }
  1362. if (parsedData.textures) {
  1363. parseObject(parsedData.textures, "textures", gltfRuntime);
  1364. }
  1365. if (parsedData.shaders) {
  1366. parseShaders(parsedData.shaders, gltfRuntime);
  1367. }
  1368. if (parsedData.programs) {
  1369. parseObject(parsedData.programs, "programs", gltfRuntime);
  1370. }
  1371. if (parsedData.samplers) {
  1372. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1373. }
  1374. if (parsedData.techniques) {
  1375. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1376. }
  1377. if (parsedData.materials) {
  1378. parseObject(parsedData.materials, "materials", gltfRuntime);
  1379. }
  1380. if (parsedData.animations) {
  1381. parseObject(parsedData.animations, "animations", gltfRuntime);
  1382. }
  1383. if (parsedData.skins) {
  1384. parseObject(parsedData.skins, "skins", gltfRuntime);
  1385. }
  1386. if (parsedData.scenes) {
  1387. gltfRuntime.scenes = parsedData.scenes;
  1388. }
  1389. if (parsedData.scene && parsedData.scenes) {
  1390. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1391. }
  1392. return gltfRuntime;
  1393. };
  1394. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1395. var buffer = gltfRuntime.buffers[id];
  1396. if (babylonjs_1.Tools.IsBase64(buffer.uri)) {
  1397. setTimeout(function () { return onSuccess(new Uint8Array(babylonjs_1.Tools.DecodeBase64(buffer.uri))); });
  1398. }
  1399. else {
  1400. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  1401. if (request) {
  1402. onError(request.status + " " + request.statusText);
  1403. }
  1404. });
  1405. }
  1406. };
  1407. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1408. var texture = gltfRuntime.textures[id];
  1409. if (!texture || !texture.source) {
  1410. onError("");
  1411. return;
  1412. }
  1413. if (texture.babylonTexture) {
  1414. onSuccess(null);
  1415. return;
  1416. }
  1417. var source = gltfRuntime.images[texture.source];
  1418. if (babylonjs_1.Tools.IsBase64(source.uri)) {
  1419. setTimeout(function () { return onSuccess(new Uint8Array(babylonjs_1.Tools.DecodeBase64(source.uri))); });
  1420. }
  1421. else {
  1422. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  1423. if (request) {
  1424. onError(request.status + " " + request.statusText);
  1425. }
  1426. });
  1427. }
  1428. };
  1429. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1430. var texture = gltfRuntime.textures[id];
  1431. if (texture.babylonTexture) {
  1432. onSuccess(texture.babylonTexture);
  1433. return;
  1434. }
  1435. var sampler = gltfRuntime.samplers[texture.sampler];
  1436. var createMipMaps = (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1437. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1438. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1439. (sampler.minFilter === glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1440. var samplingMode = babylonjs_1.Texture.BILINEAR_SAMPLINGMODE;
  1441. var blob = buffer == null ? new Blob() : new Blob([buffer]);
  1442. var blobURL = URL.createObjectURL(blob);
  1443. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1444. var newTexture = new babylonjs_1.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1445. if (sampler.wrapS !== undefined) {
  1446. newTexture.wrapU = glTFLoaderUtils_1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1447. }
  1448. if (sampler.wrapT !== undefined) {
  1449. newTexture.wrapV = glTFLoaderUtils_1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1450. }
  1451. newTexture.name = id;
  1452. texture.babylonTexture = newTexture;
  1453. onSuccess(newTexture);
  1454. };
  1455. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1456. var shader = gltfRuntime.shaders[id];
  1457. if (babylonjs_1.Tools.IsBase64(shader.uri)) {
  1458. var shaderString = atob(shader.uri.split(",")[1]);
  1459. if (onSuccess) {
  1460. onSuccess(shaderString);
  1461. }
  1462. }
  1463. else {
  1464. babylonjs_1.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  1465. if (request && onError) {
  1466. onError(request.status + " " + request.statusText);
  1467. }
  1468. });
  1469. }
  1470. };
  1471. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1472. var material = gltfRuntime.materials[id];
  1473. if (!material.technique) {
  1474. if (onError) {
  1475. onError("No technique found.");
  1476. }
  1477. return;
  1478. }
  1479. var technique = gltfRuntime.techniques[material.technique];
  1480. if (!technique) {
  1481. var defaultMaterial = new babylonjs_1.StandardMaterial(id, gltfRuntime.scene);
  1482. defaultMaterial.diffuseColor = new babylonjs_1.Color3(0.5, 0.5, 0.5);
  1483. defaultMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  1484. onSuccess(defaultMaterial);
  1485. return;
  1486. }
  1487. var program = gltfRuntime.programs[technique.program];
  1488. var states = technique.states;
  1489. var vertexShader = babylonjs_1.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1490. var pixelShader = babylonjs_1.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1491. var newVertexShader = "";
  1492. var newPixelShader = "";
  1493. var vertexTokenizer = new Tokenizer(vertexShader);
  1494. var pixelTokenizer = new Tokenizer(pixelShader);
  1495. var unTreatedUniforms = {};
  1496. var uniforms = [];
  1497. var attributes = [];
  1498. var samplers = [];
  1499. // Fill uniform, sampler2D and attributes
  1500. for (var unif in technique.uniforms) {
  1501. var uniform = technique.uniforms[unif];
  1502. var uniformParameter = technique.parameters[uniform];
  1503. unTreatedUniforms[unif] = uniformParameter;
  1504. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1505. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1506. if (transformIndex !== -1) {
  1507. uniforms.push(babylonTransforms[transformIndex]);
  1508. delete unTreatedUniforms[unif];
  1509. }
  1510. else {
  1511. uniforms.push(unif);
  1512. }
  1513. }
  1514. else if (uniformParameter.type === glTFLoaderInterfaces_1.EParameterType.SAMPLER_2D) {
  1515. samplers.push(unif);
  1516. }
  1517. else {
  1518. uniforms.push(unif);
  1519. }
  1520. }
  1521. for (var attr in technique.attributes) {
  1522. var attribute = technique.attributes[attr];
  1523. var attributeParameter = technique.parameters[attribute];
  1524. if (attributeParameter.semantic) {
  1525. var name_1 = getAttribute(attributeParameter);
  1526. if (name_1) {
  1527. attributes.push(name_1);
  1528. }
  1529. }
  1530. }
  1531. // Configure vertex shader
  1532. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1533. var tokenType = vertexTokenizer.currentToken;
  1534. if (tokenType !== ETokenType.IDENTIFIER) {
  1535. newVertexShader += vertexTokenizer.currentString;
  1536. continue;
  1537. }
  1538. var foundAttribute = false;
  1539. for (var attr in technique.attributes) {
  1540. var attribute = technique.attributes[attr];
  1541. var attributeParameter = technique.parameters[attribute];
  1542. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1543. newVertexShader += getAttribute(attributeParameter);
  1544. foundAttribute = true;
  1545. break;
  1546. }
  1547. }
  1548. if (foundAttribute) {
  1549. continue;
  1550. }
  1551. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1552. }
  1553. // Configure pixel shader
  1554. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1555. var tokenType = pixelTokenizer.currentToken;
  1556. if (tokenType !== ETokenType.IDENTIFIER) {
  1557. newPixelShader += pixelTokenizer.currentString;
  1558. continue;
  1559. }
  1560. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1561. }
  1562. // Create shader material
  1563. var shaderPath = {
  1564. vertex: program.vertexShader + id,
  1565. fragment: program.fragmentShader + id
  1566. };
  1567. var options = {
  1568. attributes: attributes,
  1569. uniforms: uniforms,
  1570. samplers: samplers,
  1571. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1572. };
  1573. babylonjs_1.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1574. babylonjs_1.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1575. var shaderMaterial = new babylonjs_1.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1576. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1577. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1578. shaderMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  1579. if (states && states.functions) {
  1580. var functions = states.functions;
  1581. if (functions.cullFace && functions.cullFace[0] !== glTFLoaderInterfaces_1.ECullingType.BACK) {
  1582. shaderMaterial.backFaceCulling = false;
  1583. }
  1584. var blendFunc = functions.blendFuncSeparate;
  1585. if (blendFunc) {
  1586. if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1587. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_COMBINE;
  1588. }
  1589. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1590. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_ONEONE;
  1591. }
  1592. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1593. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_ADD;
  1594. }
  1595. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1596. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_SUBTRACT;
  1597. }
  1598. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.DST_COLOR && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ZERO && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1599. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_MULTIPLY;
  1600. }
  1601. else if (blendFunc[0] === glTFLoaderInterfaces_1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === glTFLoaderInterfaces_1.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === glTFLoaderInterfaces_1.EBlendingFunction.ONE && blendFunc[3] === glTFLoaderInterfaces_1.EBlendingFunction.ONE) {
  1602. shaderMaterial.alphaMode = babylonjs_1.Engine.ALPHA_MAXIMIZED;
  1603. }
  1604. }
  1605. }
  1606. };
  1607. return GLTFLoaderBase;
  1608. }());
  1609. exports.GLTFLoaderBase = GLTFLoaderBase;
  1610. /**
  1611. * glTF V1 Loader
  1612. * @hidden
  1613. */
  1614. var GLTFLoader = /** @class */ (function () {
  1615. function GLTFLoader() {
  1616. this.state = null;
  1617. }
  1618. GLTFLoader.RegisterExtension = function (extension) {
  1619. if (GLTFLoader.Extensions[extension.name]) {
  1620. babylonjs_1.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1621. return;
  1622. }
  1623. GLTFLoader.Extensions[extension.name] = extension;
  1624. };
  1625. GLTFLoader.prototype.dispose = function () {
  1626. // do nothing
  1627. };
  1628. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  1629. var _this = this;
  1630. scene.useRightHandedSystem = true;
  1631. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1632. gltfRuntime.importOnlyMeshes = true;
  1633. if (meshesNames === "") {
  1634. gltfRuntime.importMeshesNames = [];
  1635. }
  1636. else if (typeof meshesNames === "string") {
  1637. gltfRuntime.importMeshesNames = [meshesNames];
  1638. }
  1639. else if (meshesNames && !(meshesNames instanceof Array)) {
  1640. gltfRuntime.importMeshesNames = [meshesNames];
  1641. }
  1642. else {
  1643. gltfRuntime.importMeshesNames = [];
  1644. babylonjs_1.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1645. }
  1646. // Create nodes
  1647. _this._createNodes(gltfRuntime);
  1648. var meshes = new Array();
  1649. var skeletons = new Array();
  1650. // Fill arrays of meshes and skeletons
  1651. for (var nde in gltfRuntime.nodes) {
  1652. var node = gltfRuntime.nodes[nde];
  1653. if (node.babylonNode instanceof babylonjs_1.AbstractMesh) {
  1654. meshes.push(node.babylonNode);
  1655. }
  1656. }
  1657. for (var skl in gltfRuntime.skins) {
  1658. var skin = gltfRuntime.skins[skl];
  1659. if (skin.babylonSkeleton instanceof babylonjs_1.Skeleton) {
  1660. skeletons.push(skin.babylonSkeleton);
  1661. }
  1662. }
  1663. // Load buffers, shaders, materials, etc.
  1664. _this._loadBuffersAsync(gltfRuntime, function () {
  1665. _this._loadShadersAsync(gltfRuntime, function () {
  1666. importMaterials(gltfRuntime);
  1667. postLoad(gltfRuntime);
  1668. if (!glTFFileLoader_1.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1669. onSuccess(meshes, skeletons);
  1670. }
  1671. });
  1672. }, onProgress);
  1673. if (glTFFileLoader_1.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1674. onSuccess(meshes, skeletons);
  1675. }
  1676. }, onError);
  1677. return true;
  1678. };
  1679. /**
  1680. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  1681. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  1682. * @param scene the scene the meshes should be added to
  1683. * @param data gltf data containing information of the meshes in a loaded file
  1684. * @param rootUrl root url to load from
  1685. * @param onProgress event that fires when loading progress has occured
  1686. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  1687. */
  1688. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  1689. var _this = this;
  1690. return new Promise(function (resolve, reject) {
  1691. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  1692. resolve({
  1693. meshes: meshes,
  1694. particleSystems: [],
  1695. skeletons: skeletons,
  1696. animationGroups: []
  1697. });
  1698. }, onProgress, function (message) {
  1699. reject(new Error(message));
  1700. });
  1701. });
  1702. };
  1703. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  1704. var _this = this;
  1705. scene.useRightHandedSystem = true;
  1706. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1707. // Load runtime extensios
  1708. glTFLoaderExtension_1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1709. // Create nodes
  1710. _this._createNodes(gltfRuntime);
  1711. // Load buffers, shaders, materials, etc.
  1712. _this._loadBuffersAsync(gltfRuntime, function () {
  1713. _this._loadShadersAsync(gltfRuntime, function () {
  1714. importMaterials(gltfRuntime);
  1715. postLoad(gltfRuntime);
  1716. if (!glTFFileLoader_1.GLTFFileLoader.IncrementalLoading) {
  1717. onSuccess();
  1718. }
  1719. });
  1720. });
  1721. if (glTFFileLoader_1.GLTFFileLoader.IncrementalLoading) {
  1722. onSuccess();
  1723. }
  1724. }, onError);
  1725. }, onError);
  1726. };
  1727. /**
  1728. * Imports all objects from a loaded gltf file and adds them to the scene
  1729. * @param scene the scene the objects should be added to
  1730. * @param data gltf data containing information of the meshes in a loaded file
  1731. * @param rootUrl root url to load from
  1732. * @param onProgress event that fires when loading progress has occured
  1733. * @returns a promise which completes when objects have been loaded to the scene
  1734. */
  1735. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  1736. var _this = this;
  1737. return new Promise(function (resolve, reject) {
  1738. _this._loadAsync(scene, data, rootUrl, function () {
  1739. resolve();
  1740. }, onProgress, function (message) {
  1741. reject(new Error(message));
  1742. });
  1743. });
  1744. };
  1745. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1746. var hasShaders = false;
  1747. var processShader = function (sha, shader) {
  1748. glTFLoaderExtension_1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1749. if (shaderString instanceof ArrayBuffer) {
  1750. return;
  1751. }
  1752. gltfRuntime.loadedShaderCount++;
  1753. if (shaderString) {
  1754. babylonjs_1.Effect.ShadersStore[sha + (shader.type === glTFLoaderInterfaces_1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1755. }
  1756. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1757. onload();
  1758. }
  1759. }, function () {
  1760. babylonjs_1.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1761. });
  1762. };
  1763. for (var sha in gltfRuntime.shaders) {
  1764. hasShaders = true;
  1765. var shader = gltfRuntime.shaders[sha];
  1766. if (shader) {
  1767. processShader.bind(this, sha, shader)();
  1768. }
  1769. else {
  1770. babylonjs_1.Tools.Error("No shader named: " + sha);
  1771. }
  1772. }
  1773. if (!hasShaders) {
  1774. onload();
  1775. }
  1776. };
  1777. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  1778. var hasBuffers = false;
  1779. var processBuffer = function (buf, buffer) {
  1780. glTFLoaderExtension_1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1781. gltfRuntime.loadedBufferCount++;
  1782. if (bufferView) {
  1783. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1784. babylonjs_1.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1785. }
  1786. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1787. }
  1788. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1789. onLoad();
  1790. }
  1791. }, function () {
  1792. babylonjs_1.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1793. });
  1794. };
  1795. for (var buf in gltfRuntime.buffers) {
  1796. hasBuffers = true;
  1797. var buffer = gltfRuntime.buffers[buf];
  1798. if (buffer) {
  1799. processBuffer.bind(this, buf, buffer)();
  1800. }
  1801. else {
  1802. babylonjs_1.Tools.Error("No buffer named: " + buf);
  1803. }
  1804. }
  1805. if (!hasBuffers) {
  1806. onLoad();
  1807. }
  1808. };
  1809. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  1810. var currentScene = gltfRuntime.currentScene;
  1811. if (currentScene) {
  1812. // Only one scene even if multiple scenes are defined
  1813. for (var i = 0; i < currentScene.nodes.length; i++) {
  1814. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1815. }
  1816. }
  1817. else {
  1818. // Load all scenes
  1819. for (var thing in gltfRuntime.scenes) {
  1820. currentScene = gltfRuntime.scenes[thing];
  1821. for (var i = 0; i < currentScene.nodes.length; i++) {
  1822. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1823. }
  1824. }
  1825. }
  1826. };
  1827. GLTFLoader.Extensions = {};
  1828. return GLTFLoader;
  1829. }());
  1830. exports.GLTFLoader = GLTFLoader;
  1831. glTFFileLoader_1.GLTFFileLoader._CreateGLTF1Loader = function () { return new GLTFLoader(); };
  1832. /***/ }),
  1833. /***/ "./src/glTF/1.0/glTFLoaderExtension.ts":
  1834. /*!*********************************************!*\
  1835. !*** ./src/glTF/1.0/glTFLoaderExtension.ts ***!
  1836. \*********************************************/
  1837. /*! no static exports found */
  1838. /***/ (function(module, exports, __webpack_require__) {
  1839. "use strict";
  1840. Object.defineProperty(exports, "__esModule", { value: true });
  1841. var glTFLoader_1 = __webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts");
  1842. /** @hidden */
  1843. var GLTFLoaderExtension = /** @class */ (function () {
  1844. function GLTFLoaderExtension(name) {
  1845. this._name = name;
  1846. }
  1847. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  1848. get: function () {
  1849. return this._name;
  1850. },
  1851. enumerable: true,
  1852. configurable: true
  1853. });
  1854. /**
  1855. * Defines an override for loading the runtime
  1856. * Return true to stop further extensions from loading the runtime
  1857. */
  1858. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1859. return false;
  1860. };
  1861. /**
  1862. * Defines an onverride for creating gltf runtime
  1863. * Return true to stop further extensions from creating the runtime
  1864. */
  1865. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  1866. return false;
  1867. };
  1868. /**
  1869. * Defines an override for loading buffers
  1870. * Return true to stop further extensions from loading this buffer
  1871. */
  1872. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1873. return false;
  1874. };
  1875. /**
  1876. * Defines an override for loading texture buffers
  1877. * Return true to stop further extensions from loading this texture data
  1878. */
  1879. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1880. return false;
  1881. };
  1882. /**
  1883. * Defines an override for creating textures
  1884. * Return true to stop further extensions from loading this texture
  1885. */
  1886. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1887. return false;
  1888. };
  1889. /**
  1890. * Defines an override for loading shader strings
  1891. * Return true to stop further extensions from loading this shader data
  1892. */
  1893. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1894. return false;
  1895. };
  1896. /**
  1897. * Defines an override for loading materials
  1898. * Return true to stop further extensions from loading this material
  1899. */
  1900. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1901. return false;
  1902. };
  1903. // ---------
  1904. // Utilities
  1905. // ---------
  1906. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1907. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1908. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  1909. }, function () {
  1910. setTimeout(function () {
  1911. if (!onSuccess) {
  1912. return;
  1913. }
  1914. onSuccess(glTFLoader_1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  1915. });
  1916. });
  1917. };
  1918. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  1919. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1920. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  1921. }, function () {
  1922. setTimeout(function () {
  1923. onSuccess();
  1924. });
  1925. });
  1926. };
  1927. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1928. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1929. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  1930. }, function () {
  1931. glTFLoader_1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  1932. });
  1933. };
  1934. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  1935. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  1936. if (buffer) {
  1937. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1938. }
  1939. }, onError);
  1940. };
  1941. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1942. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1943. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1944. }, function () {
  1945. glTFLoader_1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1946. });
  1947. };
  1948. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1949. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1950. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1951. }, function () {
  1952. glTFLoader_1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1953. });
  1954. };
  1955. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1956. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1957. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1958. }, function () {
  1959. glTFLoader_1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1960. });
  1961. };
  1962. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1963. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1964. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1965. }, function () {
  1966. glTFLoader_1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1967. });
  1968. };
  1969. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  1970. for (var extensionName in glTFLoader_1.GLTFLoader.Extensions) {
  1971. var loaderExtension = glTFLoader_1.GLTFLoader.Extensions[extensionName];
  1972. if (func(loaderExtension)) {
  1973. return;
  1974. }
  1975. }
  1976. defaultFunc();
  1977. };
  1978. return GLTFLoaderExtension;
  1979. }());
  1980. exports.GLTFLoaderExtension = GLTFLoaderExtension;
  1981. /***/ }),
  1982. /***/ "./src/glTF/1.0/glTFLoaderInterfaces.ts":
  1983. /*!**********************************************!*\
  1984. !*** ./src/glTF/1.0/glTFLoaderInterfaces.ts ***!
  1985. \**********************************************/
  1986. /*! no static exports found */
  1987. /***/ (function(module, exports, __webpack_require__) {
  1988. "use strict";
  1989. Object.defineProperty(exports, "__esModule", { value: true });
  1990. /**
  1991. * Enums
  1992. * @hidden
  1993. */
  1994. var EComponentType;
  1995. (function (EComponentType) {
  1996. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  1997. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  1998. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  1999. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  2000. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  2001. })(EComponentType = exports.EComponentType || (exports.EComponentType = {}));
  2002. /** @hidden */
  2003. var EShaderType;
  2004. (function (EShaderType) {
  2005. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  2006. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  2007. })(EShaderType = exports.EShaderType || (exports.EShaderType = {}));
  2008. /** @hidden */
  2009. var EParameterType;
  2010. (function (EParameterType) {
  2011. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  2012. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  2013. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  2014. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  2015. EParameterType[EParameterType["INT"] = 5124] = "INT";
  2016. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  2017. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  2018. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  2019. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  2020. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  2021. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  2022. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  2023. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  2024. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  2025. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  2026. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  2027. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  2028. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  2029. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  2030. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  2031. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  2032. })(EParameterType = exports.EParameterType || (exports.EParameterType = {}));
  2033. /** @hidden */
  2034. var ETextureWrapMode;
  2035. (function (ETextureWrapMode) {
  2036. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  2037. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  2038. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  2039. })(ETextureWrapMode = exports.ETextureWrapMode || (exports.ETextureWrapMode = {}));
  2040. /** @hidden */
  2041. var ETextureFilterType;
  2042. (function (ETextureFilterType) {
  2043. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  2044. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  2045. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  2046. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  2047. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  2048. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  2049. })(ETextureFilterType = exports.ETextureFilterType || (exports.ETextureFilterType = {}));
  2050. /** @hidden */
  2051. var ETextureFormat;
  2052. (function (ETextureFormat) {
  2053. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  2054. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  2055. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  2056. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  2057. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  2058. })(ETextureFormat = exports.ETextureFormat || (exports.ETextureFormat = {}));
  2059. /** @hidden */
  2060. var ECullingType;
  2061. (function (ECullingType) {
  2062. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  2063. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  2064. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  2065. })(ECullingType = exports.ECullingType || (exports.ECullingType = {}));
  2066. /** @hidden */
  2067. var EBlendingFunction;
  2068. (function (EBlendingFunction) {
  2069. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  2070. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  2071. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  2072. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  2073. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  2074. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  2075. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  2076. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  2077. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  2078. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  2079. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  2080. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  2081. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  2082. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  2083. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  2084. })(EBlendingFunction = exports.EBlendingFunction || (exports.EBlendingFunction = {}));
  2085. /***/ }),
  2086. /***/ "./src/glTF/1.0/glTFLoaderUtils.ts":
  2087. /*!*****************************************!*\
  2088. !*** ./src/glTF/1.0/glTFLoaderUtils.ts ***!
  2089. \*****************************************/
  2090. /*! no static exports found */
  2091. /***/ (function(module, exports, __webpack_require__) {
  2092. "use strict";
  2093. Object.defineProperty(exports, "__esModule", { value: true });
  2094. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2095. var glTFLoaderInterfaces_1 = __webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts");
  2096. /**
  2097. * Utils functions for GLTF
  2098. * @hidden
  2099. */
  2100. var GLTFUtils = /** @class */ (function () {
  2101. function GLTFUtils() {
  2102. }
  2103. /**
  2104. * Sets the given "parameter" matrix
  2105. * @param scene: the Scene object
  2106. * @param source: the source node where to pick the matrix
  2107. * @param parameter: the GLTF technique parameter
  2108. * @param uniformName: the name of the shader's uniform
  2109. * @param shaderMaterial: the shader material
  2110. */
  2111. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  2112. var mat = null;
  2113. if (parameter.semantic === "MODEL") {
  2114. mat = source.getWorldMatrix();
  2115. }
  2116. else if (parameter.semantic === "PROJECTION") {
  2117. mat = scene.getProjectionMatrix();
  2118. }
  2119. else if (parameter.semantic === "VIEW") {
  2120. mat = scene.getViewMatrix();
  2121. }
  2122. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  2123. mat = babylonjs_1.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  2124. }
  2125. else if (parameter.semantic === "MODELVIEW") {
  2126. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  2127. }
  2128. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  2129. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  2130. }
  2131. else if (parameter.semantic === "MODELINVERSE") {
  2132. mat = source.getWorldMatrix().invert();
  2133. }
  2134. else if (parameter.semantic === "VIEWINVERSE") {
  2135. mat = scene.getViewMatrix().invert();
  2136. }
  2137. else if (parameter.semantic === "PROJECTIONINVERSE") {
  2138. mat = scene.getProjectionMatrix().invert();
  2139. }
  2140. else if (parameter.semantic === "MODELVIEWINVERSE") {
  2141. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  2142. }
  2143. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  2144. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  2145. }
  2146. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  2147. mat = babylonjs_1.Matrix.Transpose(source.getWorldMatrix().invert());
  2148. }
  2149. else {
  2150. debugger;
  2151. }
  2152. if (mat) {
  2153. switch (parameter.type) {
  2154. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT2:
  2155. shaderMaterial.setMatrix2x2(uniformName, babylonjs_1.Matrix.GetAsMatrix2x2(mat));
  2156. break;
  2157. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT3:
  2158. shaderMaterial.setMatrix3x3(uniformName, babylonjs_1.Matrix.GetAsMatrix3x3(mat));
  2159. break;
  2160. case glTFLoaderInterfaces_1.EParameterType.FLOAT_MAT4:
  2161. shaderMaterial.setMatrix(uniformName, mat);
  2162. break;
  2163. default: break;
  2164. }
  2165. }
  2166. };
  2167. /**
  2168. * Sets the given "parameter" matrix
  2169. * @param shaderMaterial: the shader material
  2170. * @param uniform: the name of the shader's uniform
  2171. * @param value: the value of the uniform
  2172. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  2173. */
  2174. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  2175. switch (type) {
  2176. case glTFLoaderInterfaces_1.EParameterType.FLOAT:
  2177. shaderMaterial.setFloat(uniform, value);
  2178. return true;
  2179. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC2:
  2180. shaderMaterial.setVector2(uniform, babylonjs_1.Vector2.FromArray(value));
  2181. return true;
  2182. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC3:
  2183. shaderMaterial.setVector3(uniform, babylonjs_1.Vector3.FromArray(value));
  2184. return true;
  2185. case glTFLoaderInterfaces_1.EParameterType.FLOAT_VEC4:
  2186. shaderMaterial.setVector4(uniform, babylonjs_1.Vector4.FromArray(value));
  2187. return true;
  2188. default: return false;
  2189. }
  2190. };
  2191. /**
  2192. * Returns the wrap mode of the texture
  2193. * @param mode: the mode value
  2194. */
  2195. GLTFUtils.GetWrapMode = function (mode) {
  2196. switch (mode) {
  2197. case glTFLoaderInterfaces_1.ETextureWrapMode.CLAMP_TO_EDGE: return babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  2198. case glTFLoaderInterfaces_1.ETextureWrapMode.MIRRORED_REPEAT: return babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  2199. case glTFLoaderInterfaces_1.ETextureWrapMode.REPEAT: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  2200. default: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  2201. }
  2202. };
  2203. /**
  2204. * Returns the byte stride giving an accessor
  2205. * @param accessor: the GLTF accessor objet
  2206. */
  2207. GLTFUtils.GetByteStrideFromType = function (accessor) {
  2208. // Needs this function since "byteStride" isn't requiered in glTF format
  2209. var type = accessor.type;
  2210. switch (type) {
  2211. case "VEC2": return 2;
  2212. case "VEC3": return 3;
  2213. case "VEC4": return 4;
  2214. case "MAT2": return 4;
  2215. case "MAT3": return 9;
  2216. case "MAT4": return 16;
  2217. default: return 1;
  2218. }
  2219. };
  2220. /**
  2221. * Returns the texture filter mode giving a mode value
  2222. * @param mode: the filter mode value
  2223. */
  2224. GLTFUtils.GetTextureFilterMode = function (mode) {
  2225. switch (mode) {
  2226. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR:
  2227. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  2228. case glTFLoaderInterfaces_1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return babylonjs_1.Texture.TRILINEAR_SAMPLINGMODE;
  2229. case glTFLoaderInterfaces_1.ETextureFilterType.NEAREST:
  2230. case glTFLoaderInterfaces_1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return babylonjs_1.Texture.NEAREST_SAMPLINGMODE;
  2231. default: return babylonjs_1.Texture.BILINEAR_SAMPLINGMODE;
  2232. }
  2233. };
  2234. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  2235. var byteOffset = bufferView.byteOffset + byteOffset;
  2236. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  2237. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  2238. throw new Error("Buffer access is out of range");
  2239. }
  2240. var buffer = loadedBufferView.buffer;
  2241. byteOffset += loadedBufferView.byteOffset;
  2242. switch (componentType) {
  2243. case glTFLoaderInterfaces_1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  2244. case glTFLoaderInterfaces_1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  2245. case glTFLoaderInterfaces_1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  2246. case glTFLoaderInterfaces_1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  2247. default: return new Float32Array(buffer, byteOffset, byteLength);
  2248. }
  2249. };
  2250. /**
  2251. * Returns a buffer from its accessor
  2252. * @param gltfRuntime: the GLTF runtime
  2253. * @param accessor: the GLTF accessor
  2254. */
  2255. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  2256. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  2257. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  2258. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  2259. };
  2260. /**
  2261. * Decodes a buffer view into a string
  2262. * @param view: the buffer view
  2263. */
  2264. GLTFUtils.DecodeBufferToText = function (view) {
  2265. var result = "";
  2266. var length = view.byteLength;
  2267. for (var i = 0; i < length; ++i) {
  2268. result += String.fromCharCode(view[i]);
  2269. }
  2270. return result;
  2271. };
  2272. /**
  2273. * Returns the default material of gltf. Related to
  2274. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  2275. * @param scene: the Babylon.js scene
  2276. */
  2277. GLTFUtils.GetDefaultMaterial = function (scene) {
  2278. if (!GLTFUtils._DefaultMaterial) {
  2279. babylonjs_1.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  2280. "precision highp float;",
  2281. "",
  2282. "uniform mat4 worldView;",
  2283. "uniform mat4 projection;",
  2284. "",
  2285. "attribute vec3 position;",
  2286. "",
  2287. "void main(void)",
  2288. "{",
  2289. " gl_Position = projection * worldView * vec4(position, 1.0);",
  2290. "}"
  2291. ].join("\n");
  2292. babylonjs_1.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  2293. "precision highp float;",
  2294. "",
  2295. "uniform vec4 u_emission;",
  2296. "",
  2297. "void main(void)",
  2298. "{",
  2299. " gl_FragColor = u_emission;",
  2300. "}"
  2301. ].join("\n");
  2302. var shaderPath = {
  2303. vertex: "GLTFDefaultMaterial",
  2304. fragment: "GLTFDefaultMaterial"
  2305. };
  2306. var options = {
  2307. attributes: ["position"],
  2308. uniforms: ["worldView", "projection", "u_emission"],
  2309. samplers: new Array(),
  2310. needAlphaBlending: false
  2311. };
  2312. GLTFUtils._DefaultMaterial = new babylonjs_1.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  2313. GLTFUtils._DefaultMaterial.setColor4("u_emission", new babylonjs_1.Color4(0.5, 0.5, 0.5, 1.0));
  2314. }
  2315. return GLTFUtils._DefaultMaterial;
  2316. };
  2317. // The GLTF default material
  2318. GLTFUtils._DefaultMaterial = null;
  2319. return GLTFUtils;
  2320. }());
  2321. exports.GLTFUtils = GLTFUtils;
  2322. /***/ }),
  2323. /***/ "./src/glTF/1.0/glTFMaterialsCommonExtension.ts":
  2324. /*!******************************************************!*\
  2325. !*** ./src/glTF/1.0/glTFMaterialsCommonExtension.ts ***!
  2326. \******************************************************/
  2327. /*! no static exports found */
  2328. /***/ (function(module, exports, __webpack_require__) {
  2329. "use strict";
  2330. var __extends = (this && this.__extends) || (function () {
  2331. var extendStatics = function (d, b) {
  2332. extendStatics = Object.setPrototypeOf ||
  2333. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2334. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2335. return extendStatics(d, b);
  2336. }
  2337. return function (d, b) {
  2338. extendStatics(d, b);
  2339. function __() { this.constructor = d; }
  2340. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2341. };
  2342. })();
  2343. Object.defineProperty(exports, "__esModule", { value: true });
  2344. var _1 = __webpack_require__(/*! . */ "./src/glTF/1.0/index.ts");
  2345. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2346. var glTFLoader_1 = __webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts");
  2347. /** @hidden */
  2348. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  2349. __extends(GLTFMaterialsCommonExtension, _super);
  2350. function GLTFMaterialsCommonExtension() {
  2351. return _super.call(this, "KHR_materials_common") || this;
  2352. }
  2353. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2354. if (!gltfRuntime.extensions) {
  2355. return false;
  2356. }
  2357. var extension = gltfRuntime.extensions[this.name];
  2358. if (!extension) {
  2359. return false;
  2360. }
  2361. // Create lights
  2362. var lights = extension.lights;
  2363. if (lights) {
  2364. for (var thing in lights) {
  2365. var light = lights[thing];
  2366. switch (light.type) {
  2367. case "ambient":
  2368. var ambientLight = new babylonjs_1.HemisphericLight(light.name, new babylonjs_1.Vector3(0, 1, 0), gltfRuntime.scene);
  2369. var ambient = light.ambient;
  2370. if (ambient) {
  2371. ambientLight.diffuse = babylonjs_1.Color3.FromArray(ambient.color || [1, 1, 1]);
  2372. }
  2373. break;
  2374. case "point":
  2375. var pointLight = new babylonjs_1.PointLight(light.name, new babylonjs_1.Vector3(10, 10, 10), gltfRuntime.scene);
  2376. var point = light.point;
  2377. if (point) {
  2378. pointLight.diffuse = babylonjs_1.Color3.FromArray(point.color || [1, 1, 1]);
  2379. }
  2380. break;
  2381. case "directional":
  2382. var dirLight = new babylonjs_1.DirectionalLight(light.name, new babylonjs_1.Vector3(0, -1, 0), gltfRuntime.scene);
  2383. var directional = light.directional;
  2384. if (directional) {
  2385. dirLight.diffuse = babylonjs_1.Color3.FromArray(directional.color || [1, 1, 1]);
  2386. }
  2387. break;
  2388. case "spot":
  2389. var spot = light.spot;
  2390. if (spot) {
  2391. var spotLight = new babylonjs_1.SpotLight(light.name, new babylonjs_1.Vector3(0, 10, 0), new babylonjs_1.Vector3(0, -1, 0), spot.fallOffAngle || Math.PI, spot.fallOffExponent || 0.0, gltfRuntime.scene);
  2392. spotLight.diffuse = babylonjs_1.Color3.FromArray(spot.color || [1, 1, 1]);
  2393. }
  2394. break;
  2395. default:
  2396. babylonjs_1.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2397. break;
  2398. }
  2399. }
  2400. }
  2401. return false;
  2402. };
  2403. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2404. var material = gltfRuntime.materials[id];
  2405. if (!material || !material.extensions) {
  2406. return false;
  2407. }
  2408. var extension = material.extensions[this.name];
  2409. if (!extension) {
  2410. return false;
  2411. }
  2412. var standardMaterial = new babylonjs_1.StandardMaterial(id, gltfRuntime.scene);
  2413. standardMaterial.sideOrientation = babylonjs_1.Material.CounterClockWiseSideOrientation;
  2414. if (extension.technique === "CONSTANT") {
  2415. standardMaterial.disableLighting = true;
  2416. }
  2417. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2418. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2419. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2420. // Ambient
  2421. if (typeof extension.values.ambient === "string") {
  2422. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2423. }
  2424. else {
  2425. standardMaterial.ambientColor = babylonjs_1.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2426. }
  2427. // Diffuse
  2428. if (typeof extension.values.diffuse === "string") {
  2429. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2430. }
  2431. else {
  2432. standardMaterial.diffuseColor = babylonjs_1.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2433. }
  2434. // Emission
  2435. if (typeof extension.values.emission === "string") {
  2436. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2437. }
  2438. else {
  2439. standardMaterial.emissiveColor = babylonjs_1.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2440. }
  2441. // Specular
  2442. if (typeof extension.values.specular === "string") {
  2443. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2444. }
  2445. else {
  2446. standardMaterial.specularColor = babylonjs_1.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2447. }
  2448. return true;
  2449. };
  2450. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2451. // Create buffer from texture url
  2452. _1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2453. // Create texture from buffer
  2454. _1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2455. }, onError);
  2456. };
  2457. return GLTFMaterialsCommonExtension;
  2458. }(_1.GLTFLoaderExtension));
  2459. exports.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2460. glTFLoader_1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2461. /***/ }),
  2462. /***/ "./src/glTF/1.0/index.ts":
  2463. /*!*******************************!*\
  2464. !*** ./src/glTF/1.0/index.ts ***!
  2465. \*******************************/
  2466. /*! no static exports found */
  2467. /***/ (function(module, exports, __webpack_require__) {
  2468. "use strict";
  2469. function __export(m) {
  2470. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  2471. }
  2472. Object.defineProperty(exports, "__esModule", { value: true });
  2473. __export(__webpack_require__(/*! ./glTFBinaryExtension */ "./src/glTF/1.0/glTFBinaryExtension.ts"));
  2474. __export(__webpack_require__(/*! ./glTFLoader */ "./src/glTF/1.0/glTFLoader.ts"));
  2475. __export(__webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/1.0/glTFLoaderExtension.ts"));
  2476. __export(__webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/1.0/glTFLoaderInterfaces.ts"));
  2477. __export(__webpack_require__(/*! ./glTFLoaderUtils */ "./src/glTF/1.0/glTFLoaderUtils.ts"));
  2478. __export(__webpack_require__(/*! ./glTFMaterialsCommonExtension */ "./src/glTF/1.0/glTFMaterialsCommonExtension.ts"));
  2479. /***/ }),
  2480. /***/ "./src/glTF/2.0/Extensions/EXT_lights_image_based.ts":
  2481. /*!***********************************************************!*\
  2482. !*** ./src/glTF/2.0/Extensions/EXT_lights_image_based.ts ***!
  2483. \***********************************************************/
  2484. /*! no static exports found */
  2485. /***/ (function(module, exports, __webpack_require__) {
  2486. "use strict";
  2487. Object.defineProperty(exports, "__esModule", { value: true });
  2488. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2489. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  2490. var NAME = "EXT_lights_image_based";
  2491. /**
  2492. * [Specification](https://github.com/KhronosGroup/glTF/blob/eb3e32332042e04691a5f35103f8c261e50d8f1e/extensions/2.0/Khronos/EXT_lights_image_based/README.md) (Experimental)
  2493. */
  2494. var EXT_lights_image_based = /** @class */ (function () {
  2495. /** @hidden */
  2496. function EXT_lights_image_based(loader) {
  2497. /** The name of this extension. */
  2498. this.name = NAME;
  2499. /** Defines whether this extension is enabled. */
  2500. this.enabled = true;
  2501. this._loader = loader;
  2502. }
  2503. /** @hidden */
  2504. EXT_lights_image_based.prototype.dispose = function () {
  2505. delete this._loader;
  2506. delete this._lights;
  2507. };
  2508. /** @hidden */
  2509. EXT_lights_image_based.prototype.onLoading = function () {
  2510. var extensions = this._loader.gltf.extensions;
  2511. if (extensions && extensions[this.name]) {
  2512. var extension = extensions[this.name];
  2513. this._lights = extension.lights;
  2514. }
  2515. };
  2516. /** @hidden */
  2517. EXT_lights_image_based.prototype.loadSceneAsync = function (context, scene) {
  2518. var _this = this;
  2519. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  2520. var promises = new Array();
  2521. promises.push(_this._loader.loadSceneAsync(context, scene));
  2522. _this._loader.logOpen("" + extensionContext);
  2523. var light = glTFLoader_1.ArrayItem.Get(extensionContext + "/light", _this._lights, extension.light);
  2524. promises.push(_this._loadLightAsync("#/extensions/" + _this.name + "/lights/" + extension.light, light).then(function (texture) {
  2525. _this._loader.babylonScene.environmentTexture = texture;
  2526. }));
  2527. _this._loader.logClose();
  2528. return Promise.all(promises).then(function () { });
  2529. });
  2530. };
  2531. EXT_lights_image_based.prototype._loadLightAsync = function (context, light) {
  2532. var _this = this;
  2533. if (!light._loaded) {
  2534. var promises = new Array();
  2535. this._loader.logOpen("" + context);
  2536. var imageData_1 = new Array(light.specularImages.length);
  2537. var _loop_1 = function (mipmap) {
  2538. var faces = light.specularImages[mipmap];
  2539. imageData_1[mipmap] = new Array(faces.length);
  2540. var _loop_2 = function (face) {
  2541. var specularImageContext = context + "/specularImages/" + mipmap + "/" + face;
  2542. this_1._loader.logOpen("" + specularImageContext);
  2543. var index = faces[face];
  2544. var image = glTFLoader_1.ArrayItem.Get(specularImageContext, this_1._loader.gltf.images, index);
  2545. promises.push(this_1._loader.loadImageAsync("#/images/" + index, image).then(function (data) {
  2546. imageData_1[mipmap][face] = data;
  2547. }));
  2548. this_1._loader.logClose();
  2549. };
  2550. for (var face = 0; face < faces.length; face++) {
  2551. _loop_2(face);
  2552. }
  2553. };
  2554. var this_1 = this;
  2555. for (var mipmap = 0; mipmap < light.specularImages.length; mipmap++) {
  2556. _loop_1(mipmap);
  2557. }
  2558. this._loader.logClose();
  2559. light._loaded = Promise.all(promises).then(function () {
  2560. var babylonTexture = new babylonjs_1.RawCubeTexture(_this._loader.babylonScene, null, light.specularImageSize);
  2561. light._babylonTexture = babylonTexture;
  2562. if (light.intensity != undefined) {
  2563. babylonTexture.level = light.intensity;
  2564. }
  2565. if (light.rotation) {
  2566. var rotation = babylonjs_1.Quaternion.FromArray(light.rotation);
  2567. // Invert the rotation so that positive rotation is counter-clockwise.
  2568. if (!_this._loader.babylonScene.useRightHandedSystem) {
  2569. rotation = babylonjs_1.Quaternion.Inverse(rotation);
  2570. }
  2571. babylonjs_1.Matrix.FromQuaternionToRef(rotation, babylonTexture.getReflectionTextureMatrix());
  2572. }
  2573. var sphericalHarmonics = babylonjs_1.SphericalHarmonics.FromArray(light.irradianceCoefficients);
  2574. sphericalHarmonics.scale(light.intensity);
  2575. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  2576. var sphericalPolynomial = babylonjs_1.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  2577. // Compute the lod generation scale to fit exactly to the number of levels available.
  2578. var lodGenerationScale = (imageData_1.length - 1) / babylonjs_1.Scalar.Log2(light.specularImageSize);
  2579. return babylonTexture.updateRGBDAsync(imageData_1, sphericalPolynomial, lodGenerationScale);
  2580. });
  2581. }
  2582. return light._loaded.then(function () {
  2583. return light._babylonTexture;
  2584. });
  2585. };
  2586. return EXT_lights_image_based;
  2587. }());
  2588. exports.EXT_lights_image_based = EXT_lights_image_based;
  2589. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new EXT_lights_image_based(loader); });
  2590. /***/ }),
  2591. /***/ "./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts":
  2592. /*!***************************************************************!*\
  2593. !*** ./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts ***!
  2594. \***************************************************************/
  2595. /*! no static exports found */
  2596. /***/ (function(module, exports, __webpack_require__) {
  2597. "use strict";
  2598. Object.defineProperty(exports, "__esModule", { value: true });
  2599. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2600. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  2601. var NAME = "KHR_draco_mesh_compression";
  2602. /**
  2603. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  2604. */
  2605. var KHR_draco_mesh_compression = /** @class */ (function () {
  2606. /** @hidden */
  2607. function KHR_draco_mesh_compression(loader) {
  2608. /** The name of this extension. */
  2609. this.name = NAME;
  2610. /** Defines whether this extension is enabled. */
  2611. this.enabled = babylonjs_1.DracoCompression.DecoderAvailable;
  2612. this._loader = loader;
  2613. }
  2614. /** @hidden */
  2615. KHR_draco_mesh_compression.prototype.dispose = function () {
  2616. if (this._dracoCompression) {
  2617. this._dracoCompression.dispose();
  2618. delete this._dracoCompression;
  2619. }
  2620. delete this._loader;
  2621. };
  2622. /** @hidden */
  2623. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  2624. var _this = this;
  2625. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, primitive, this.name, function (extensionContext, extension) {
  2626. if (primitive.mode != undefined) {
  2627. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  2628. primitive.mode !== 4 /* TRIANGLES */) {
  2629. throw new Error(context + ": Unsupported mode " + primitive.mode);
  2630. }
  2631. // TODO: handle triangle strips
  2632. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  2633. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  2634. }
  2635. }
  2636. var attributes = {};
  2637. var loadAttribute = function (name, kind) {
  2638. var uniqueId = extension.attributes[name];
  2639. if (uniqueId == undefined) {
  2640. return;
  2641. }
  2642. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  2643. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  2644. babylonMesh._delayInfo.push(kind);
  2645. }
  2646. attributes[kind] = uniqueId;
  2647. };
  2648. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind);
  2649. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind);
  2650. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind);
  2651. loadAttribute("TEXCOORD_0", babylonjs_1.VertexBuffer.UVKind);
  2652. loadAttribute("TEXCOORD_1", babylonjs_1.VertexBuffer.UV2Kind);
  2653. loadAttribute("JOINTS_0", babylonjs_1.VertexBuffer.MatricesIndicesKind);
  2654. loadAttribute("WEIGHTS_0", babylonjs_1.VertexBuffer.MatricesWeightsKind);
  2655. loadAttribute("COLOR_0", babylonjs_1.VertexBuffer.ColorKind);
  2656. var bufferView = glTFLoader_1.ArrayItem.Get(extensionContext, _this._loader.gltf.bufferViews, extension.bufferView);
  2657. if (!bufferView._dracoBabylonGeometry) {
  2658. bufferView._dracoBabylonGeometry = _this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  2659. if (!_this._dracoCompression) {
  2660. _this._dracoCompression = new babylonjs_1.DracoCompression();
  2661. }
  2662. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  2663. var babylonGeometry = new babylonjs_1.Geometry(babylonMesh.name, _this._loader.babylonScene);
  2664. babylonVertexData.applyToGeometry(babylonGeometry);
  2665. return babylonGeometry;
  2666. }).catch(function (error) {
  2667. throw new Error(context + ": " + error.message);
  2668. });
  2669. });
  2670. }
  2671. return bufferView._dracoBabylonGeometry;
  2672. });
  2673. };
  2674. return KHR_draco_mesh_compression;
  2675. }());
  2676. exports.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  2677. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  2678. /***/ }),
  2679. /***/ "./src/glTF/2.0/Extensions/KHR_lights_punctual.ts":
  2680. /*!********************************************************!*\
  2681. !*** ./src/glTF/2.0/Extensions/KHR_lights_punctual.ts ***!
  2682. \********************************************************/
  2683. /*! no static exports found */
  2684. /***/ (function(module, exports, __webpack_require__) {
  2685. "use strict";
  2686. Object.defineProperty(exports, "__esModule", { value: true });
  2687. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2688. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  2689. var NAME = "KHR_lights_punctual";
  2690. var LightType;
  2691. (function (LightType) {
  2692. LightType["DIRECTIONAL"] = "directional";
  2693. LightType["POINT"] = "point";
  2694. LightType["SPOT"] = "spot";
  2695. })(LightType || (LightType = {}));
  2696. /**
  2697. * [Specification](https://github.com/KhronosGroup/glTF/blob/1048d162a44dbcb05aefc1874bfd423cf60135a6/extensions/2.0/Khronos/KHR_lights_punctual/README.md) (Experimental)
  2698. */
  2699. var KHR_lights = /** @class */ (function () {
  2700. /** @hidden */
  2701. function KHR_lights(loader) {
  2702. /** The name of this extension. */
  2703. this.name = NAME;
  2704. /** Defines whether this extension is enabled. */
  2705. this.enabled = true;
  2706. this._loader = loader;
  2707. }
  2708. /** @hidden */
  2709. KHR_lights.prototype.dispose = function () {
  2710. delete this._loader;
  2711. delete this._lights;
  2712. };
  2713. /** @hidden */
  2714. KHR_lights.prototype.onLoading = function () {
  2715. var extensions = this._loader.gltf.extensions;
  2716. if (extensions && extensions[this.name]) {
  2717. var extension = extensions[this.name];
  2718. this._lights = extension.lights;
  2719. }
  2720. };
  2721. /** @hidden */
  2722. KHR_lights.prototype.loadNodeAsync = function (context, node, assign) {
  2723. var _this = this;
  2724. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  2725. return _this._loader.loadNodeAsync(context, node, function (babylonMesh) {
  2726. var babylonLight;
  2727. var light = glTFLoader_1.ArrayItem.Get(extensionContext, _this._lights, extension.light);
  2728. var name = light.name || babylonMesh.name;
  2729. switch (light.type) {
  2730. case LightType.DIRECTIONAL: {
  2731. babylonLight = new babylonjs_1.DirectionalLight(name, babylonjs_1.Vector3.Backward(), _this._loader.babylonScene);
  2732. break;
  2733. }
  2734. case LightType.POINT: {
  2735. babylonLight = new babylonjs_1.PointLight(name, babylonjs_1.Vector3.Zero(), _this._loader.babylonScene);
  2736. break;
  2737. }
  2738. case LightType.SPOT: {
  2739. var babylonSpotLight = new babylonjs_1.SpotLight(name, babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Backward(), 0, 1, _this._loader.babylonScene);
  2740. babylonSpotLight.angle = ((light.spot && light.spot.outerConeAngle) || Math.PI / 4) * 2;
  2741. babylonSpotLight.innerAngle = ((light.spot && light.spot.innerConeAngle) || 0) * 2;
  2742. babylonLight = babylonSpotLight;
  2743. break;
  2744. }
  2745. default: {
  2746. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  2747. }
  2748. }
  2749. babylonLight.falloffType = babylonjs_1.Light.FALLOFF_GLTF;
  2750. babylonLight.diffuse = light.color ? babylonjs_1.Color3.FromArray(light.color) : babylonjs_1.Color3.White();
  2751. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  2752. babylonLight.range = light.range == undefined ? Number.MAX_VALUE : light.range;
  2753. babylonLight.parent = babylonMesh;
  2754. assign(babylonMesh);
  2755. });
  2756. });
  2757. };
  2758. return KHR_lights;
  2759. }());
  2760. exports.KHR_lights = KHR_lights;
  2761. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_lights(loader); });
  2762. /***/ }),
  2763. /***/ "./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts":
  2764. /*!************************************************************************!*\
  2765. !*** ./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts ***!
  2766. \************************************************************************/
  2767. /*! no static exports found */
  2768. /***/ (function(module, exports, __webpack_require__) {
  2769. "use strict";
  2770. Object.defineProperty(exports, "__esModule", { value: true });
  2771. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2772. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  2773. var NAME = "KHR_materials_pbrSpecularGlossiness";
  2774. /**
  2775. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  2776. */
  2777. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function () {
  2778. /** @hidden */
  2779. function KHR_materials_pbrSpecularGlossiness(loader) {
  2780. /** The name of this extension. */
  2781. this.name = NAME;
  2782. /** Defines whether this extension is enabled. */
  2783. this.enabled = true;
  2784. this._loader = loader;
  2785. }
  2786. /** @hidden */
  2787. KHR_materials_pbrSpecularGlossiness.prototype.dispose = function () {
  2788. delete this._loader;
  2789. };
  2790. /** @hidden */
  2791. KHR_materials_pbrSpecularGlossiness.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2792. var _this = this;
  2793. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  2794. var promises = new Array();
  2795. promises.push(_this._loader.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  2796. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  2797. _this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  2798. return Promise.all(promises).then(function () { });
  2799. });
  2800. };
  2801. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  2802. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  2803. throw new Error(context + ": Material type not supported");
  2804. }
  2805. var promises = new Array();
  2806. babylonMaterial.metallic = null;
  2807. babylonMaterial.roughness = null;
  2808. if (properties.diffuseFactor) {
  2809. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.diffuseFactor);
  2810. babylonMaterial.alpha = properties.diffuseFactor[3];
  2811. }
  2812. else {
  2813. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  2814. }
  2815. babylonMaterial.reflectivityColor = properties.specularFactor ? babylonjs_1.Color3.FromArray(properties.specularFactor) : babylonjs_1.Color3.White();
  2816. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  2817. if (properties.diffuseTexture) {
  2818. promises.push(this._loader.loadTextureInfoAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  2819. babylonMaterial.albedoTexture = texture;
  2820. return Promise.resolve();
  2821. }));
  2822. }
  2823. if (properties.specularGlossinessTexture) {
  2824. promises.push(this._loader.loadTextureInfoAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  2825. babylonMaterial.reflectivityTexture = texture;
  2826. return Promise.resolve();
  2827. }));
  2828. babylonMaterial.reflectivityTexture.hasAlpha = true;
  2829. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  2830. }
  2831. return Promise.all(promises).then(function () { });
  2832. };
  2833. return KHR_materials_pbrSpecularGlossiness;
  2834. }());
  2835. exports.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  2836. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  2837. /***/ }),
  2838. /***/ "./src/glTF/2.0/Extensions/KHR_materials_unlit.ts":
  2839. /*!********************************************************!*\
  2840. !*** ./src/glTF/2.0/Extensions/KHR_materials_unlit.ts ***!
  2841. \********************************************************/
  2842. /*! no static exports found */
  2843. /***/ (function(module, exports, __webpack_require__) {
  2844. "use strict";
  2845. Object.defineProperty(exports, "__esModule", { value: true });
  2846. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2847. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  2848. var NAME = "KHR_materials_unlit";
  2849. /**
  2850. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  2851. */
  2852. var KHR_materials_unlit = /** @class */ (function () {
  2853. /** @hidden */
  2854. function KHR_materials_unlit(loader) {
  2855. /** The name of this extension. */
  2856. this.name = NAME;
  2857. /** Defines whether this extension is enabled. */
  2858. this.enabled = true;
  2859. this._loader = loader;
  2860. }
  2861. /** @hidden */
  2862. KHR_materials_unlit.prototype.dispose = function () {
  2863. delete this._loader;
  2864. };
  2865. /** @hidden */
  2866. KHR_materials_unlit.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  2867. var _this = this;
  2868. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, material, this.name, function () {
  2869. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  2870. });
  2871. };
  2872. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  2873. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  2874. throw new Error(context + ": Material type not supported");
  2875. }
  2876. var promises = new Array();
  2877. babylonMaterial.unlit = true;
  2878. var properties = material.pbrMetallicRoughness;
  2879. if (properties) {
  2880. if (properties.baseColorFactor) {
  2881. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.baseColorFactor);
  2882. babylonMaterial.alpha = properties.baseColorFactor[3];
  2883. }
  2884. else {
  2885. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  2886. }
  2887. if (properties.baseColorTexture) {
  2888. promises.push(this._loader.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  2889. babylonMaterial.albedoTexture = texture;
  2890. return Promise.resolve();
  2891. }));
  2892. }
  2893. }
  2894. if (material.doubleSided) {
  2895. babylonMaterial.backFaceCulling = false;
  2896. babylonMaterial.twoSidedLighting = true;
  2897. }
  2898. this._loader.loadMaterialAlphaProperties(context, material, babylonMaterial);
  2899. return Promise.all(promises).then(function () { });
  2900. };
  2901. return KHR_materials_unlit;
  2902. }());
  2903. exports.KHR_materials_unlit = KHR_materials_unlit;
  2904. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  2905. /***/ }),
  2906. /***/ "./src/glTF/2.0/Extensions/KHR_texture_transform.ts":
  2907. /*!**********************************************************!*\
  2908. !*** ./src/glTF/2.0/Extensions/KHR_texture_transform.ts ***!
  2909. \**********************************************************/
  2910. /*! no static exports found */
  2911. /***/ (function(module, exports, __webpack_require__) {
  2912. "use strict";
  2913. Object.defineProperty(exports, "__esModule", { value: true });
  2914. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2915. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  2916. var NAME = "KHR_texture_transform";
  2917. /**
  2918. * [Specification](https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_texture_transform/README.md)
  2919. */
  2920. var KHR_texture_transform = /** @class */ (function () {
  2921. /** @hidden */
  2922. function KHR_texture_transform(loader) {
  2923. /** The name of this extension. */
  2924. this.name = NAME;
  2925. /** Defines whether this extension is enabled. */
  2926. this.enabled = true;
  2927. this._loader = loader;
  2928. }
  2929. /** @hidden */
  2930. KHR_texture_transform.prototype.dispose = function () {
  2931. delete this._loader;
  2932. };
  2933. /** @hidden */
  2934. KHR_texture_transform.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  2935. var _this = this;
  2936. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, textureInfo, this.name, function (extensionContext, extension) {
  2937. return _this._loader.loadTextureInfoAsync(context, textureInfo, function (babylonTexture) {
  2938. if (!(babylonTexture instanceof babylonjs_1.Texture)) {
  2939. throw new Error(extensionContext + ": Texture type not supported");
  2940. }
  2941. if (extension.offset) {
  2942. babylonTexture.uOffset = extension.offset[0];
  2943. babylonTexture.vOffset = extension.offset[1];
  2944. }
  2945. // Always rotate around the origin.
  2946. babylonTexture.uRotationCenter = 0;
  2947. babylonTexture.vRotationCenter = 0;
  2948. if (extension.rotation) {
  2949. babylonTexture.wAng = -extension.rotation;
  2950. }
  2951. if (extension.scale) {
  2952. babylonTexture.uScale = extension.scale[0];
  2953. babylonTexture.vScale = extension.scale[1];
  2954. }
  2955. if (extension.texCoord != undefined) {
  2956. babylonTexture.coordinatesIndex = extension.texCoord;
  2957. }
  2958. assign(babylonTexture);
  2959. });
  2960. });
  2961. };
  2962. return KHR_texture_transform;
  2963. }());
  2964. exports.KHR_texture_transform = KHR_texture_transform;
  2965. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new KHR_texture_transform(loader); });
  2966. /***/ }),
  2967. /***/ "./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts":
  2968. /*!*******************************************************!*\
  2969. !*** ./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts ***!
  2970. \*******************************************************/
  2971. /*! no static exports found */
  2972. /***/ (function(module, exports, __webpack_require__) {
  2973. "use strict";
  2974. Object.defineProperty(exports, "__esModule", { value: true });
  2975. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  2976. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  2977. var NAME = "MSFT_audio_emitter";
  2978. /**
  2979. * [Specification](https://github.com/najadojo/glTF/tree/MSFT_audio_emitter/extensions/2.0/Vendor/MSFT_audio_emitter)
  2980. */
  2981. var MSFT_audio_emitter = /** @class */ (function () {
  2982. /** @hidden */
  2983. function MSFT_audio_emitter(loader) {
  2984. /** The name of this extension. */
  2985. this.name = NAME;
  2986. /** Defines whether this extension is enabled. */
  2987. this.enabled = true;
  2988. this._loader = loader;
  2989. }
  2990. /** @hidden */
  2991. MSFT_audio_emitter.prototype.dispose = function () {
  2992. delete this._loader;
  2993. delete this._clips;
  2994. delete this._emitters;
  2995. };
  2996. /** @hidden */
  2997. MSFT_audio_emitter.prototype.onLoading = function () {
  2998. var extensions = this._loader.gltf.extensions;
  2999. if (extensions && extensions[this.name]) {
  3000. var extension = extensions[this.name];
  3001. this._clips = extension.clips;
  3002. this._emitters = extension.emitters;
  3003. glTFLoader_1.ArrayItem.Assign(this._clips);
  3004. glTFLoader_1.ArrayItem.Assign(this._emitters);
  3005. }
  3006. };
  3007. /** @hidden */
  3008. MSFT_audio_emitter.prototype.loadSceneAsync = function (context, scene) {
  3009. var _this = this;
  3010. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, scene, this.name, function (extensionContext, extension) {
  3011. var promises = new Array();
  3012. promises.push(_this._loader.loadSceneAsync(context, scene));
  3013. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  3014. var emitterIndex = _a[_i];
  3015. var emitter = glTFLoader_1.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  3016. if (emitter.refDistance != undefined || emitter.maxDistance != undefined || emitter.rolloffFactor != undefined ||
  3017. emitter.distanceModel != undefined || emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  3018. throw new Error(extensionContext + ": Direction or Distance properties are not allowed on emitters attached to a scene");
  3019. }
  3020. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter));
  3021. }
  3022. return Promise.all(promises).then(function () { });
  3023. });
  3024. };
  3025. /** @hidden */
  3026. MSFT_audio_emitter.prototype.loadNodeAsync = function (context, node, assign) {
  3027. var _this = this;
  3028. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  3029. var promises = new Array();
  3030. return _this._loader.loadNodeAsync(extensionContext, node, function (babylonMesh) {
  3031. var _loop_1 = function (emitterIndex) {
  3032. var emitter = glTFLoader_1.ArrayItem.Get(extensionContext + "/emitters", _this._emitters, emitterIndex);
  3033. promises.push(_this._loadEmitterAsync(extensionContext + "/emitters/" + emitter.index, emitter).then(function () {
  3034. for (var _i = 0, _a = emitter._babylonSounds; _i < _a.length; _i++) {
  3035. var sound = _a[_i];
  3036. sound.attachToMesh(babylonMesh);
  3037. if (emitter.innerAngle != undefined || emitter.outerAngle != undefined) {
  3038. sound.setLocalDirectionToMesh(babylonjs_1.Vector3.Forward());
  3039. sound.setDirectionalCone(2 * babylonjs_1.Tools.ToDegrees(emitter.innerAngle == undefined ? Math.PI : emitter.innerAngle), 2 * babylonjs_1.Tools.ToDegrees(emitter.outerAngle == undefined ? Math.PI : emitter.outerAngle), 0);
  3040. }
  3041. }
  3042. }));
  3043. };
  3044. for (var _i = 0, _a = extension.emitters; _i < _a.length; _i++) {
  3045. var emitterIndex = _a[_i];
  3046. _loop_1(emitterIndex);
  3047. }
  3048. assign(babylonMesh);
  3049. }).then(function (babylonMesh) {
  3050. return Promise.all(promises).then(function () {
  3051. return babylonMesh;
  3052. });
  3053. });
  3054. });
  3055. };
  3056. /** @hidden */
  3057. MSFT_audio_emitter.prototype.loadAnimationAsync = function (context, animation) {
  3058. var _this = this;
  3059. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, animation, this.name, function (extensionContext, extension) {
  3060. return _this._loader.loadAnimationAsync(context, animation).then(function (babylonAnimationGroup) {
  3061. var promises = new Array();
  3062. glTFLoader_1.ArrayItem.Assign(extension.events);
  3063. for (var _i = 0, _a = extension.events; _i < _a.length; _i++) {
  3064. var event_1 = _a[_i];
  3065. promises.push(_this._loadAnimationEventAsync(extensionContext + "/events/" + event_1.index, context, animation, event_1, babylonAnimationGroup));
  3066. }
  3067. return Promise.all(promises).then(function () {
  3068. return babylonAnimationGroup;
  3069. });
  3070. });
  3071. });
  3072. };
  3073. MSFT_audio_emitter.prototype._loadClipAsync = function (context, clip) {
  3074. if (clip._objectURL) {
  3075. return clip._objectURL;
  3076. }
  3077. var promise;
  3078. if (clip.uri) {
  3079. promise = this._loader.loadUriAsync(context, clip.uri);
  3080. }
  3081. else {
  3082. var bufferView = glTFLoader_1.ArrayItem.Get(context + "/bufferView", this._loader.gltf.bufferViews, clip.bufferView);
  3083. promise = this._loader.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  3084. }
  3085. clip._objectURL = promise.then(function (data) {
  3086. return URL.createObjectURL(new Blob([data], { type: clip.mimeType }));
  3087. });
  3088. return clip._objectURL;
  3089. };
  3090. MSFT_audio_emitter.prototype._loadEmitterAsync = function (context, emitter) {
  3091. var _this = this;
  3092. emitter._babylonSounds = emitter._babylonSounds || [];
  3093. if (!emitter._babylonData) {
  3094. var clipPromises = new Array();
  3095. var name_1 = emitter.name || "emitter" + emitter.index;
  3096. var options_1 = {
  3097. loop: false,
  3098. autoplay: false,
  3099. volume: emitter.volume == undefined ? 1 : emitter.volume,
  3100. };
  3101. var _loop_2 = function (i) {
  3102. var clipContext = "#/extensions/" + this_1.name + "/clips";
  3103. var clip = glTFLoader_1.ArrayItem.Get(clipContext, this_1._clips, emitter.clips[i].clip);
  3104. clipPromises.push(this_1._loadClipAsync(clipContext + "/" + emitter.clips[i].clip, clip).then(function (objectURL) {
  3105. var sound = emitter._babylonSounds[i] = new babylonjs_1.Sound(name_1, objectURL, _this._loader.babylonScene, null, options_1);
  3106. sound.refDistance = emitter.refDistance || 1;
  3107. sound.maxDistance = emitter.maxDistance || 256;
  3108. sound.rolloffFactor = emitter.rolloffFactor || 1;
  3109. sound.distanceModel = emitter.distanceModel || 'exponential';
  3110. sound._positionInEmitterSpace = true;
  3111. }));
  3112. };
  3113. var this_1 = this;
  3114. for (var i = 0; i < emitter.clips.length; i++) {
  3115. _loop_2(i);
  3116. }
  3117. var promise = Promise.all(clipPromises).then(function () {
  3118. var weights = emitter.clips.map(function (clip) { return clip.weight || 1; });
  3119. var weightedSound = new babylonjs_1.WeightedSound(emitter.loop || false, emitter._babylonSounds, weights);
  3120. if (emitter.innerAngle) {
  3121. weightedSound.directionalConeInnerAngle = 2 * babylonjs_1.Tools.ToDegrees(emitter.innerAngle);
  3122. }
  3123. if (emitter.outerAngle) {
  3124. weightedSound.directionalConeOuterAngle = 2 * babylonjs_1.Tools.ToDegrees(emitter.outerAngle);
  3125. }
  3126. if (emitter.volume) {
  3127. weightedSound.volume = emitter.volume;
  3128. }
  3129. emitter._babylonData.sound = weightedSound;
  3130. });
  3131. emitter._babylonData = {
  3132. loaded: promise
  3133. };
  3134. }
  3135. return emitter._babylonData.loaded;
  3136. };
  3137. MSFT_audio_emitter.prototype._getEventAction = function (context, sound, action, time, startOffset) {
  3138. switch (action) {
  3139. case "play" /* play */: {
  3140. return function (currentFrame) {
  3141. var frameOffset = (startOffset || 0) + (currentFrame - time);
  3142. sound.play(frameOffset);
  3143. };
  3144. }
  3145. case "stop" /* stop */: {
  3146. return function (currentFrame) {
  3147. sound.stop();
  3148. };
  3149. }
  3150. case "pause" /* pause */: {
  3151. return function (currentFrame) {
  3152. sound.pause();
  3153. };
  3154. }
  3155. default: {
  3156. throw new Error(context + ": Unsupported action " + action);
  3157. }
  3158. }
  3159. };
  3160. MSFT_audio_emitter.prototype._loadAnimationEventAsync = function (context, animationContext, animation, event, babylonAnimationGroup) {
  3161. var _this = this;
  3162. if (babylonAnimationGroup.targetedAnimations.length == 0) {
  3163. return Promise.resolve();
  3164. }
  3165. var babylonAnimation = babylonAnimationGroup.targetedAnimations[0];
  3166. var emitterIndex = event.emitter;
  3167. var emitter = glTFLoader_1.ArrayItem.Get("#/extensions/" + this.name + "/emitters", this._emitters, emitterIndex);
  3168. return this._loadEmitterAsync(context, emitter).then(function () {
  3169. var sound = emitter._babylonData.sound;
  3170. if (sound) {
  3171. var babylonAnimationEvent = new babylonjs_1.AnimationEvent(event.time, _this._getEventAction(context, sound, event.action, event.time, event.startOffset));
  3172. babylonAnimation.animation.addEvent(babylonAnimationEvent);
  3173. // Make sure all started audio stops when this animation is terminated.
  3174. babylonAnimationGroup.onAnimationGroupEndObservable.add(function () {
  3175. sound.stop();
  3176. });
  3177. babylonAnimationGroup.onAnimationGroupPauseObservable.add(function () {
  3178. sound.pause();
  3179. });
  3180. }
  3181. });
  3182. };
  3183. return MSFT_audio_emitter;
  3184. }());
  3185. exports.MSFT_audio_emitter = MSFT_audio_emitter;
  3186. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_audio_emitter(loader); });
  3187. /***/ }),
  3188. /***/ "./src/glTF/2.0/Extensions/MSFT_lod.ts":
  3189. /*!*********************************************!*\
  3190. !*** ./src/glTF/2.0/Extensions/MSFT_lod.ts ***!
  3191. \*********************************************/
  3192. /*! no static exports found */
  3193. /***/ (function(module, exports, __webpack_require__) {
  3194. "use strict";
  3195. Object.defineProperty(exports, "__esModule", { value: true });
  3196. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3197. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3198. var NAME = "MSFT_lod";
  3199. /**
  3200. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  3201. */
  3202. var MSFT_lod = /** @class */ (function () {
  3203. /** @hidden */
  3204. function MSFT_lod(loader) {
  3205. /** The name of this extension. */
  3206. this.name = NAME;
  3207. /** Defines whether this extension is enabled. */
  3208. this.enabled = true;
  3209. /**
  3210. * Maximum number of LODs to load, starting from the lowest LOD.
  3211. */
  3212. this.maxLODsToLoad = Number.MAX_VALUE;
  3213. /**
  3214. * Observable raised when all node LODs of one level are loaded.
  3215. * The event data is the index of the loaded LOD starting from zero.
  3216. * Dispose the loader to cancel the loading of the next level of LODs.
  3217. */
  3218. this.onNodeLODsLoadedObservable = new babylonjs_1.Observable();
  3219. /**
  3220. * Observable raised when all material LODs of one level are loaded.
  3221. * The event data is the index of the loaded LOD starting from zero.
  3222. * Dispose the loader to cancel the loading of the next level of LODs.
  3223. */
  3224. this.onMaterialLODsLoadedObservable = new babylonjs_1.Observable();
  3225. this._nodeIndexLOD = null;
  3226. this._nodeSignalLODs = new Array();
  3227. this._nodePromiseLODs = new Array();
  3228. this._materialIndexLOD = null;
  3229. this._materialSignalLODs = new Array();
  3230. this._materialPromiseLODs = new Array();
  3231. this._loader = loader;
  3232. }
  3233. /** @hidden */
  3234. MSFT_lod.prototype.dispose = function () {
  3235. delete this._loader;
  3236. this._nodeIndexLOD = null;
  3237. this._nodeSignalLODs.length = 0;
  3238. this._nodePromiseLODs.length = 0;
  3239. this._materialIndexLOD = null;
  3240. this._materialSignalLODs.length = 0;
  3241. this._materialPromiseLODs.length = 0;
  3242. this.onMaterialLODsLoadedObservable.clear();
  3243. this.onNodeLODsLoadedObservable.clear();
  3244. };
  3245. /** @hidden */
  3246. MSFT_lod.prototype.onReady = function () {
  3247. var _this = this;
  3248. var _loop_1 = function (indexLOD) {
  3249. var promise = Promise.all(this_1._nodePromiseLODs[indexLOD]).then(function () {
  3250. if (indexLOD !== 0) {
  3251. _this._loader.endPerformanceCounter("Node LOD " + indexLOD);
  3252. }
  3253. _this._loader.log("Loaded node LOD " + indexLOD);
  3254. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  3255. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  3256. _this._loader.startPerformanceCounter("Node LOD " + (indexLOD + 1));
  3257. if (_this._nodeSignalLODs[indexLOD]) {
  3258. _this._nodeSignalLODs[indexLOD].resolve();
  3259. }
  3260. }
  3261. });
  3262. this_1._loader._completePromises.push(promise);
  3263. };
  3264. var this_1 = this;
  3265. for (var indexLOD = 0; indexLOD < this._nodePromiseLODs.length; indexLOD++) {
  3266. _loop_1(indexLOD);
  3267. }
  3268. var _loop_2 = function (indexLOD) {
  3269. var promise = Promise.all(this_2._materialPromiseLODs[indexLOD]).then(function () {
  3270. if (indexLOD !== 0) {
  3271. _this._loader.endPerformanceCounter("Material LOD " + indexLOD);
  3272. }
  3273. _this._loader.log("Loaded material LOD " + indexLOD);
  3274. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  3275. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  3276. _this._loader.startPerformanceCounter("Material LOD " + (indexLOD + 1));
  3277. if (_this._materialSignalLODs[indexLOD]) {
  3278. _this._materialSignalLODs[indexLOD].resolve();
  3279. }
  3280. }
  3281. });
  3282. this_2._loader._completePromises.push(promise);
  3283. };
  3284. var this_2 = this;
  3285. for (var indexLOD = 0; indexLOD < this._materialPromiseLODs.length; indexLOD++) {
  3286. _loop_2(indexLOD);
  3287. }
  3288. };
  3289. /** @hidden */
  3290. MSFT_lod.prototype.loadNodeAsync = function (context, node, assign) {
  3291. var _this = this;
  3292. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, node, this.name, function (extensionContext, extension) {
  3293. var firstPromise;
  3294. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader.gltf.nodes, extension.ids);
  3295. _this._loader.logOpen("" + extensionContext);
  3296. var _loop_3 = function (indexLOD) {
  3297. var nodeLOD = nodeLODs[indexLOD];
  3298. if (indexLOD !== 0) {
  3299. _this._nodeIndexLOD = indexLOD;
  3300. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new babylonjs_1.Deferred();
  3301. }
  3302. var promise = _this._loader.loadNodeAsync("#/nodes/" + nodeLOD.index, nodeLOD).then(function (babylonMesh) {
  3303. if (indexLOD !== 0) {
  3304. // TODO: should not rely on _babylonMesh
  3305. var previousNodeLOD = nodeLODs[indexLOD - 1];
  3306. if (previousNodeLOD._babylonMesh) {
  3307. previousNodeLOD._babylonMesh.dispose();
  3308. delete previousNodeLOD._babylonMesh;
  3309. _this._disposeUnusedMaterials();
  3310. }
  3311. }
  3312. return babylonMesh;
  3313. });
  3314. if (indexLOD === 0) {
  3315. firstPromise = promise;
  3316. }
  3317. else {
  3318. _this._nodeIndexLOD = null;
  3319. }
  3320. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  3321. _this._nodePromiseLODs[indexLOD].push(promise);
  3322. };
  3323. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  3324. _loop_3(indexLOD);
  3325. }
  3326. _this._loader.logClose();
  3327. return firstPromise;
  3328. });
  3329. };
  3330. /** @hidden */
  3331. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  3332. var _this = this;
  3333. // Don't load material LODs if already loading a node LOD.
  3334. if (this._nodeIndexLOD) {
  3335. return null;
  3336. }
  3337. return glTFLoader_1.GLTFLoader.LoadExtensionAsync(context, material, this.name, function (extensionContext, extension) {
  3338. var firstPromise;
  3339. var materialLODs = _this._getLODs(extensionContext, material, _this._loader.gltf.materials, extension.ids);
  3340. _this._loader.logOpen("" + extensionContext);
  3341. var _loop_4 = function (indexLOD) {
  3342. var materialLOD = materialLODs[indexLOD];
  3343. if (indexLOD !== 0) {
  3344. _this._materialIndexLOD = indexLOD;
  3345. }
  3346. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD.index, materialLOD, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  3347. if (indexLOD === 0) {
  3348. assign(babylonMaterial);
  3349. }
  3350. }).then(function (babylonMaterial) {
  3351. if (indexLOD !== 0) {
  3352. assign(babylonMaterial);
  3353. // TODO: should not rely on _babylonData
  3354. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  3355. if (previousBabylonDataLOD[babylonDrawMode]) {
  3356. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  3357. delete previousBabylonDataLOD[babylonDrawMode];
  3358. }
  3359. }
  3360. return babylonMaterial;
  3361. });
  3362. if (indexLOD === 0) {
  3363. firstPromise = promise;
  3364. }
  3365. else {
  3366. _this._materialIndexLOD = null;
  3367. }
  3368. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  3369. _this._materialPromiseLODs[indexLOD].push(promise);
  3370. };
  3371. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  3372. _loop_4(indexLOD);
  3373. }
  3374. _this._loader.logClose();
  3375. return firstPromise;
  3376. });
  3377. };
  3378. /** @hidden */
  3379. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  3380. var _this = this;
  3381. // Defer the loading of uris if loading a material or node LOD.
  3382. if (this._materialIndexLOD !== null) {
  3383. this._loader.log("deferred");
  3384. var previousIndexLOD = this._materialIndexLOD - 1;
  3385. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new babylonjs_1.Deferred();
  3386. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  3387. return _this._loader.loadUriAsync(context, uri);
  3388. });
  3389. }
  3390. else if (this._nodeIndexLOD !== null) {
  3391. this._loader.log("deferred");
  3392. var previousIndexLOD = this._nodeIndexLOD - 1;
  3393. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new babylonjs_1.Deferred();
  3394. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  3395. return _this._loader.loadUriAsync(context, uri);
  3396. });
  3397. }
  3398. return null;
  3399. };
  3400. /**
  3401. * Gets an array of LOD properties from lowest to highest.
  3402. */
  3403. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  3404. if (this.maxLODsToLoad <= 0) {
  3405. throw new Error("maxLODsToLoad must be greater than zero");
  3406. }
  3407. var properties = new Array();
  3408. for (var i = ids.length - 1; i >= 0; i--) {
  3409. properties.push(glTFLoader_1.ArrayItem.Get(context + "/ids/" + ids[i], array, ids[i]));
  3410. if (properties.length === this.maxLODsToLoad) {
  3411. return properties;
  3412. }
  3413. }
  3414. properties.push(property);
  3415. return properties;
  3416. };
  3417. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  3418. // TODO: should not rely on _babylonData
  3419. var materials = this._loader.gltf.materials;
  3420. if (materials) {
  3421. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  3422. var material = materials_1[_i];
  3423. if (material._babylonData) {
  3424. for (var drawMode in material._babylonData) {
  3425. var babylonData = material._babylonData[drawMode];
  3426. if (babylonData.meshes.length === 0) {
  3427. babylonData.material.dispose(false, true);
  3428. delete material._babylonData[drawMode];
  3429. }
  3430. }
  3431. }
  3432. }
  3433. }
  3434. };
  3435. return MSFT_lod;
  3436. }());
  3437. exports.MSFT_lod = MSFT_lod;
  3438. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_lod(loader); });
  3439. /***/ }),
  3440. /***/ "./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts":
  3441. /*!*******************************************************!*\
  3442. !*** ./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts ***!
  3443. \*******************************************************/
  3444. /*! no static exports found */
  3445. /***/ (function(module, exports, __webpack_require__) {
  3446. "use strict";
  3447. Object.defineProperty(exports, "__esModule", { value: true });
  3448. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3449. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3450. var NAME = "MSFT_minecraftMesh";
  3451. /** @hidden */
  3452. var MSFT_minecraftMesh = /** @class */ (function () {
  3453. function MSFT_minecraftMesh(loader) {
  3454. this.name = NAME;
  3455. this.enabled = true;
  3456. this._loader = loader;
  3457. }
  3458. MSFT_minecraftMesh.prototype.dispose = function () {
  3459. delete this._loader;
  3460. };
  3461. MSFT_minecraftMesh.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3462. var _this = this;
  3463. return glTFLoader_1.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  3464. if (extra) {
  3465. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  3466. throw new Error(extraContext + ": Material type not supported");
  3467. }
  3468. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  3469. if (babylonMaterial.needAlphaBlending()) {
  3470. babylonMaterial.forceDepthWrite = true;
  3471. babylonMaterial.separateCullingPass = true;
  3472. }
  3473. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  3474. babylonMaterial.twoSidedLighting = true;
  3475. return promise;
  3476. }
  3477. return null;
  3478. });
  3479. };
  3480. return MSFT_minecraftMesh;
  3481. }());
  3482. exports.MSFT_minecraftMesh = MSFT_minecraftMesh;
  3483. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  3484. /***/ }),
  3485. /***/ "./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts":
  3486. /*!*****************************************************!*\
  3487. !*** ./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts ***!
  3488. \*****************************************************/
  3489. /*! no static exports found */
  3490. /***/ (function(module, exports, __webpack_require__) {
  3491. "use strict";
  3492. Object.defineProperty(exports, "__esModule", { value: true });
  3493. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3494. var glTFLoader_1 = __webpack_require__(/*! ../glTFLoader */ "./src/glTF/2.0/glTFLoader.ts");
  3495. var NAME = "MSFT_sRGBFactors";
  3496. /** @hidden */
  3497. var MSFT_sRGBFactors = /** @class */ (function () {
  3498. function MSFT_sRGBFactors(loader) {
  3499. this.name = NAME;
  3500. this.enabled = true;
  3501. this._loader = loader;
  3502. }
  3503. MSFT_sRGBFactors.prototype.dispose = function () {
  3504. delete this._loader;
  3505. };
  3506. MSFT_sRGBFactors.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  3507. var _this = this;
  3508. return glTFLoader_1.GLTFLoader.LoadExtraAsync(context, material, this.name, function (extraContext, extra) {
  3509. if (extra) {
  3510. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  3511. throw new Error(extraContext + ": Material type not supported");
  3512. }
  3513. var promise = _this._loader.loadMaterialPropertiesAsync(context, material, babylonMaterial);
  3514. if (!babylonMaterial.albedoTexture) {
  3515. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  3516. }
  3517. if (!babylonMaterial.reflectivityTexture) {
  3518. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  3519. }
  3520. return promise;
  3521. }
  3522. return null;
  3523. });
  3524. };
  3525. return MSFT_sRGBFactors;
  3526. }());
  3527. exports.MSFT_sRGBFactors = MSFT_sRGBFactors;
  3528. glTFLoader_1.GLTFLoader.RegisterExtension(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  3529. /***/ }),
  3530. /***/ "./src/glTF/2.0/Extensions/index.ts":
  3531. /*!******************************************!*\
  3532. !*** ./src/glTF/2.0/Extensions/index.ts ***!
  3533. \******************************************/
  3534. /*! no static exports found */
  3535. /***/ (function(module, exports, __webpack_require__) {
  3536. "use strict";
  3537. function __export(m) {
  3538. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  3539. }
  3540. Object.defineProperty(exports, "__esModule", { value: true });
  3541. __export(__webpack_require__(/*! ./EXT_lights_image_based */ "./src/glTF/2.0/Extensions/EXT_lights_image_based.ts"));
  3542. __export(__webpack_require__(/*! ./KHR_draco_mesh_compression */ "./src/glTF/2.0/Extensions/KHR_draco_mesh_compression.ts"));
  3543. __export(__webpack_require__(/*! ./KHR_lights_punctual */ "./src/glTF/2.0/Extensions/KHR_lights_punctual.ts"));
  3544. __export(__webpack_require__(/*! ./KHR_materials_pbrSpecularGlossiness */ "./src/glTF/2.0/Extensions/KHR_materials_pbrSpecularGlossiness.ts"));
  3545. __export(__webpack_require__(/*! ./KHR_materials_unlit */ "./src/glTF/2.0/Extensions/KHR_materials_unlit.ts"));
  3546. __export(__webpack_require__(/*! ./KHR_texture_transform */ "./src/glTF/2.0/Extensions/KHR_texture_transform.ts"));
  3547. __export(__webpack_require__(/*! ./MSFT_audio_emitter */ "./src/glTF/2.0/Extensions/MSFT_audio_emitter.ts"));
  3548. __export(__webpack_require__(/*! ./MSFT_lod */ "./src/glTF/2.0/Extensions/MSFT_lod.ts"));
  3549. __export(__webpack_require__(/*! ./MSFT_minecraftMesh */ "./src/glTF/2.0/Extensions/MSFT_minecraftMesh.ts"));
  3550. __export(__webpack_require__(/*! ./MSFT_sRGBFactors */ "./src/glTF/2.0/Extensions/MSFT_sRGBFactors.ts"));
  3551. /***/ }),
  3552. /***/ "./src/glTF/2.0/glTFLoader.ts":
  3553. /*!************************************!*\
  3554. !*** ./src/glTF/2.0/glTFLoader.ts ***!
  3555. \************************************/
  3556. /*! no static exports found */
  3557. /***/ (function(module, exports, __webpack_require__) {
  3558. "use strict";
  3559. Object.defineProperty(exports, "__esModule", { value: true });
  3560. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  3561. var glTFFileLoader_1 = __webpack_require__(/*! ../glTFFileLoader */ "./src/glTF/glTFFileLoader.ts");
  3562. /**
  3563. * Helper class for working with arrays when loading the glTF asset
  3564. */
  3565. var ArrayItem = /** @class */ (function () {
  3566. function ArrayItem() {
  3567. }
  3568. /**
  3569. * Gets an item from the given array.
  3570. * @param context The context when loading the asset
  3571. * @param array The array to get the item from
  3572. * @param index The index to the array
  3573. * @returns The array item
  3574. */
  3575. ArrayItem.Get = function (context, array, index) {
  3576. if (!array || index == undefined || !array[index]) {
  3577. throw new Error(context + ": Failed to find index (" + index + ")");
  3578. }
  3579. return array[index];
  3580. };
  3581. /**
  3582. * Assign an `index` field to each item of the given array.
  3583. * @param array The array of items
  3584. */
  3585. ArrayItem.Assign = function (array) {
  3586. if (array) {
  3587. for (var index = 0; index < array.length; index++) {
  3588. array[index].index = index;
  3589. }
  3590. }
  3591. };
  3592. return ArrayItem;
  3593. }());
  3594. exports.ArrayItem = ArrayItem;
  3595. /**
  3596. * The glTF 2.0 loader
  3597. */
  3598. var GLTFLoader = /** @class */ (function () {
  3599. /** @hidden */
  3600. function GLTFLoader(parent) {
  3601. /** @hidden */
  3602. this._completePromises = new Array();
  3603. this._disposed = false;
  3604. this._state = null;
  3605. this._extensions = {};
  3606. this._defaultBabylonMaterialData = {};
  3607. this._requests = new Array();
  3608. this._parent = parent;
  3609. }
  3610. /**
  3611. * Registers a loader extension.
  3612. * @param name The name of the loader extension.
  3613. * @param factory The factory function that creates the loader extension.
  3614. */
  3615. GLTFLoader.RegisterExtension = function (name, factory) {
  3616. if (GLTFLoader.UnregisterExtension(name)) {
  3617. babylonjs_1.Tools.Warn("Extension with the name '" + name + "' already exists");
  3618. }
  3619. GLTFLoader._ExtensionFactories[name] = factory;
  3620. // Keep the order of registration so that extensions registered first are called first.
  3621. GLTFLoader._ExtensionNames.push(name);
  3622. };
  3623. /**
  3624. * Unregisters a loader extension.
  3625. * @param name The name of the loader extenion.
  3626. * @returns A boolean indicating whether the extension has been unregistered
  3627. */
  3628. GLTFLoader.UnregisterExtension = function (name) {
  3629. if (!GLTFLoader._ExtensionFactories[name]) {
  3630. return false;
  3631. }
  3632. delete GLTFLoader._ExtensionFactories[name];
  3633. var index = GLTFLoader._ExtensionNames.indexOf(name);
  3634. if (index !== -1) {
  3635. GLTFLoader._ExtensionNames.splice(index, 1);
  3636. }
  3637. return true;
  3638. };
  3639. Object.defineProperty(GLTFLoader.prototype, "state", {
  3640. /**
  3641. * Gets the loader state.
  3642. */
  3643. get: function () {
  3644. return this._state;
  3645. },
  3646. enumerable: true,
  3647. configurable: true
  3648. });
  3649. /** @hidden */
  3650. GLTFLoader.prototype.dispose = function () {
  3651. if (this._disposed) {
  3652. return;
  3653. }
  3654. this._disposed = true;
  3655. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  3656. var request = _a[_i];
  3657. request.abort();
  3658. }
  3659. this._requests.length = 0;
  3660. delete this.gltf;
  3661. delete this.babylonScene;
  3662. this._completePromises.length = 0;
  3663. for (var name_1 in this._extensions) {
  3664. var extension = this._extensions[name_1];
  3665. if (extension.dispose) {
  3666. this._extensions[name_1].dispose();
  3667. }
  3668. }
  3669. this._extensions = {};
  3670. delete this._rootBabylonMesh;
  3671. delete this._progressCallback;
  3672. this._parent._clear();
  3673. };
  3674. /** @hidden */
  3675. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  3676. var _this = this;
  3677. return Promise.resolve().then(function () {
  3678. _this.babylonScene = scene;
  3679. _this._rootUrl = rootUrl;
  3680. _this._fileName = fileName || "scene";
  3681. _this._progressCallback = onProgress;
  3682. _this._loadData(data);
  3683. var nodes = null;
  3684. if (meshesNames) {
  3685. var nodeMap_1 = {};
  3686. if (_this.gltf.nodes) {
  3687. for (var _i = 0, _a = _this.gltf.nodes; _i < _a.length; _i++) {
  3688. var node = _a[_i];
  3689. if (node.name) {
  3690. nodeMap_1[node.name] = node.index;
  3691. }
  3692. }
  3693. }
  3694. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  3695. nodes = names.map(function (name) {
  3696. var node = nodeMap_1[name];
  3697. if (node === undefined) {
  3698. throw new Error("Failed to find node '" + name + "'");
  3699. }
  3700. return node;
  3701. });
  3702. }
  3703. return _this._loadAsync(nodes, function () {
  3704. return {
  3705. meshes: _this._getMeshes(),
  3706. particleSystems: [],
  3707. skeletons: _this._getSkeletons(),
  3708. animationGroups: _this._getAnimationGroups()
  3709. };
  3710. });
  3711. });
  3712. };
  3713. /** @hidden */
  3714. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  3715. var _this = this;
  3716. return Promise.resolve().then(function () {
  3717. _this.babylonScene = scene;
  3718. _this._rootUrl = rootUrl;
  3719. _this._fileName = fileName || "scene";
  3720. _this._progressCallback = onProgress;
  3721. _this._loadData(data);
  3722. return _this._loadAsync(null, function () { return undefined; });
  3723. });
  3724. };
  3725. GLTFLoader.prototype._loadAsync = function (nodes, resultFunc) {
  3726. var _this = this;
  3727. return Promise.resolve().then(function () {
  3728. _this._uniqueRootUrl = (_this._rootUrl.indexOf("file:") === -1 && _this._fileName) ? _this._rootUrl : "" + _this._rootUrl + Date.now() + "/";
  3729. _this._loadExtensions();
  3730. _this._checkExtensions();
  3731. var loadingToReadyCounterName = glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.LOADING] + " => " + glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.READY];
  3732. var loadingToCompleteCounterName = glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.LOADING] + " => " + glTFFileLoader_1.GLTFLoaderState[glTFFileLoader_1.GLTFLoaderState.COMPLETE];
  3733. _this._parent._startPerformanceCounter(loadingToReadyCounterName);
  3734. _this._parent._startPerformanceCounter(loadingToCompleteCounterName);
  3735. _this._setState(glTFFileLoader_1.GLTFLoaderState.LOADING);
  3736. _this._extensionsOnLoading();
  3737. var promises = new Array();
  3738. if (nodes) {
  3739. promises.push(_this.loadSceneAsync("#/nodes", { nodes: nodes, index: -1 }));
  3740. }
  3741. else {
  3742. var scene = ArrayItem.Get("#/scene", _this.gltf.scenes, _this.gltf.scene || 0);
  3743. promises.push(_this.loadSceneAsync("#/scenes/" + scene.index, scene));
  3744. }
  3745. if (_this._parent.compileMaterials) {
  3746. promises.push(_this._compileMaterialsAsync());
  3747. }
  3748. if (_this._parent.compileShadowGenerators) {
  3749. promises.push(_this._compileShadowGeneratorsAsync());
  3750. }
  3751. var resultPromise = Promise.all(promises).then(function () {
  3752. _this._setState(glTFFileLoader_1.GLTFLoaderState.READY);
  3753. _this._extensionsOnReady();
  3754. _this._startAnimations();
  3755. return resultFunc();
  3756. });
  3757. resultPromise.then(function () {
  3758. _this._parent._endPerformanceCounter(loadingToReadyCounterName);
  3759. babylonjs_1.Tools.SetImmediate(function () {
  3760. if (!_this._disposed) {
  3761. Promise.all(_this._completePromises).then(function () {
  3762. _this._parent._endPerformanceCounter(loadingToCompleteCounterName);
  3763. _this._setState(glTFFileLoader_1.GLTFLoaderState.COMPLETE);
  3764. _this._parent.onCompleteObservable.notifyObservers(undefined);
  3765. _this._parent.onCompleteObservable.clear();
  3766. _this.dispose();
  3767. }, function (error) {
  3768. _this._parent.onErrorObservable.notifyObservers(error);
  3769. _this._parent.onErrorObservable.clear();
  3770. _this.dispose();
  3771. });
  3772. }
  3773. });
  3774. });
  3775. return resultPromise;
  3776. }, function (error) {
  3777. if (!_this._disposed) {
  3778. _this._parent.onErrorObservable.notifyObservers(error);
  3779. _this._parent.onErrorObservable.clear();
  3780. _this.dispose();
  3781. }
  3782. throw error;
  3783. });
  3784. };
  3785. GLTFLoader.prototype._loadData = function (data) {
  3786. this.gltf = data.json;
  3787. this._setupData();
  3788. if (data.bin) {
  3789. var buffers = this.gltf.buffers;
  3790. if (buffers && buffers[0] && !buffers[0].uri) {
  3791. var binaryBuffer = buffers[0];
  3792. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  3793. babylonjs_1.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  3794. }
  3795. binaryBuffer._data = Promise.resolve(data.bin);
  3796. }
  3797. else {
  3798. babylonjs_1.Tools.Warn("Unexpected BIN chunk");
  3799. }
  3800. }
  3801. };
  3802. GLTFLoader.prototype._setupData = function () {
  3803. ArrayItem.Assign(this.gltf.accessors);
  3804. ArrayItem.Assign(this.gltf.animations);
  3805. ArrayItem.Assign(this.gltf.buffers);
  3806. ArrayItem.Assign(this.gltf.bufferViews);
  3807. ArrayItem.Assign(this.gltf.cameras);
  3808. ArrayItem.Assign(this.gltf.images);
  3809. ArrayItem.Assign(this.gltf.materials);
  3810. ArrayItem.Assign(this.gltf.meshes);
  3811. ArrayItem.Assign(this.gltf.nodes);
  3812. ArrayItem.Assign(this.gltf.samplers);
  3813. ArrayItem.Assign(this.gltf.scenes);
  3814. ArrayItem.Assign(this.gltf.skins);
  3815. ArrayItem.Assign(this.gltf.textures);
  3816. if (this.gltf.nodes) {
  3817. var nodeParents = {};
  3818. for (var _i = 0, _a = this.gltf.nodes; _i < _a.length; _i++) {
  3819. var node = _a[_i];
  3820. if (node.children) {
  3821. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  3822. var index = _c[_b];
  3823. nodeParents[index] = node.index;
  3824. }
  3825. }
  3826. }
  3827. var rootNode = this._createRootNode();
  3828. for (var _d = 0, _e = this.gltf.nodes; _d < _e.length; _d++) {
  3829. var node = _e[_d];
  3830. var parentIndex = nodeParents[node.index];
  3831. node.parent = parentIndex === undefined ? rootNode : this.gltf.nodes[parentIndex];
  3832. }
  3833. }
  3834. };
  3835. GLTFLoader.prototype._loadExtensions = function () {
  3836. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  3837. var name_2 = _a[_i];
  3838. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  3839. this._extensions[name_2] = extension;
  3840. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  3841. }
  3842. this._parent.onExtensionLoadedObservable.clear();
  3843. };
  3844. GLTFLoader.prototype._checkExtensions = function () {
  3845. if (this.gltf.extensionsRequired) {
  3846. for (var _i = 0, _a = this.gltf.extensionsRequired; _i < _a.length; _i++) {
  3847. var name_3 = _a[_i];
  3848. var extension = this._extensions[name_3];
  3849. if (!extension || !extension.enabled) {
  3850. throw new Error("Require extension " + name_3 + " is not available");
  3851. }
  3852. }
  3853. }
  3854. };
  3855. GLTFLoader.prototype._setState = function (state) {
  3856. this._state = state;
  3857. this.log(glTFFileLoader_1.GLTFLoaderState[this._state]);
  3858. };
  3859. GLTFLoader.prototype._createRootNode = function () {
  3860. this._rootBabylonMesh = new babylonjs_1.Mesh("__root__", this.babylonScene);
  3861. var rootNode = {
  3862. _babylonMesh: this._rootBabylonMesh,
  3863. index: -1
  3864. };
  3865. switch (this._parent.coordinateSystemMode) {
  3866. case glTFFileLoader_1.GLTFLoaderCoordinateSystemMode.AUTO: {
  3867. if (!this.babylonScene.useRightHandedSystem) {
  3868. rootNode.rotation = [0, 1, 0, 0];
  3869. rootNode.scale = [1, 1, -1];
  3870. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  3871. }
  3872. break;
  3873. }
  3874. case glTFFileLoader_1.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  3875. this.babylonScene.useRightHandedSystem = true;
  3876. break;
  3877. }
  3878. default: {
  3879. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  3880. }
  3881. }
  3882. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  3883. return rootNode;
  3884. };
  3885. /**
  3886. * Loads a glTF scene.
  3887. * @param context The context when loading the asset
  3888. * @param scene The glTF scene property
  3889. * @returns A promise that resolves when the load is complete
  3890. */
  3891. GLTFLoader.prototype.loadSceneAsync = function (context, scene) {
  3892. var _this = this;
  3893. var extensionPromise = this._extensionsLoadSceneAsync(context, scene);
  3894. if (extensionPromise) {
  3895. return extensionPromise;
  3896. }
  3897. var promises = new Array();
  3898. this.logOpen(context + " " + (scene.name || ""));
  3899. if (scene.nodes) {
  3900. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  3901. var index = _a[_i];
  3902. var node = ArrayItem.Get(context + "/nodes/" + index, this.gltf.nodes, index);
  3903. promises.push(this.loadNodeAsync("#/nodes/" + node.index, node, function (babylonMesh) {
  3904. babylonMesh.parent = _this._rootBabylonMesh;
  3905. }));
  3906. }
  3907. }
  3908. promises.push(this._loadAnimationsAsync());
  3909. this.logClose();
  3910. return Promise.all(promises).then(function () { });
  3911. };
  3912. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  3913. if (node._primitiveBabylonMeshes) {
  3914. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  3915. var babylonMesh = _a[_i];
  3916. callback(babylonMesh);
  3917. }
  3918. }
  3919. else {
  3920. callback(node._babylonMesh);
  3921. }
  3922. };
  3923. GLTFLoader.prototype._getMeshes = function () {
  3924. var meshes = new Array();
  3925. // Root mesh is always first.
  3926. meshes.push(this._rootBabylonMesh);
  3927. var nodes = this.gltf.nodes;
  3928. if (nodes) {
  3929. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  3930. var node = nodes_1[_i];
  3931. if (node._babylonMesh) {
  3932. meshes.push(node._babylonMesh);
  3933. }
  3934. if (node._primitiveBabylonMeshes) {
  3935. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  3936. var babylonMesh = _b[_a];
  3937. meshes.push(babylonMesh);
  3938. }
  3939. }
  3940. }
  3941. }
  3942. return meshes;
  3943. };
  3944. GLTFLoader.prototype._getSkeletons = function () {
  3945. var skeletons = new Array();
  3946. var skins = this.gltf.skins;
  3947. if (skins) {
  3948. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  3949. var skin = skins_1[_i];
  3950. if (skin._babylonSkeleton) {
  3951. skeletons.push(skin._babylonSkeleton);
  3952. }
  3953. }
  3954. }
  3955. return skeletons;
  3956. };
  3957. GLTFLoader.prototype._getAnimationGroups = function () {
  3958. var animationGroups = new Array();
  3959. var animations = this.gltf.animations;
  3960. if (animations) {
  3961. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  3962. var animation = animations_1[_i];
  3963. if (animation._babylonAnimationGroup) {
  3964. animationGroups.push(animation._babylonAnimationGroup);
  3965. }
  3966. }
  3967. }
  3968. return animationGroups;
  3969. };
  3970. GLTFLoader.prototype._startAnimations = function () {
  3971. switch (this._parent.animationStartMode) {
  3972. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.NONE: {
  3973. // do nothing
  3974. break;
  3975. }
  3976. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.FIRST: {
  3977. var babylonAnimationGroups = this._getAnimationGroups();
  3978. if (babylonAnimationGroups.length !== 0) {
  3979. babylonAnimationGroups[0].start(true);
  3980. }
  3981. break;
  3982. }
  3983. case glTFFileLoader_1.GLTFLoaderAnimationStartMode.ALL: {
  3984. var babylonAnimationGroups = this._getAnimationGroups();
  3985. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  3986. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  3987. babylonAnimationGroup.start(true);
  3988. }
  3989. break;
  3990. }
  3991. default: {
  3992. babylonjs_1.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  3993. return;
  3994. }
  3995. }
  3996. };
  3997. /**
  3998. * Loads a glTF node.
  3999. * @param context The context when loading the asset
  4000. * @param node The glTF node property
  4001. * @param assign A function called synchronously after parsing the glTF properties
  4002. * @returns A promise that resolves with the loaded Babylon mesh when the load is complete
  4003. */
  4004. GLTFLoader.prototype.loadNodeAsync = function (context, node, assign) {
  4005. var _this = this;
  4006. if (assign === void 0) { assign = function () { }; }
  4007. var extensionPromise = this._extensionsLoadNodeAsync(context, node, assign);
  4008. if (extensionPromise) {
  4009. return extensionPromise;
  4010. }
  4011. if (node._babylonMesh) {
  4012. throw new Error(context + ": Invalid recursive node hierarchy");
  4013. }
  4014. var promises = new Array();
  4015. this.logOpen(context + " " + (node.name || ""));
  4016. var babylonMesh = new babylonjs_1.Mesh(node.name || "node" + node.index, this.babylonScene);
  4017. node._babylonMesh = babylonMesh;
  4018. babylonMesh.setEnabled(false);
  4019. GLTFLoader._LoadTransform(node, babylonMesh);
  4020. if (node.mesh != undefined) {
  4021. var mesh = ArrayItem.Get(context + "/mesh", this.gltf.meshes, node.mesh);
  4022. promises.push(this._loadMeshAsync("#/meshes/" + mesh.index, node, mesh, babylonMesh));
  4023. }
  4024. if (node.camera != undefined) {
  4025. var camera = ArrayItem.Get(context + "/camera", this.gltf.cameras, node.camera);
  4026. promises.push(this.loadCameraAsync("#/cameras/" + camera.index, camera, function (babylonCamera) {
  4027. babylonCamera.parent = babylonMesh;
  4028. }));
  4029. }
  4030. if (node.children) {
  4031. var _loop_1 = function (index) {
  4032. var childNode = ArrayItem.Get(context + "/children/" + index, this_1.gltf.nodes, index);
  4033. promises.push(this_1.loadNodeAsync("#/nodes/" + node.index, childNode, function (childBabylonMesh) {
  4034. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  4035. if (childNode.skin != undefined) {
  4036. childBabylonMesh.parent = _this._rootBabylonMesh;
  4037. return;
  4038. }
  4039. childBabylonMesh.parent = babylonMesh;
  4040. }));
  4041. };
  4042. var this_1 = this;
  4043. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  4044. var index = _a[_i];
  4045. _loop_1(index);
  4046. }
  4047. }
  4048. assign(babylonMesh);
  4049. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  4050. this.logClose();
  4051. return Promise.all(promises).then(function () {
  4052. babylonMesh.setEnabled(true);
  4053. return babylonMesh;
  4054. });
  4055. };
  4056. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  4057. var _this = this;
  4058. var promises = new Array();
  4059. this.logOpen(context + " " + (mesh.name || ""));
  4060. var primitives = mesh.primitives;
  4061. if (!primitives || primitives.length === 0) {
  4062. throw new Error(context + ": Primitives are missing");
  4063. }
  4064. ArrayItem.Assign(primitives);
  4065. if (primitives.length === 1) {
  4066. var primitive = primitives[0];
  4067. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, babylonMesh));
  4068. }
  4069. else {
  4070. node._primitiveBabylonMeshes = [];
  4071. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  4072. var primitive = primitives_1[_i];
  4073. var primitiveBabylonMesh = new babylonjs_1.Mesh((mesh.name || babylonMesh.name) + "_" + primitive.index, this.babylonScene, babylonMesh);
  4074. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  4075. promises.push(this._loadMeshPrimitiveAsync(context + "/primitives/" + primitive.index, node, mesh, primitive, primitiveBabylonMesh));
  4076. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  4077. }
  4078. }
  4079. if (node.skin != undefined) {
  4080. var skin = ArrayItem.Get(context + "/skin", this.gltf.skins, node.skin);
  4081. promises.push(this._loadSkinAsync("#/skins/" + skin.index, node, skin));
  4082. }
  4083. this.logClose();
  4084. return Promise.all(promises).then(function () {
  4085. _this._forEachPrimitive(node, function (babylonMesh) {
  4086. babylonMesh._refreshBoundingInfo(true);
  4087. });
  4088. });
  4089. };
  4090. GLTFLoader.prototype._loadMeshPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  4091. var _this = this;
  4092. var promises = new Array();
  4093. this.logOpen("" + context);
  4094. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  4095. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  4096. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  4097. babylonGeometry.applyToMesh(babylonMesh);
  4098. });
  4099. }));
  4100. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  4101. if (primitive.material == undefined) {
  4102. var babylonMaterial = this._defaultBabylonMaterialData[babylonDrawMode];
  4103. if (!babylonMaterial) {
  4104. babylonMaterial = this._createDefaultMaterial("__gltf_default", babylonDrawMode);
  4105. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4106. this._defaultBabylonMaterialData[babylonDrawMode] = babylonMaterial;
  4107. }
  4108. babylonMesh.material = babylonMaterial;
  4109. }
  4110. else {
  4111. var material = ArrayItem.Get(context + "/material", this.gltf.materials, primitive.material);
  4112. promises.push(this._loadMaterialAsync("#/materials/" + material.index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  4113. babylonMesh.material = babylonMaterial;
  4114. }));
  4115. }
  4116. this.logClose();
  4117. return Promise.all(promises).then(function () { });
  4118. };
  4119. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  4120. var _this = this;
  4121. var extensionPromise = this._extensionsLoadVertexDataAsync(context, primitive, babylonMesh);
  4122. if (extensionPromise) {
  4123. return extensionPromise;
  4124. }
  4125. var attributes = primitive.attributes;
  4126. if (!attributes) {
  4127. throw new Error(context + ": Attributes are missing");
  4128. }
  4129. var promises = new Array();
  4130. var babylonGeometry = new babylonjs_1.Geometry(babylonMesh.name, this.babylonScene);
  4131. if (primitive.indices == undefined) {
  4132. babylonMesh.isUnIndexed = true;
  4133. }
  4134. else {
  4135. var accessor = ArrayItem.Get(context + "/indices", this.gltf.accessors, primitive.indices);
  4136. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  4137. babylonGeometry.setIndices(data);
  4138. }));
  4139. }
  4140. var loadAttribute = function (attribute, kind, callback) {
  4141. if (attributes[attribute] == undefined) {
  4142. return;
  4143. }
  4144. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  4145. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  4146. babylonMesh._delayInfo.push(kind);
  4147. }
  4148. var accessor = ArrayItem.Get(context + "/attributes/" + attribute, _this.gltf.accessors, attributes[attribute]);
  4149. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor.index, accessor, kind).then(function (babylonVertexBuffer) {
  4150. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  4151. }));
  4152. if (callback) {
  4153. callback(accessor);
  4154. }
  4155. };
  4156. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind);
  4157. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind);
  4158. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind);
  4159. loadAttribute("TEXCOORD_0", babylonjs_1.VertexBuffer.UVKind);
  4160. loadAttribute("TEXCOORD_1", babylonjs_1.VertexBuffer.UV2Kind);
  4161. loadAttribute("JOINTS_0", babylonjs_1.VertexBuffer.MatricesIndicesKind);
  4162. loadAttribute("WEIGHTS_0", babylonjs_1.VertexBuffer.MatricesWeightsKind);
  4163. loadAttribute("COLOR_0", babylonjs_1.VertexBuffer.ColorKind, function (accessor) {
  4164. if (accessor.type === "VEC4" /* VEC4 */) {
  4165. babylonMesh.hasVertexAlpha = true;
  4166. }
  4167. });
  4168. return Promise.all(promises).then(function () {
  4169. return babylonGeometry;
  4170. });
  4171. };
  4172. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  4173. if (!primitive.targets) {
  4174. return;
  4175. }
  4176. if (node._numMorphTargets == undefined) {
  4177. node._numMorphTargets = primitive.targets.length;
  4178. }
  4179. else if (primitive.targets.length !== node._numMorphTargets) {
  4180. throw new Error(context + ": Primitives do not have the same number of targets");
  4181. }
  4182. babylonMesh.morphTargetManager = new babylonjs_1.MorphTargetManager();
  4183. for (var index = 0; index < primitive.targets.length; index++) {
  4184. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  4185. babylonMesh.morphTargetManager.addTarget(new babylonjs_1.MorphTarget("morphTarget" + index, weight));
  4186. // TODO: tell the target whether it has positions, normals, tangents
  4187. }
  4188. };
  4189. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  4190. if (!primitive.targets) {
  4191. return Promise.resolve();
  4192. }
  4193. var promises = new Array();
  4194. var morphTargetManager = babylonMesh.morphTargetManager;
  4195. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  4196. var babylonMorphTarget = morphTargetManager.getTarget(index);
  4197. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  4198. }
  4199. return Promise.all(promises).then(function () { });
  4200. };
  4201. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  4202. var _this = this;
  4203. var promises = new Array();
  4204. var loadAttribute = function (attribute, kind, setData) {
  4205. if (attributes[attribute] == undefined) {
  4206. return;
  4207. }
  4208. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  4209. if (!babylonVertexBuffer) {
  4210. return;
  4211. }
  4212. var accessor = ArrayItem.Get(context + "/" + attribute, _this.gltf.accessors, attributes[attribute]);
  4213. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  4214. setData(babylonVertexBuffer, data);
  4215. }));
  4216. };
  4217. loadAttribute("POSITION", babylonjs_1.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  4218. babylonVertexBuffer.forEach(data.length, function (value, index) {
  4219. data[index] += value;
  4220. });
  4221. babylonMorphTarget.setPositions(data);
  4222. });
  4223. loadAttribute("NORMAL", babylonjs_1.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  4224. babylonVertexBuffer.forEach(data.length, function (value, index) {
  4225. data[index] += value;
  4226. });
  4227. babylonMorphTarget.setNormals(data);
  4228. });
  4229. loadAttribute("TANGENT", babylonjs_1.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  4230. var dataIndex = 0;
  4231. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  4232. // Tangent data for morph targets is stored as xyz delta.
  4233. // The vertexData.tangent is stored as xyzw.
  4234. // So we need to skip every fourth vertexData.tangent.
  4235. if (((index + 1) % 4) !== 0) {
  4236. data[dataIndex++] += value;
  4237. }
  4238. });
  4239. babylonMorphTarget.setTangents(data);
  4240. });
  4241. return Promise.all(promises).then(function () { });
  4242. };
  4243. GLTFLoader._LoadTransform = function (node, babylonNode) {
  4244. var position = babylonjs_1.Vector3.Zero();
  4245. var rotation = babylonjs_1.Quaternion.Identity();
  4246. var scaling = babylonjs_1.Vector3.One();
  4247. if (node.matrix) {
  4248. var matrix = babylonjs_1.Matrix.FromArray(node.matrix);
  4249. matrix.decompose(scaling, rotation, position);
  4250. }
  4251. else {
  4252. if (node.translation) {
  4253. position = babylonjs_1.Vector3.FromArray(node.translation);
  4254. }
  4255. if (node.rotation) {
  4256. rotation = babylonjs_1.Quaternion.FromArray(node.rotation);
  4257. }
  4258. if (node.scale) {
  4259. scaling = babylonjs_1.Vector3.FromArray(node.scale);
  4260. }
  4261. }
  4262. babylonNode.position = position;
  4263. babylonNode.rotationQuaternion = rotation;
  4264. babylonNode.scaling = scaling;
  4265. };
  4266. GLTFLoader.prototype._loadSkinAsync = function (context, node, skin) {
  4267. var _this = this;
  4268. var assignSkeleton = function (skeleton) {
  4269. _this._forEachPrimitive(node, function (babylonMesh) {
  4270. babylonMesh.skeleton = skeleton;
  4271. });
  4272. // Ignore the TRS of skinned nodes.
  4273. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  4274. node._babylonMesh.position = babylonjs_1.Vector3.Zero();
  4275. node._babylonMesh.rotationQuaternion = babylonjs_1.Quaternion.Identity();
  4276. node._babylonMesh.scaling = babylonjs_1.Vector3.One();
  4277. };
  4278. if (skin._promise) {
  4279. return skin._promise.then(function () {
  4280. assignSkeleton(skin._babylonSkeleton);
  4281. });
  4282. }
  4283. var skeletonId = "skeleton" + skin.index;
  4284. var babylonSkeleton = new babylonjs_1.Skeleton(skin.name || skeletonId, skeletonId, this.babylonScene);
  4285. skin._babylonSkeleton = babylonSkeleton;
  4286. this._loadBones(context, skin);
  4287. assignSkeleton(babylonSkeleton);
  4288. return (skin._promise = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  4289. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  4290. }));
  4291. };
  4292. GLTFLoader.prototype._loadBones = function (context, skin) {
  4293. var babylonBones = {};
  4294. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  4295. var index = _a[_i];
  4296. var node = ArrayItem.Get(context + "/joints/" + index, this.gltf.nodes, index);
  4297. this._loadBone(node, skin, babylonBones);
  4298. }
  4299. };
  4300. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  4301. var babylonBone = babylonBones[node.index];
  4302. if (babylonBone) {
  4303. return babylonBone;
  4304. }
  4305. var babylonParentBone = null;
  4306. if (node.parent && node.parent._babylonMesh !== this._rootBabylonMesh) {
  4307. babylonParentBone = this._loadBone(node.parent, skin, babylonBones);
  4308. }
  4309. var boneIndex = skin.joints.indexOf(node.index);
  4310. babylonBone = new babylonjs_1.Bone(node.name || "joint" + node.index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  4311. babylonBones[node.index] = babylonBone;
  4312. node._babylonBones = node._babylonBones || [];
  4313. node._babylonBones.push(babylonBone);
  4314. return babylonBone;
  4315. };
  4316. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  4317. if (skin.inverseBindMatrices == undefined) {
  4318. return Promise.resolve(null);
  4319. }
  4320. var accessor = ArrayItem.Get(context + "/inverseBindMatrices", this.gltf.accessors, skin.inverseBindMatrices);
  4321. return this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor);
  4322. };
  4323. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  4324. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  4325. var babylonBone = _a[_i];
  4326. var baseMatrix = babylonjs_1.Matrix.Identity();
  4327. var boneIndex = babylonBone._index;
  4328. if (inverseBindMatricesData && boneIndex !== -1) {
  4329. babylonjs_1.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  4330. baseMatrix.invertToRef(baseMatrix);
  4331. }
  4332. var babylonParentBone = babylonBone.getParent();
  4333. if (babylonParentBone) {
  4334. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  4335. }
  4336. babylonBone.updateMatrix(baseMatrix, false, false);
  4337. babylonBone._updateDifferenceMatrix(undefined, false);
  4338. }
  4339. };
  4340. GLTFLoader.prototype._getNodeMatrix = function (node) {
  4341. return node.matrix ?
  4342. babylonjs_1.Matrix.FromArray(node.matrix) :
  4343. babylonjs_1.Matrix.Compose(node.scale ? babylonjs_1.Vector3.FromArray(node.scale) : babylonjs_1.Vector3.One(), node.rotation ? babylonjs_1.Quaternion.FromArray(node.rotation) : babylonjs_1.Quaternion.Identity(), node.translation ? babylonjs_1.Vector3.FromArray(node.translation) : babylonjs_1.Vector3.Zero());
  4344. };
  4345. /**
  4346. * Loads a glTF camera.
  4347. * @param context The context when loading the asset
  4348. * @param camera The glTF camera property
  4349. * @param assign A function called synchronously after parsing the glTF properties
  4350. * @returns A promise that resolves with the loaded Babylon camera when the load is complete
  4351. */
  4352. GLTFLoader.prototype.loadCameraAsync = function (context, camera, assign) {
  4353. if (assign === void 0) { assign = function () { }; }
  4354. var extensionPromise = this._extensionsLoadCameraAsync(context, camera, assign);
  4355. if (extensionPromise) {
  4356. return extensionPromise;
  4357. }
  4358. var promises = new Array();
  4359. this.logOpen(context + " " + (camera.name || ""));
  4360. var babylonCamera = new babylonjs_1.FreeCamera(camera.name || "camera" + camera.index, babylonjs_1.Vector3.Zero(), this.babylonScene, false);
  4361. babylonCamera.rotation = new babylonjs_1.Vector3(0, Math.PI, 0);
  4362. switch (camera.type) {
  4363. case "perspective" /* PERSPECTIVE */: {
  4364. var perspective = camera.perspective;
  4365. if (!perspective) {
  4366. throw new Error(context + ": Camera perspective properties are missing");
  4367. }
  4368. babylonCamera.fov = perspective.yfov;
  4369. babylonCamera.minZ = perspective.znear;
  4370. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  4371. break;
  4372. }
  4373. case "orthographic" /* ORTHOGRAPHIC */: {
  4374. if (!camera.orthographic) {
  4375. throw new Error(context + ": Camera orthographic properties are missing");
  4376. }
  4377. babylonCamera.mode = babylonjs_1.Camera.ORTHOGRAPHIC_CAMERA;
  4378. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  4379. babylonCamera.orthoRight = camera.orthographic.xmag;
  4380. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  4381. babylonCamera.orthoTop = camera.orthographic.ymag;
  4382. babylonCamera.minZ = camera.orthographic.znear;
  4383. babylonCamera.maxZ = camera.orthographic.zfar;
  4384. break;
  4385. }
  4386. default: {
  4387. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  4388. }
  4389. }
  4390. assign(babylonCamera);
  4391. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  4392. return Promise.all(promises).then(function () {
  4393. return babylonCamera;
  4394. });
  4395. };
  4396. GLTFLoader.prototype._loadAnimationsAsync = function () {
  4397. var animations = this.gltf.animations;
  4398. if (!animations) {
  4399. return Promise.resolve();
  4400. }
  4401. var promises = new Array();
  4402. for (var index = 0; index < animations.length; index++) {
  4403. var animation = animations[index];
  4404. promises.push(this.loadAnimationAsync("#/animations/" + animation.index, animation));
  4405. }
  4406. return Promise.all(promises).then(function () { });
  4407. };
  4408. /**
  4409. * Loads a glTF animation.
  4410. * @param context The context when loading the asset
  4411. * @param animation The glTF animation property
  4412. * @returns A promise that resolves with the loaded Babylon animation group when the load is complete
  4413. */
  4414. GLTFLoader.prototype.loadAnimationAsync = function (context, animation) {
  4415. var promise = this._extensionsLoadAnimationAsync(context, animation);
  4416. if (promise) {
  4417. return promise;
  4418. }
  4419. var babylonAnimationGroup = new babylonjs_1.AnimationGroup(animation.name || "animation" + animation.index, this.babylonScene);
  4420. animation._babylonAnimationGroup = babylonAnimationGroup;
  4421. var promises = new Array();
  4422. ArrayItem.Assign(animation.channels);
  4423. ArrayItem.Assign(animation.samplers);
  4424. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  4425. var channel = _a[_i];
  4426. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel.index, context, animation, channel, babylonAnimationGroup));
  4427. }
  4428. return Promise.all(promises).then(function () {
  4429. babylonAnimationGroup.normalize(0);
  4430. return babylonAnimationGroup;
  4431. });
  4432. };
  4433. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  4434. var _this = this;
  4435. if (channel.target.node == undefined) {
  4436. return Promise.resolve();
  4437. }
  4438. var targetNode = ArrayItem.Get(context + "/target/node", this.gltf.nodes, channel.target.node);
  4439. // Ignore animations that have no animation targets.
  4440. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  4441. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  4442. return Promise.resolve();
  4443. }
  4444. // Ignore animations targeting TRS of skinned nodes.
  4445. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  4446. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  4447. return Promise.resolve();
  4448. }
  4449. var sampler = ArrayItem.Get(context + "/sampler", animation.samplers, channel.sampler);
  4450. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  4451. var targetPath;
  4452. var animationType;
  4453. switch (channel.target.path) {
  4454. case "translation" /* TRANSLATION */: {
  4455. targetPath = "position";
  4456. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  4457. break;
  4458. }
  4459. case "rotation" /* ROTATION */: {
  4460. targetPath = "rotationQuaternion";
  4461. animationType = babylonjs_1.Animation.ANIMATIONTYPE_QUATERNION;
  4462. break;
  4463. }
  4464. case "scale" /* SCALE */: {
  4465. targetPath = "scaling";
  4466. animationType = babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3;
  4467. break;
  4468. }
  4469. case "weights" /* WEIGHTS */: {
  4470. targetPath = "influence";
  4471. animationType = babylonjs_1.Animation.ANIMATIONTYPE_FLOAT;
  4472. break;
  4473. }
  4474. default: {
  4475. throw new Error(context + "/target/path: Invalid value (" + channel.target.path + ")");
  4476. }
  4477. }
  4478. var outputBufferOffset = 0;
  4479. var getNextOutputValue;
  4480. switch (targetPath) {
  4481. case "position": {
  4482. getNextOutputValue = function () {
  4483. var value = babylonjs_1.Vector3.FromArray(data.output, outputBufferOffset);
  4484. outputBufferOffset += 3;
  4485. return value;
  4486. };
  4487. break;
  4488. }
  4489. case "rotationQuaternion": {
  4490. getNextOutputValue = function () {
  4491. var value = babylonjs_1.Quaternion.FromArray(data.output, outputBufferOffset);
  4492. outputBufferOffset += 4;
  4493. return value;
  4494. };
  4495. break;
  4496. }
  4497. case "scaling": {
  4498. getNextOutputValue = function () {
  4499. var value = babylonjs_1.Vector3.FromArray(data.output, outputBufferOffset);
  4500. outputBufferOffset += 3;
  4501. return value;
  4502. };
  4503. break;
  4504. }
  4505. case "influence": {
  4506. getNextOutputValue = function () {
  4507. var value = new Array(targetNode._numMorphTargets);
  4508. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  4509. value[i] = data.output[outputBufferOffset++];
  4510. }
  4511. return value;
  4512. };
  4513. break;
  4514. }
  4515. }
  4516. var getNextKey;
  4517. switch (data.interpolation) {
  4518. case "STEP" /* STEP */: {
  4519. getNextKey = function (frameIndex) { return ({
  4520. frame: data.input[frameIndex],
  4521. value: getNextOutputValue(),
  4522. interpolation: babylonjs_1.AnimationKeyInterpolation.STEP
  4523. }); };
  4524. break;
  4525. }
  4526. case "LINEAR" /* LINEAR */: {
  4527. getNextKey = function (frameIndex) { return ({
  4528. frame: data.input[frameIndex],
  4529. value: getNextOutputValue()
  4530. }); };
  4531. break;
  4532. }
  4533. case "CUBICSPLINE" /* CUBICSPLINE */: {
  4534. getNextKey = function (frameIndex) { return ({
  4535. frame: data.input[frameIndex],
  4536. inTangent: getNextOutputValue(),
  4537. value: getNextOutputValue(),
  4538. outTangent: getNextOutputValue()
  4539. }); };
  4540. break;
  4541. }
  4542. }
  4543. var keys = new Array(data.input.length);
  4544. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  4545. keys[frameIndex] = getNextKey(frameIndex);
  4546. }
  4547. if (targetPath === "influence") {
  4548. var _loop_2 = function (targetIndex) {
  4549. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  4550. var babylonAnimation = new babylonjs_1.Animation(animationName, targetPath, 1, animationType);
  4551. babylonAnimation.setKeys(keys.map(function (key) { return ({
  4552. frame: key.frame,
  4553. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  4554. value: key.value[targetIndex],
  4555. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  4556. }); }));
  4557. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  4558. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  4559. var babylonAnimationClone = babylonAnimation.clone();
  4560. morphTarget.animations.push(babylonAnimationClone);
  4561. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  4562. });
  4563. };
  4564. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  4565. _loop_2(targetIndex);
  4566. }
  4567. }
  4568. else {
  4569. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  4570. var babylonAnimation = new babylonjs_1.Animation(animationName, targetPath, 1, animationType);
  4571. babylonAnimation.setKeys(keys);
  4572. if (targetNode._babylonBones) {
  4573. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  4574. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  4575. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  4576. babylonAnimationTarget.animations.push(babylonAnimation);
  4577. }
  4578. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  4579. }
  4580. else {
  4581. targetNode._babylonMesh.animations.push(babylonAnimation);
  4582. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  4583. }
  4584. }
  4585. });
  4586. };
  4587. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  4588. if (sampler._data) {
  4589. return sampler._data;
  4590. }
  4591. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  4592. switch (interpolation) {
  4593. case "STEP" /* STEP */:
  4594. case "LINEAR" /* LINEAR */:
  4595. case "CUBICSPLINE" /* CUBICSPLINE */: {
  4596. break;
  4597. }
  4598. default: {
  4599. throw new Error(context + "/interpolation: Invalid value (" + sampler.interpolation + ")");
  4600. }
  4601. }
  4602. var inputAccessor = ArrayItem.Get(context + "/input", this.gltf.accessors, sampler.input);
  4603. var outputAccessor = ArrayItem.Get(context + "/output", this.gltf.accessors, sampler.output);
  4604. sampler._data = Promise.all([
  4605. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor.index, inputAccessor),
  4606. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor.index, outputAccessor)
  4607. ]).then(function (_a) {
  4608. var inputData = _a[0], outputData = _a[1];
  4609. return {
  4610. input: inputData,
  4611. interpolation: interpolation,
  4612. output: outputData,
  4613. };
  4614. });
  4615. return sampler._data;
  4616. };
  4617. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  4618. if (buffer._data) {
  4619. return buffer._data;
  4620. }
  4621. if (!buffer.uri) {
  4622. throw new Error(context + "/uri: Value is missing");
  4623. }
  4624. buffer._data = this.loadUriAsync(context + "/uri", buffer.uri);
  4625. return buffer._data;
  4626. };
  4627. /**
  4628. * Loads a glTF buffer view.
  4629. * @param context The context when loading the asset
  4630. * @param bufferView The glTF buffer view property
  4631. * @returns A promise that resolves with the loaded data when the load is complete
  4632. */
  4633. GLTFLoader.prototype.loadBufferViewAsync = function (context, bufferView) {
  4634. if (bufferView._data) {
  4635. return bufferView._data;
  4636. }
  4637. var buffer = ArrayItem.Get(context + "/buffer", this.gltf.buffers, bufferView.buffer);
  4638. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer.index, buffer).then(function (data) {
  4639. try {
  4640. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  4641. }
  4642. catch (e) {
  4643. throw new Error(context + ": " + e.message);
  4644. }
  4645. });
  4646. return bufferView._data;
  4647. };
  4648. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  4649. if (accessor.type !== "SCALAR" /* SCALAR */) {
  4650. throw new Error(context + "/type: Invalid value " + accessor.type);
  4651. }
  4652. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  4653. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  4654. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  4655. throw new Error(context + "/componentType: Invalid value " + accessor.componentType);
  4656. }
  4657. if (accessor._data) {
  4658. return accessor._data;
  4659. }
  4660. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  4661. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  4662. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  4663. });
  4664. return accessor._data;
  4665. };
  4666. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  4667. // TODO: support normalized and stride
  4668. var _this = this;
  4669. if (accessor.componentType !== 5126 /* FLOAT */) {
  4670. throw new Error("Invalid component type " + accessor.componentType);
  4671. }
  4672. if (accessor._data) {
  4673. return accessor._data;
  4674. }
  4675. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  4676. var length = numComponents * accessor.count;
  4677. if (accessor.bufferView == undefined) {
  4678. accessor._data = Promise.resolve(new Float32Array(length));
  4679. }
  4680. else {
  4681. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  4682. accessor._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  4683. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  4684. });
  4685. }
  4686. if (accessor.sparse) {
  4687. var sparse_1 = accessor.sparse;
  4688. accessor._data = accessor._data.then(function (data) {
  4689. var indicesBufferView = ArrayItem.Get(context + "/sparse/indices/bufferView", _this.gltf.bufferViews, sparse_1.indices.bufferView);
  4690. var valuesBufferView = ArrayItem.Get(context + "/sparse/values/bufferView", _this.gltf.bufferViews, sparse_1.values.bufferView);
  4691. return Promise.all([
  4692. _this.loadBufferViewAsync("#/bufferViews/" + indicesBufferView.index, indicesBufferView),
  4693. _this.loadBufferViewAsync("#/bufferViews/" + valuesBufferView.index, valuesBufferView)
  4694. ]).then(function (_a) {
  4695. var indicesData = _a[0], valuesData = _a[1];
  4696. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  4697. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  4698. var valuesIndex = 0;
  4699. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  4700. var dataIndex = indices[indicesIndex] * numComponents;
  4701. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  4702. data[dataIndex++] = values[valuesIndex++];
  4703. }
  4704. }
  4705. return data;
  4706. });
  4707. });
  4708. }
  4709. return accessor._data;
  4710. };
  4711. GLTFLoader.prototype._loadVertexBufferViewAsync = function (bufferView, kind) {
  4712. var _this = this;
  4713. if (bufferView._babylonBuffer) {
  4714. return bufferView._babylonBuffer;
  4715. }
  4716. bufferView._babylonBuffer = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView).then(function (data) {
  4717. return new babylonjs_1.Buffer(_this.babylonScene.getEngine(), data, false);
  4718. });
  4719. return bufferView._babylonBuffer;
  4720. };
  4721. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  4722. var _this = this;
  4723. if (accessor._babylonVertexBuffer) {
  4724. return accessor._babylonVertexBuffer;
  4725. }
  4726. if (accessor.sparse) {
  4727. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  4728. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  4729. });
  4730. }
  4731. // HACK: If byte offset is not a multiple of component type byte length then load as a float array instead of using Babylon buffers.
  4732. else if (accessor.byteOffset && accessor.byteOffset % babylonjs_1.VertexBuffer.GetTypeByteLength(accessor.componentType) !== 0) {
  4733. babylonjs_1.Tools.Warn("Accessor byte offset is not a multiple of component type byte length");
  4734. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync("#/accessors/" + accessor.index, accessor).then(function (data) {
  4735. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), data, kind, false);
  4736. });
  4737. }
  4738. else {
  4739. var bufferView_1 = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, accessor.bufferView);
  4740. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync(bufferView_1, kind).then(function (babylonBuffer) {
  4741. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  4742. return new babylonjs_1.VertexBuffer(_this.babylonScene.getEngine(), babylonBuffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  4743. });
  4744. }
  4745. return accessor._babylonVertexBuffer;
  4746. };
  4747. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, properties, babylonMaterial) {
  4748. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  4749. throw new Error(context + ": Material type not supported");
  4750. }
  4751. var promises = new Array();
  4752. if (properties) {
  4753. if (properties.baseColorFactor) {
  4754. babylonMaterial.albedoColor = babylonjs_1.Color3.FromArray(properties.baseColorFactor);
  4755. babylonMaterial.alpha = properties.baseColorFactor[3];
  4756. }
  4757. else {
  4758. babylonMaterial.albedoColor = babylonjs_1.Color3.White();
  4759. }
  4760. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  4761. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  4762. if (properties.baseColorTexture) {
  4763. promises.push(this.loadTextureInfoAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  4764. babylonMaterial.albedoTexture = texture;
  4765. }));
  4766. }
  4767. if (properties.metallicRoughnessTexture) {
  4768. promises.push(this.loadTextureInfoAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  4769. babylonMaterial.metallicTexture = texture;
  4770. }));
  4771. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  4772. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  4773. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  4774. }
  4775. }
  4776. return Promise.all(promises).then(function () { });
  4777. };
  4778. /** @hidden */
  4779. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  4780. if (assign === void 0) { assign = function () { }; }
  4781. var extensionPromise = this._extensionsLoadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign);
  4782. if (extensionPromise) {
  4783. return extensionPromise;
  4784. }
  4785. material._babylonData = material._babylonData || {};
  4786. var babylonData = material._babylonData[babylonDrawMode];
  4787. if (!babylonData) {
  4788. this.logOpen(context + " " + (material.name || ""));
  4789. var babylonMaterial = this.createMaterial(context, material, babylonDrawMode);
  4790. babylonData = {
  4791. material: babylonMaterial,
  4792. meshes: [],
  4793. promise: this.loadMaterialPropertiesAsync(context, material, babylonMaterial)
  4794. };
  4795. material._babylonData[babylonDrawMode] = babylonData;
  4796. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  4797. this.logClose();
  4798. }
  4799. babylonData.meshes.push(babylonMesh);
  4800. babylonMesh.onDisposeObservable.addOnce(function () {
  4801. var index = babylonData.meshes.indexOf(babylonMesh);
  4802. if (index !== -1) {
  4803. babylonData.meshes.splice(index, 1);
  4804. }
  4805. });
  4806. assign(babylonData.material);
  4807. return babylonData.promise.then(function () {
  4808. return babylonData.material;
  4809. });
  4810. };
  4811. GLTFLoader.prototype._createDefaultMaterial = function (name, babylonDrawMode) {
  4812. var babylonMaterial = new babylonjs_1.PBRMaterial(name, this.babylonScene);
  4813. babylonMaterial.sideOrientation = this.babylonScene.useRightHandedSystem ? babylonjs_1.Material.CounterClockWiseSideOrientation : babylonjs_1.Material.ClockWiseSideOrientation;
  4814. babylonMaterial.fillMode = babylonDrawMode;
  4815. babylonMaterial.enableSpecularAntiAliasing = true;
  4816. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  4817. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  4818. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_OPAQUE;
  4819. babylonMaterial.metallic = 1;
  4820. babylonMaterial.roughness = 1;
  4821. return babylonMaterial;
  4822. };
  4823. /**
  4824. * Creates a Babylon material from a glTF material.
  4825. * @param context The context when loading the asset
  4826. * @param material The glTF material property
  4827. * @param babylonDrawMode The draw mode for the Babylon material
  4828. * @returns The Babylon material
  4829. */
  4830. GLTFLoader.prototype.createMaterial = function (context, material, babylonDrawMode) {
  4831. var extensionPromise = this._extensionsCreateMaterial(context, material, babylonDrawMode);
  4832. if (extensionPromise) {
  4833. return extensionPromise;
  4834. }
  4835. var name = material.name || "material" + material.index;
  4836. return this._createDefaultMaterial(name, babylonDrawMode);
  4837. };
  4838. /**
  4839. * Loads properties from a glTF material into a Babylon material.
  4840. * @param context The context when loading the asset
  4841. * @param material The glTF material property
  4842. * @param babylonMaterial The Babylon material
  4843. * @returns A promise that resolves when the load is complete
  4844. */
  4845. GLTFLoader.prototype.loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  4846. var extensionPromise = this._extensionsLoadMaterialPropertiesAsync(context, material, babylonMaterial);
  4847. if (extensionPromise) {
  4848. return extensionPromise;
  4849. }
  4850. var promises = new Array();
  4851. promises.push(this.loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  4852. if (material.pbrMetallicRoughness) {
  4853. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context + "/pbrMetallicRoughness", material.pbrMetallicRoughness, babylonMaterial));
  4854. }
  4855. this.loadMaterialAlphaProperties(context, material, babylonMaterial);
  4856. return Promise.all(promises).then(function () { });
  4857. };
  4858. /**
  4859. * Loads the normal, occlusion, and emissive properties from a glTF material into a Babylon material.
  4860. * @param context The context when loading the asset
  4861. * @param material The glTF material property
  4862. * @param babylonMaterial The Babylon material
  4863. * @returns A promise that resolves when the load is complete
  4864. */
  4865. GLTFLoader.prototype.loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  4866. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  4867. throw new Error(context + ": Material type not supported");
  4868. }
  4869. var promises = new Array();
  4870. babylonMaterial.emissiveColor = material.emissiveFactor ? babylonjs_1.Color3.FromArray(material.emissiveFactor) : new babylonjs_1.Color3(0, 0, 0);
  4871. if (material.doubleSided) {
  4872. babylonMaterial.backFaceCulling = false;
  4873. babylonMaterial.twoSidedLighting = true;
  4874. }
  4875. if (material.normalTexture) {
  4876. promises.push(this.loadTextureInfoAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  4877. babylonMaterial.bumpTexture = texture;
  4878. }));
  4879. babylonMaterial.invertNormalMapX = !this.babylonScene.useRightHandedSystem;
  4880. babylonMaterial.invertNormalMapY = this.babylonScene.useRightHandedSystem;
  4881. if (material.normalTexture.scale != undefined) {
  4882. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  4883. }
  4884. }
  4885. if (material.occlusionTexture) {
  4886. promises.push(this.loadTextureInfoAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  4887. babylonMaterial.ambientTexture = texture;
  4888. }));
  4889. babylonMaterial.useAmbientInGrayScale = true;
  4890. if (material.occlusionTexture.strength != undefined) {
  4891. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  4892. }
  4893. }
  4894. if (material.emissiveTexture) {
  4895. promises.push(this.loadTextureInfoAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  4896. babylonMaterial.emissiveTexture = texture;
  4897. }));
  4898. }
  4899. return Promise.all(promises).then(function () { });
  4900. };
  4901. /**
  4902. * Loads the alpha properties from a glTF material into a Babylon material.
  4903. * Must be called after the setting the albedo texture of the Babylon material when the material has an albedo texture.
  4904. * @param context The context when loading the asset
  4905. * @param material The glTF material property
  4906. * @param babylonMaterial The Babylon material
  4907. */
  4908. GLTFLoader.prototype.loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  4909. if (!(babylonMaterial instanceof babylonjs_1.PBRMaterial)) {
  4910. throw new Error(context + ": Material type not supported");
  4911. }
  4912. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  4913. switch (alphaMode) {
  4914. case "OPAQUE" /* OPAQUE */: {
  4915. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_OPAQUE;
  4916. break;
  4917. }
  4918. case "MASK" /* MASK */: {
  4919. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_ALPHATEST;
  4920. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  4921. if (babylonMaterial.albedoTexture) {
  4922. babylonMaterial.albedoTexture.hasAlpha = true;
  4923. }
  4924. break;
  4925. }
  4926. case "BLEND" /* BLEND */: {
  4927. babylonMaterial.transparencyMode = babylonjs_1.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  4928. if (babylonMaterial.albedoTexture) {
  4929. babylonMaterial.albedoTexture.hasAlpha = true;
  4930. babylonMaterial.useAlphaFromAlbedoTexture = true;
  4931. }
  4932. break;
  4933. }
  4934. default: {
  4935. throw new Error(context + "/alphaMode: Invalid value (" + material.alphaMode + ")");
  4936. }
  4937. }
  4938. };
  4939. /**
  4940. * Loads a glTF texture info.
  4941. * @param context The context when loading the asset
  4942. * @param textureInfo The glTF texture info property
  4943. * @param assign A function called synchronously after parsing the glTF properties
  4944. * @returns A promise that resolves with the loaded Babylon texture when the load is complete
  4945. */
  4946. GLTFLoader.prototype.loadTextureInfoAsync = function (context, textureInfo, assign) {
  4947. if (assign === void 0) { assign = function () { }; }
  4948. var extensionPromise = this._extensionsLoadTextureInfoAsync(context, textureInfo, assign);
  4949. if (extensionPromise) {
  4950. return extensionPromise;
  4951. }
  4952. this.logOpen("" + context);
  4953. var texture = ArrayItem.Get(context + "/index", this.gltf.textures, textureInfo.index);
  4954. var promise = this._loadTextureAsync("#/textures/" + textureInfo.index, texture, function (babylonTexture) {
  4955. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  4956. assign(babylonTexture);
  4957. });
  4958. this.logClose();
  4959. return promise;
  4960. };
  4961. GLTFLoader.prototype._loadTextureAsync = function (context, texture, assign) {
  4962. var _this = this;
  4963. if (assign === void 0) { assign = function () { }; }
  4964. var promises = new Array();
  4965. this.logOpen(context + " " + (texture.name || ""));
  4966. var sampler = (texture.sampler == undefined ? GLTFLoader._DefaultSampler : ArrayItem.Get(context + "/sampler", this.gltf.samplers, texture.sampler));
  4967. var samplerData = this._loadSampler("#/samplers/" + sampler.index, sampler);
  4968. var deferred = new babylonjs_1.Deferred();
  4969. var babylonTexture = new babylonjs_1.Texture(null, this.babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  4970. if (!_this._disposed) {
  4971. deferred.resolve();
  4972. }
  4973. }, function (message, exception) {
  4974. if (!_this._disposed) {
  4975. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  4976. }
  4977. });
  4978. promises.push(deferred.promise);
  4979. babylonTexture.name = texture.name || "texture" + texture.index;
  4980. babylonTexture.wrapU = samplerData.wrapU;
  4981. babylonTexture.wrapV = samplerData.wrapV;
  4982. var image = ArrayItem.Get(context + "/source", this.gltf.images, texture.source);
  4983. promises.push(this.loadImageAsync("#/images/" + image.index, image).then(function (data) {
  4984. var name = image.uri || _this._fileName + "#image" + image.index;
  4985. var dataUrl = "data:" + _this._uniqueRootUrl + name;
  4986. babylonTexture.updateURL(dataUrl, new Blob([data], { type: image.mimeType }));
  4987. }));
  4988. assign(babylonTexture);
  4989. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  4990. this.logClose();
  4991. return Promise.all(promises).then(function () {
  4992. return babylonTexture;
  4993. });
  4994. };
  4995. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  4996. if (!sampler._data) {
  4997. sampler._data = {
  4998. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  4999. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler),
  5000. wrapU: GLTFLoader._GetTextureWrapMode(context + "/wrapS", sampler.wrapS),
  5001. wrapV: GLTFLoader._GetTextureWrapMode(context + "/wrapT", sampler.wrapT)
  5002. };
  5003. }
  5004. return sampler._data;
  5005. };
  5006. /**
  5007. * Loads a glTF image.
  5008. * @param context The context when loading the asset
  5009. * @param image The glTF image property
  5010. * @returns A promise that resolves with the loaded data when the load is complete
  5011. */
  5012. GLTFLoader.prototype.loadImageAsync = function (context, image) {
  5013. if (!image._data) {
  5014. this.logOpen(context + " " + (image.name || ""));
  5015. if (image.uri) {
  5016. image._data = this.loadUriAsync(context + "/uri", image.uri);
  5017. }
  5018. else {
  5019. var bufferView = ArrayItem.Get(context + "/bufferView", this.gltf.bufferViews, image.bufferView);
  5020. image._data = this.loadBufferViewAsync("#/bufferViews/" + bufferView.index, bufferView);
  5021. }
  5022. this.logClose();
  5023. }
  5024. return image._data;
  5025. };
  5026. /**
  5027. * Loads a glTF uri.
  5028. * @param context The context when loading the asset
  5029. * @param uri The base64 or relative uri
  5030. * @returns A promise that resolves with the loaded data when the load is complete
  5031. */
  5032. GLTFLoader.prototype.loadUriAsync = function (context, uri) {
  5033. var _this = this;
  5034. var extensionPromise = this._extensionsLoadUriAsync(context, uri);
  5035. if (extensionPromise) {
  5036. return extensionPromise;
  5037. }
  5038. if (!GLTFLoader._ValidateUri(uri)) {
  5039. throw new Error(context + ": '" + uri + "' is invalid");
  5040. }
  5041. if (babylonjs_1.Tools.IsBase64(uri)) {
  5042. var data = new Uint8Array(babylonjs_1.Tools.DecodeBase64(uri));
  5043. this.log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  5044. return Promise.resolve(data);
  5045. }
  5046. this.log("Loading " + uri);
  5047. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  5048. return new Promise(function (resolve, reject) {
  5049. if (!_this._disposed) {
  5050. var request_1 = babylonjs_1.Tools.LoadFile(url, function (fileData) {
  5051. if (!_this._disposed) {
  5052. var data = new Uint8Array(fileData);
  5053. _this.log("Loaded " + uri + " (" + data.length + " bytes)");
  5054. resolve(data);
  5055. }
  5056. }, function (event) {
  5057. if (!_this._disposed) {
  5058. if (request_1) {
  5059. request_1._lengthComputable = event.lengthComputable;
  5060. request_1._loaded = event.loaded;
  5061. request_1._total = event.total;
  5062. }
  5063. if (_this._state === glTFFileLoader_1.GLTFLoaderState.LOADING) {
  5064. try {
  5065. _this._onProgress();
  5066. }
  5067. catch (e) {
  5068. reject(e);
  5069. }
  5070. }
  5071. }
  5072. }, _this.babylonScene.offlineProvider, true, function (request, exception) {
  5073. if (!_this._disposed) {
  5074. reject(new babylonjs_1.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  5075. }
  5076. });
  5077. _this._requests.push(request_1);
  5078. }
  5079. });
  5080. });
  5081. };
  5082. GLTFLoader.prototype._onProgress = function () {
  5083. if (!this._progressCallback) {
  5084. return;
  5085. }
  5086. var lengthComputable = true;
  5087. var loaded = 0;
  5088. var total = 0;
  5089. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  5090. var request = _a[_i];
  5091. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  5092. return;
  5093. }
  5094. lengthComputable = lengthComputable && request._lengthComputable;
  5095. loaded += request._loaded;
  5096. total += request._total;
  5097. }
  5098. this._progressCallback(new babylonjs_1.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  5099. };
  5100. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  5101. // Set defaults if undefined
  5102. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  5103. switch (mode) {
  5104. case 33071 /* CLAMP_TO_EDGE */: return babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  5105. case 33648 /* MIRRORED_REPEAT */: return babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  5106. case 10497 /* REPEAT */: return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  5107. default:
  5108. babylonjs_1.Tools.Warn(context + ": Invalid value (" + mode + ")");
  5109. return babylonjs_1.Texture.WRAP_ADDRESSMODE;
  5110. }
  5111. };
  5112. GLTFLoader._GetTextureSamplingMode = function (context, sampler) {
  5113. // Set defaults if undefined
  5114. var magFilter = sampler.magFilter == undefined ? 9729 /* LINEAR */ : sampler.magFilter;
  5115. var minFilter = sampler.minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : sampler.minFilter;
  5116. if (magFilter === 9729 /* LINEAR */) {
  5117. switch (minFilter) {
  5118. case 9728 /* NEAREST */: return babylonjs_1.Texture.LINEAR_NEAREST;
  5119. case 9729 /* LINEAR */: return babylonjs_1.Texture.LINEAR_LINEAR;
  5120. case 9984 /* NEAREST_MIPMAP_NEAREST */: return babylonjs_1.Texture.LINEAR_NEAREST_MIPNEAREST;
  5121. case 9985 /* LINEAR_MIPMAP_NEAREST */: return babylonjs_1.Texture.LINEAR_LINEAR_MIPNEAREST;
  5122. case 9986 /* NEAREST_MIPMAP_LINEAR */: return babylonjs_1.Texture.LINEAR_NEAREST_MIPLINEAR;
  5123. case 9987 /* LINEAR_MIPMAP_LINEAR */: return babylonjs_1.Texture.LINEAR_LINEAR_MIPLINEAR;
  5124. default:
  5125. babylonjs_1.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  5126. return babylonjs_1.Texture.LINEAR_LINEAR_MIPLINEAR;
  5127. }
  5128. }
  5129. else {
  5130. if (magFilter !== 9728 /* NEAREST */) {
  5131. babylonjs_1.Tools.Warn(context + "/magFilter: Invalid value (" + magFilter + ")");
  5132. }
  5133. switch (minFilter) {
  5134. case 9728 /* NEAREST */: return babylonjs_1.Texture.NEAREST_NEAREST;
  5135. case 9729 /* LINEAR */: return babylonjs_1.Texture.NEAREST_LINEAR;
  5136. case 9984 /* NEAREST_MIPMAP_NEAREST */: return babylonjs_1.Texture.NEAREST_NEAREST_MIPNEAREST;
  5137. case 9985 /* LINEAR_MIPMAP_NEAREST */: return babylonjs_1.Texture.NEAREST_LINEAR_MIPNEAREST;
  5138. case 9986 /* NEAREST_MIPMAP_LINEAR */: return babylonjs_1.Texture.NEAREST_NEAREST_MIPLINEAR;
  5139. case 9987 /* LINEAR_MIPMAP_LINEAR */: return babylonjs_1.Texture.NEAREST_LINEAR_MIPLINEAR;
  5140. default:
  5141. babylonjs_1.Tools.Warn(context + "/minFilter: Invalid value (" + minFilter + ")");
  5142. return babylonjs_1.Texture.NEAREST_NEAREST_MIPNEAREST;
  5143. }
  5144. }
  5145. };
  5146. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  5147. var buffer = bufferView.buffer;
  5148. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  5149. try {
  5150. switch (componentType) {
  5151. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  5152. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  5153. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  5154. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  5155. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  5156. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  5157. default: throw new Error("Invalid component type " + componentType);
  5158. }
  5159. }
  5160. catch (e) {
  5161. throw new Error(context + ": " + e);
  5162. }
  5163. };
  5164. GLTFLoader._GetNumComponents = function (context, type) {
  5165. switch (type) {
  5166. case "SCALAR": return 1;
  5167. case "VEC2": return 2;
  5168. case "VEC3": return 3;
  5169. case "VEC4": return 4;
  5170. case "MAT2": return 4;
  5171. case "MAT3": return 9;
  5172. case "MAT4": return 16;
  5173. }
  5174. throw new Error(context + ": Invalid type (" + type + ")");
  5175. };
  5176. GLTFLoader._ValidateUri = function (uri) {
  5177. return (babylonjs_1.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  5178. };
  5179. GLTFLoader._GetDrawMode = function (context, mode) {
  5180. if (mode == undefined) {
  5181. mode = 4 /* TRIANGLES */;
  5182. }
  5183. switch (mode) {
  5184. case 0 /* POINTS */: return babylonjs_1.Material.PointListDrawMode;
  5185. case 1 /* LINES */: return babylonjs_1.Material.LineListDrawMode;
  5186. case 2 /* LINE_LOOP */: return babylonjs_1.Material.LineLoopDrawMode;
  5187. case 3 /* LINE_STRIP */: return babylonjs_1.Material.LineStripDrawMode;
  5188. case 4 /* TRIANGLES */: return babylonjs_1.Material.TriangleFillMode;
  5189. case 5 /* TRIANGLE_STRIP */: return babylonjs_1.Material.TriangleStripDrawMode;
  5190. case 6 /* TRIANGLE_FAN */: return babylonjs_1.Material.TriangleFanDrawMode;
  5191. }
  5192. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  5193. };
  5194. GLTFLoader.prototype._compileMaterialsAsync = function () {
  5195. var _this = this;
  5196. this._parent._startPerformanceCounter("Compile materials");
  5197. var promises = new Array();
  5198. if (this.gltf.materials) {
  5199. for (var _i = 0, _a = this.gltf.materials; _i < _a.length; _i++) {
  5200. var material = _a[_i];
  5201. if (material._babylonData) {
  5202. for (var babylonDrawMode in material._babylonData) {
  5203. var babylonData = material._babylonData[babylonDrawMode];
  5204. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  5205. var babylonMesh = _c[_b];
  5206. // Ensure nonUniformScaling is set if necessary.
  5207. babylonMesh.computeWorldMatrix(true);
  5208. var babylonMaterial = babylonData.material;
  5209. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  5210. if (this._parent.useClipPlane) {
  5211. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  5212. }
  5213. }
  5214. }
  5215. }
  5216. }
  5217. }
  5218. return Promise.all(promises).then(function () {
  5219. _this._parent._endPerformanceCounter("Compile materials");
  5220. });
  5221. };
  5222. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  5223. var _this = this;
  5224. this._parent._startPerformanceCounter("Compile shadow generators");
  5225. var promises = new Array();
  5226. var lights = this.babylonScene.lights;
  5227. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  5228. var light = lights_1[_i];
  5229. var generator = light.getShadowGenerator();
  5230. if (generator) {
  5231. promises.push(generator.forceCompilationAsync());
  5232. }
  5233. }
  5234. return Promise.all(promises).then(function () {
  5235. _this._parent._endPerformanceCounter("Compile shadow generators");
  5236. });
  5237. };
  5238. GLTFLoader.prototype._forEachExtensions = function (action) {
  5239. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  5240. var name_4 = _a[_i];
  5241. var extension = this._extensions[name_4];
  5242. if (extension.enabled) {
  5243. action(extension);
  5244. }
  5245. }
  5246. };
  5247. GLTFLoader.prototype._applyExtensions = function (property, actionAsync) {
  5248. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  5249. var name_5 = _a[_i];
  5250. var extension = this._extensions[name_5];
  5251. if (extension.enabled) {
  5252. var loaderProperty = property;
  5253. loaderProperty._activeLoaderExtensions = loaderProperty._activeLoaderExtensions || {};
  5254. var activeLoaderExtensions = loaderProperty._activeLoaderExtensions;
  5255. if (!activeLoaderExtensions[name_5]) {
  5256. activeLoaderExtensions[name_5] = true;
  5257. try {
  5258. var result = actionAsync(extension);
  5259. if (result) {
  5260. return result;
  5261. }
  5262. }
  5263. finally {
  5264. delete activeLoaderExtensions[name_5];
  5265. }
  5266. }
  5267. }
  5268. }
  5269. return null;
  5270. };
  5271. GLTFLoader.prototype._extensionsOnLoading = function () {
  5272. this._forEachExtensions(function (extension) { return extension.onLoading && extension.onLoading(); });
  5273. };
  5274. GLTFLoader.prototype._extensionsOnReady = function () {
  5275. this._forEachExtensions(function (extension) { return extension.onReady && extension.onReady(); });
  5276. };
  5277. GLTFLoader.prototype._extensionsLoadSceneAsync = function (context, scene) {
  5278. return this._applyExtensions(scene, function (extension) { return extension.loadSceneAsync && extension.loadSceneAsync(context, scene); });
  5279. };
  5280. GLTFLoader.prototype._extensionsLoadNodeAsync = function (context, node, assign) {
  5281. return this._applyExtensions(node, function (extension) { return extension.loadNodeAsync && extension.loadNodeAsync(context, node, assign); });
  5282. };
  5283. GLTFLoader.prototype._extensionsLoadCameraAsync = function (context, camera, assign) {
  5284. return this._applyExtensions(camera, function (extension) { return extension.loadCameraAsync && extension.loadCameraAsync(context, camera, assign); });
  5285. };
  5286. GLTFLoader.prototype._extensionsLoadVertexDataAsync = function (context, primitive, babylonMesh) {
  5287. return this._applyExtensions(primitive, function (extension) { return extension._loadVertexDataAsync && extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  5288. };
  5289. GLTFLoader.prototype._extensionsLoadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  5290. return this._applyExtensions(material, function (extension) { return extension._loadMaterialAsync && extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  5291. };
  5292. GLTFLoader.prototype._extensionsCreateMaterial = function (context, material, babylonDrawMode) {
  5293. return this._applyExtensions({}, function (extension) { return extension.createMaterial && extension.createMaterial(context, material, babylonDrawMode); });
  5294. };
  5295. GLTFLoader.prototype._extensionsLoadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  5296. return this._applyExtensions(material, function (extension) { return extension.loadMaterialPropertiesAsync && extension.loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  5297. };
  5298. GLTFLoader.prototype._extensionsLoadTextureInfoAsync = function (context, textureInfo, assign) {
  5299. return this._applyExtensions(textureInfo, function (extension) { return extension.loadTextureInfoAsync && extension.loadTextureInfoAsync(context, textureInfo, assign); });
  5300. };
  5301. GLTFLoader.prototype._extensionsLoadAnimationAsync = function (context, animation) {
  5302. return this._applyExtensions(animation, function (extension) { return extension.loadAnimationAsync && extension.loadAnimationAsync(context, animation); });
  5303. };
  5304. GLTFLoader.prototype._extensionsLoadUriAsync = function (context, uri) {
  5305. return this._applyExtensions({}, function (extension) { return extension._loadUriAsync && extension._loadUriAsync(context, uri); });
  5306. };
  5307. /**
  5308. * Helper method called by a loader extension to load an glTF extension.
  5309. * @param context The context when loading the asset
  5310. * @param property The glTF property to load the extension from
  5311. * @param extensionName The name of the extension to load
  5312. * @param actionAsync The action to run
  5313. * @returns The promise returned by actionAsync or null if the extension does not exist
  5314. */
  5315. GLTFLoader.LoadExtensionAsync = function (context, property, extensionName, actionAsync) {
  5316. if (!property.extensions) {
  5317. return null;
  5318. }
  5319. var extensions = property.extensions;
  5320. var extension = extensions[extensionName];
  5321. if (!extension) {
  5322. return null;
  5323. }
  5324. return actionAsync(context + "/extensions/" + extensionName, extension);
  5325. };
  5326. /**
  5327. * Helper method called by a loader extension to load a glTF extra.
  5328. * @param context The context when loading the asset
  5329. * @param property The glTF property to load the extra from
  5330. * @param extensionName The name of the extension to load
  5331. * @param actionAsync The action to run
  5332. * @returns The promise returned by actionAsync or null if the extra does not exist
  5333. */
  5334. GLTFLoader.LoadExtraAsync = function (context, property, extensionName, actionAsync) {
  5335. if (!property.extras) {
  5336. return null;
  5337. }
  5338. var extras = property.extras;
  5339. var extra = extras[extensionName];
  5340. if (!extra) {
  5341. return null;
  5342. }
  5343. return actionAsync(context + "/extras/" + extensionName, extra);
  5344. };
  5345. /**
  5346. * Increments the indentation level and logs a message.
  5347. * @param message The message to log
  5348. */
  5349. GLTFLoader.prototype.logOpen = function (message) {
  5350. this._parent._logOpen(message);
  5351. };
  5352. /**
  5353. * Decrements the indentation level.
  5354. */
  5355. GLTFLoader.prototype.logClose = function () {
  5356. this._parent._logClose();
  5357. };
  5358. /**
  5359. * Logs a message
  5360. * @param message The message to log
  5361. */
  5362. GLTFLoader.prototype.log = function (message) {
  5363. this._parent._log(message);
  5364. };
  5365. /**
  5366. * Starts a performance counter.
  5367. * @param counterName The name of the performance counter
  5368. */
  5369. GLTFLoader.prototype.startPerformanceCounter = function (counterName) {
  5370. this._parent._startPerformanceCounter(counterName);
  5371. };
  5372. /**
  5373. * Ends a performance counter.
  5374. * @param counterName The name of the performance counter
  5375. */
  5376. GLTFLoader.prototype.endPerformanceCounter = function (counterName) {
  5377. this._parent._endPerformanceCounter(counterName);
  5378. };
  5379. GLTFLoader._DefaultSampler = { index: -1 };
  5380. GLTFLoader._ExtensionNames = new Array();
  5381. GLTFLoader._ExtensionFactories = {};
  5382. return GLTFLoader;
  5383. }());
  5384. exports.GLTFLoader = GLTFLoader;
  5385. glTFFileLoader_1.GLTFFileLoader._CreateGLTF2Loader = function (parent) { return new GLTFLoader(parent); };
  5386. /***/ }),
  5387. /***/ "./src/glTF/2.0/glTFLoaderExtension.ts":
  5388. /*!*********************************************!*\
  5389. !*** ./src/glTF/2.0/glTFLoaderExtension.ts ***!
  5390. \*********************************************/
  5391. /*! no static exports found */
  5392. /***/ (function(module, exports, __webpack_require__) {
  5393. "use strict";
  5394. Object.defineProperty(exports, "__esModule", { value: true });
  5395. /** @hidden */
  5396. exports.__IGLTFLoaderExtension = 0; // I am here to allow dts to be created
  5397. /***/ }),
  5398. /***/ "./src/glTF/2.0/glTFLoaderInterfaces.ts":
  5399. /*!**********************************************!*\
  5400. !*** ./src/glTF/2.0/glTFLoaderInterfaces.ts ***!
  5401. \**********************************************/
  5402. /*! no static exports found */
  5403. /***/ (function(module, exports, __webpack_require__) {
  5404. "use strict";
  5405. Object.defineProperty(exports, "__esModule", { value: true });
  5406. /** @hidden */
  5407. exports.__IGLTFLoaderInterfacesV2 = 0; // I am here to allow dts to be created
  5408. /***/ }),
  5409. /***/ "./src/glTF/2.0/index.ts":
  5410. /*!*******************************!*\
  5411. !*** ./src/glTF/2.0/index.ts ***!
  5412. \*******************************/
  5413. /*! no static exports found */
  5414. /***/ (function(module, exports, __webpack_require__) {
  5415. "use strict";
  5416. function __export(m) {
  5417. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  5418. }
  5419. Object.defineProperty(exports, "__esModule", { value: true });
  5420. __export(__webpack_require__(/*! ./glTFLoader */ "./src/glTF/2.0/glTFLoader.ts"));
  5421. __export(__webpack_require__(/*! ./glTFLoaderExtension */ "./src/glTF/2.0/glTFLoaderExtension.ts"));
  5422. __export(__webpack_require__(/*! ./glTFLoaderInterfaces */ "./src/glTF/2.0/glTFLoaderInterfaces.ts"));
  5423. __export(__webpack_require__(/*! ./Extensions */ "./src/glTF/2.0/Extensions/index.ts"));
  5424. /***/ }),
  5425. /***/ "./src/glTF/glTFFileLoader.ts":
  5426. /*!************************************!*\
  5427. !*** ./src/glTF/glTFFileLoader.ts ***!
  5428. \************************************/
  5429. /*! no static exports found */
  5430. /***/ (function(module, exports, __webpack_require__) {
  5431. "use strict";
  5432. Object.defineProperty(exports, "__esModule", { value: true });
  5433. var babylonjs_1 = __webpack_require__(/*! babylonjs */ "babylonjs");
  5434. /**
  5435. * Mode that determines the coordinate system to use.
  5436. */
  5437. var GLTFLoaderCoordinateSystemMode;
  5438. (function (GLTFLoaderCoordinateSystemMode) {
  5439. /**
  5440. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  5441. */
  5442. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  5443. /**
  5444. * Sets the useRightHandedSystem flag on the scene.
  5445. */
  5446. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  5447. })(GLTFLoaderCoordinateSystemMode = exports.GLTFLoaderCoordinateSystemMode || (exports.GLTFLoaderCoordinateSystemMode = {}));
  5448. /**
  5449. * Mode that determines what animations will start.
  5450. */
  5451. var GLTFLoaderAnimationStartMode;
  5452. (function (GLTFLoaderAnimationStartMode) {
  5453. /**
  5454. * No animation will start.
  5455. */
  5456. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  5457. /**
  5458. * The first animation will start.
  5459. */
  5460. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  5461. /**
  5462. * All animations will start.
  5463. */
  5464. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  5465. })(GLTFLoaderAnimationStartMode = exports.GLTFLoaderAnimationStartMode || (exports.GLTFLoaderAnimationStartMode = {}));
  5466. /**
  5467. * Loader state.
  5468. */
  5469. var GLTFLoaderState;
  5470. (function (GLTFLoaderState) {
  5471. /**
  5472. * The asset is loading.
  5473. */
  5474. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  5475. /**
  5476. * The asset is ready for rendering.
  5477. */
  5478. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  5479. /**
  5480. * The asset is completely loaded.
  5481. */
  5482. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  5483. })(GLTFLoaderState = exports.GLTFLoaderState || (exports.GLTFLoaderState = {}));
  5484. /**
  5485. * File loader for loading glTF files into a scene.
  5486. */
  5487. var GLTFFileLoader = /** @class */ (function () {
  5488. function GLTFFileLoader() {
  5489. // --------------
  5490. // Common options
  5491. // --------------
  5492. /**
  5493. * Raised when the asset has been parsed
  5494. */
  5495. this.onParsedObservable = new babylonjs_1.Observable();
  5496. // ----------
  5497. // V2 options
  5498. // ----------
  5499. /**
  5500. * The coordinate system mode. Defaults to AUTO.
  5501. */
  5502. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  5503. /**
  5504. * The animation start mode. Defaults to FIRST.
  5505. */
  5506. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  5507. /**
  5508. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  5509. */
  5510. this.compileMaterials = false;
  5511. /**
  5512. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  5513. */
  5514. this.useClipPlane = false;
  5515. /**
  5516. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  5517. */
  5518. this.compileShadowGenerators = false;
  5519. /**
  5520. * Defines if the Alpha blended materials are only applied as coverage.
  5521. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  5522. * If true, no extra effects are applied to transparent pixels.
  5523. */
  5524. this.transparencyAsCoverage = false;
  5525. /**
  5526. * Function called before loading a url referenced by the asset.
  5527. */
  5528. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  5529. /**
  5530. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  5531. */
  5532. this.onMeshLoadedObservable = new babylonjs_1.Observable();
  5533. /**
  5534. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  5535. */
  5536. this.onTextureLoadedObservable = new babylonjs_1.Observable();
  5537. /**
  5538. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  5539. */
  5540. this.onMaterialLoadedObservable = new babylonjs_1.Observable();
  5541. /**
  5542. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  5543. */
  5544. this.onCameraLoadedObservable = new babylonjs_1.Observable();
  5545. /**
  5546. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  5547. * For assets with LODs, raised when all of the LODs are complete.
  5548. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  5549. */
  5550. this.onCompleteObservable = new babylonjs_1.Observable();
  5551. /**
  5552. * Observable raised when an error occurs.
  5553. */
  5554. this.onErrorObservable = new babylonjs_1.Observable();
  5555. /**
  5556. * Observable raised after the loader is disposed.
  5557. */
  5558. this.onDisposeObservable = new babylonjs_1.Observable();
  5559. /**
  5560. * Observable raised after a loader extension is created.
  5561. * Set additional options for a loader extension in this event.
  5562. */
  5563. this.onExtensionLoadedObservable = new babylonjs_1.Observable();
  5564. /**
  5565. * Defines if the loader should validate the asset.
  5566. */
  5567. this.validate = false;
  5568. /**
  5569. * Observable raised after validation when validate is set to true. The event data is the result of the validation.
  5570. */
  5571. this.onValidatedObservable = new babylonjs_1.Observable();
  5572. this._loader = null;
  5573. /**
  5574. * Name of the loader ("gltf")
  5575. */
  5576. this.name = "gltf";
  5577. /**
  5578. * Supported file extensions of the loader (.gltf, .glb)
  5579. */
  5580. this.extensions = {
  5581. ".gltf": { isBinary: false },
  5582. ".glb": { isBinary: true }
  5583. };
  5584. this._logIndentLevel = 0;
  5585. this._loggingEnabled = false;
  5586. /** @hidden */
  5587. this._log = this._logDisabled;
  5588. this._capturePerformanceCounters = false;
  5589. /** @hidden */
  5590. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  5591. /** @hidden */
  5592. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  5593. }
  5594. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  5595. /**
  5596. * Raised when the asset has been parsed
  5597. */
  5598. set: function (callback) {
  5599. if (this._onParsedObserver) {
  5600. this.onParsedObservable.remove(this._onParsedObserver);
  5601. }
  5602. this._onParsedObserver = this.onParsedObservable.add(callback);
  5603. },
  5604. enumerable: true,
  5605. configurable: true
  5606. });
  5607. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  5608. /**
  5609. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  5610. */
  5611. set: function (callback) {
  5612. if (this._onMeshLoadedObserver) {
  5613. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  5614. }
  5615. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  5616. },
  5617. enumerable: true,
  5618. configurable: true
  5619. });
  5620. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  5621. /**
  5622. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  5623. */
  5624. set: function (callback) {
  5625. if (this._onTextureLoadedObserver) {
  5626. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  5627. }
  5628. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  5629. },
  5630. enumerable: true,
  5631. configurable: true
  5632. });
  5633. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  5634. /**
  5635. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  5636. */
  5637. set: function (callback) {
  5638. if (this._onMaterialLoadedObserver) {
  5639. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  5640. }
  5641. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  5642. },
  5643. enumerable: true,
  5644. configurable: true
  5645. });
  5646. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  5647. /**
  5648. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  5649. */
  5650. set: function (callback) {
  5651. if (this._onCameraLoadedObserver) {
  5652. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  5653. }
  5654. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  5655. },
  5656. enumerable: true,
  5657. configurable: true
  5658. });
  5659. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  5660. /**
  5661. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  5662. * For assets with LODs, raised when all of the LODs are complete.
  5663. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  5664. */
  5665. set: function (callback) {
  5666. if (this._onCompleteObserver) {
  5667. this.onCompleteObservable.remove(this._onCompleteObserver);
  5668. }
  5669. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  5670. },
  5671. enumerable: true,
  5672. configurable: true
  5673. });
  5674. Object.defineProperty(GLTFFileLoader.prototype, "onError", {
  5675. /**
  5676. * Callback raised when an error occurs.
  5677. */
  5678. set: function (callback) {
  5679. if (this._onErrorObserver) {
  5680. this.onErrorObservable.remove(this._onErrorObserver);
  5681. }
  5682. this._onErrorObserver = this.onErrorObservable.add(callback);
  5683. },
  5684. enumerable: true,
  5685. configurable: true
  5686. });
  5687. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  5688. /**
  5689. * Callback raised after the loader is disposed.
  5690. */
  5691. set: function (callback) {
  5692. if (this._onDisposeObserver) {
  5693. this.onDisposeObservable.remove(this._onDisposeObserver);
  5694. }
  5695. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  5696. },
  5697. enumerable: true,
  5698. configurable: true
  5699. });
  5700. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  5701. /**
  5702. * Callback raised after a loader extension is created.
  5703. */
  5704. set: function (callback) {
  5705. if (this._onExtensionLoadedObserver) {
  5706. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  5707. }
  5708. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  5709. },
  5710. enumerable: true,
  5711. configurable: true
  5712. });
  5713. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  5714. /**
  5715. * Defines if the loader logging is enabled.
  5716. */
  5717. get: function () {
  5718. return this._loggingEnabled;
  5719. },
  5720. set: function (value) {
  5721. if (this._loggingEnabled === value) {
  5722. return;
  5723. }
  5724. this._loggingEnabled = value;
  5725. if (this._loggingEnabled) {
  5726. this._log = this._logEnabled;
  5727. }
  5728. else {
  5729. this._log = this._logDisabled;
  5730. }
  5731. },
  5732. enumerable: true,
  5733. configurable: true
  5734. });
  5735. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  5736. /**
  5737. * Defines if the loader should capture performance counters.
  5738. */
  5739. get: function () {
  5740. return this._capturePerformanceCounters;
  5741. },
  5742. set: function (value) {
  5743. if (this._capturePerformanceCounters === value) {
  5744. return;
  5745. }
  5746. this._capturePerformanceCounters = value;
  5747. if (this._capturePerformanceCounters) {
  5748. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  5749. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  5750. }
  5751. else {
  5752. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  5753. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  5754. }
  5755. },
  5756. enumerable: true,
  5757. configurable: true
  5758. });
  5759. Object.defineProperty(GLTFFileLoader.prototype, "onValidated", {
  5760. /**
  5761. * Callback raised after a loader extension is created.
  5762. */
  5763. set: function (callback) {
  5764. if (this._onValidatedObserver) {
  5765. this.onValidatedObservable.remove(this._onValidatedObserver);
  5766. }
  5767. this._onValidatedObserver = this.onValidatedObservable.add(callback);
  5768. },
  5769. enumerable: true,
  5770. configurable: true
  5771. });
  5772. /**
  5773. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  5774. */
  5775. GLTFFileLoader.prototype.dispose = function () {
  5776. if (this._loader) {
  5777. this._loader.dispose();
  5778. this._loader = null;
  5779. }
  5780. this._clear();
  5781. this.onDisposeObservable.notifyObservers(undefined);
  5782. this.onDisposeObservable.clear();
  5783. };
  5784. /** @hidden */
  5785. GLTFFileLoader.prototype._clear = function () {
  5786. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  5787. this.onMeshLoadedObservable.clear();
  5788. this.onTextureLoadedObservable.clear();
  5789. this.onMaterialLoadedObservable.clear();
  5790. this.onCameraLoadedObservable.clear();
  5791. this.onCompleteObservable.clear();
  5792. this.onExtensionLoadedObservable.clear();
  5793. };
  5794. /**
  5795. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  5796. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  5797. * @param scene the scene the meshes should be added to
  5798. * @param data the glTF data to load
  5799. * @param rootUrl root url to load from
  5800. * @param onProgress event that fires when loading progress has occured
  5801. * @param fileName Defines the name of the file to load
  5802. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  5803. */
  5804. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress, fileName) {
  5805. var _this = this;
  5806. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  5807. _this._log("Loading " + (fileName || ""));
  5808. _this._loader = _this._getLoader(loaderData);
  5809. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress, fileName);
  5810. });
  5811. };
  5812. /**
  5813. * Imports all objects from the loaded glTF data and adds them to the scene
  5814. * @param scene the scene the objects should be added to
  5815. * @param data the glTF data to load
  5816. * @param rootUrl root url to load from
  5817. * @param onProgress event that fires when loading progress has occured
  5818. * @param fileName Defines the name of the file to load
  5819. * @returns a promise which completes when objects have been loaded to the scene
  5820. */
  5821. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress, fileName) {
  5822. var _this = this;
  5823. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  5824. _this._log("Loading " + (fileName || ""));
  5825. _this._loader = _this._getLoader(loaderData);
  5826. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress, fileName);
  5827. });
  5828. };
  5829. /**
  5830. * Load into an asset container.
  5831. * @param scene The scene to load into
  5832. * @param data The data to import
  5833. * @param rootUrl The root url for scene and resources
  5834. * @param onProgress The callback when the load progresses
  5835. * @param fileName Defines the name of the file to load
  5836. * @returns The loaded asset container
  5837. */
  5838. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress, fileName) {
  5839. var _this = this;
  5840. return this._parseAsync(scene, data, rootUrl, fileName).then(function (loaderData) {
  5841. _this._log("Loading " + (fileName || ""));
  5842. _this._loader = _this._getLoader(loaderData);
  5843. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress, fileName).then(function (result) {
  5844. var container = new babylonjs_1.AssetContainer(scene);
  5845. Array.prototype.push.apply(container.meshes, result.meshes);
  5846. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  5847. Array.prototype.push.apply(container.skeletons, result.skeletons);
  5848. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  5849. container.removeAllFromScene();
  5850. return container;
  5851. });
  5852. });
  5853. };
  5854. /**
  5855. * If the data string can be loaded directly.
  5856. * @param data string contianing the file data
  5857. * @returns if the data can be loaded directly
  5858. */
  5859. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  5860. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  5861. };
  5862. /**
  5863. * Instantiates a glTF file loader plugin.
  5864. * @returns the created plugin
  5865. */
  5866. GLTFFileLoader.prototype.createPlugin = function () {
  5867. return new GLTFFileLoader();
  5868. };
  5869. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  5870. /**
  5871. * The loader state or null if the loader is not active.
  5872. */
  5873. get: function () {
  5874. return this._loader ? this._loader.state : null;
  5875. },
  5876. enumerable: true,
  5877. configurable: true
  5878. });
  5879. /**
  5880. * Returns a promise that resolves when the asset is completely loaded.
  5881. * @returns a promise that resolves when the asset is completely loaded.
  5882. */
  5883. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  5884. var _this = this;
  5885. return new Promise(function (resolve, reject) {
  5886. _this.onCompleteObservable.addOnce(function () {
  5887. resolve();
  5888. });
  5889. _this.onErrorObservable.addOnce(function (reason) {
  5890. reject(reason);
  5891. });
  5892. });
  5893. };
  5894. GLTFFileLoader.prototype._parseAsync = function (scene, data, rootUrl, fileName) {
  5895. var _this = this;
  5896. return Promise.resolve().then(function () {
  5897. var unpacked = (data instanceof ArrayBuffer) ? _this._unpackBinary(data) : { json: data, bin: null };
  5898. return _this._validateAsync(scene, unpacked.json, rootUrl, fileName).then(function () {
  5899. _this._startPerformanceCounter("Parse JSON");
  5900. _this._log("JSON length: " + unpacked.json.length);
  5901. var loaderData = {
  5902. json: JSON.parse(unpacked.json),
  5903. bin: unpacked.bin
  5904. };
  5905. _this._endPerformanceCounter("Parse JSON");
  5906. _this.onParsedObservable.notifyObservers(loaderData);
  5907. _this.onParsedObservable.clear();
  5908. return loaderData;
  5909. });
  5910. });
  5911. };
  5912. GLTFFileLoader.prototype._validateAsync = function (scene, json, rootUrl, fileName) {
  5913. var _this = this;
  5914. if (!this.validate || typeof GLTFValidator === "undefined") {
  5915. return Promise.resolve();
  5916. }
  5917. this._startPerformanceCounter("Validate JSON");
  5918. var options = {
  5919. externalResourceFunction: function (uri) {
  5920. return _this.preprocessUrlAsync(rootUrl + uri)
  5921. .then(function (url) { return scene._loadFileAsync(url, true, true); })
  5922. .then(function (data) { return new Uint8Array(data); });
  5923. }
  5924. };
  5925. if (fileName && fileName.substr(0, 5) !== "data:") {
  5926. options.uri = (rootUrl === "file:" ? fileName : "" + rootUrl + fileName);
  5927. }
  5928. return GLTFValidator.validateString(json, options).then(function (result) {
  5929. _this._endPerformanceCounter("Validate JSON");
  5930. _this.onValidatedObservable.notifyObservers(result);
  5931. _this.onValidatedObservable.clear();
  5932. }, function (reason) {
  5933. _this._endPerformanceCounter("Validate JSON");
  5934. babylonjs_1.Tools.Warn("Failed to validate: " + reason);
  5935. _this.onValidatedObservable.clear();
  5936. });
  5937. };
  5938. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  5939. var asset = loaderData.json.asset || {};
  5940. this._log("Asset version: " + asset.version);
  5941. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  5942. asset.generator && this._log("Asset generator: " + asset.generator);
  5943. var version = GLTFFileLoader._parseVersion(asset.version);
  5944. if (!version) {
  5945. throw new Error("Invalid version: " + asset.version);
  5946. }
  5947. if (asset.minVersion !== undefined) {
  5948. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  5949. if (!minVersion) {
  5950. throw new Error("Invalid minimum version: " + asset.minVersion);
  5951. }
  5952. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  5953. throw new Error("Incompatible minimum version: " + asset.minVersion);
  5954. }
  5955. }
  5956. var createLoaders = {
  5957. 1: GLTFFileLoader._CreateGLTF1Loader,
  5958. 2: GLTFFileLoader._CreateGLTF2Loader
  5959. };
  5960. var createLoader = createLoaders[version.major];
  5961. if (!createLoader) {
  5962. throw new Error("Unsupported version: " + asset.version);
  5963. }
  5964. return createLoader(this);
  5965. };
  5966. GLTFFileLoader.prototype._unpackBinary = function (data) {
  5967. this._startPerformanceCounter("Unpack binary");
  5968. this._log("Binary length: " + data.byteLength);
  5969. var Binary = {
  5970. Magic: 0x46546C67
  5971. };
  5972. var binaryReader = new BinaryReader(data);
  5973. var magic = binaryReader.readUint32();
  5974. if (magic !== Binary.Magic) {
  5975. throw new Error("Unexpected magic: " + magic);
  5976. }
  5977. var version = binaryReader.readUint32();
  5978. if (this.loggingEnabled) {
  5979. this._log("Binary version: " + version);
  5980. }
  5981. var unpacked;
  5982. switch (version) {
  5983. case 1: {
  5984. unpacked = this._unpackBinaryV1(binaryReader);
  5985. break;
  5986. }
  5987. case 2: {
  5988. unpacked = this._unpackBinaryV2(binaryReader);
  5989. break;
  5990. }
  5991. default: {
  5992. throw new Error("Unsupported version: " + version);
  5993. }
  5994. }
  5995. this._endPerformanceCounter("Unpack binary");
  5996. return unpacked;
  5997. };
  5998. GLTFFileLoader.prototype._unpackBinaryV1 = function (binaryReader) {
  5999. var ContentFormat = {
  6000. JSON: 0
  6001. };
  6002. var length = binaryReader.readUint32();
  6003. if (length != binaryReader.getLength()) {
  6004. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  6005. }
  6006. var contentLength = binaryReader.readUint32();
  6007. var contentFormat = binaryReader.readUint32();
  6008. var content;
  6009. switch (contentFormat) {
  6010. case ContentFormat.JSON: {
  6011. content = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength));
  6012. break;
  6013. }
  6014. default: {
  6015. throw new Error("Unexpected content format: " + contentFormat);
  6016. }
  6017. }
  6018. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  6019. var body = binaryReader.readUint8Array(bytesRemaining);
  6020. return {
  6021. json: content,
  6022. bin: body
  6023. };
  6024. };
  6025. GLTFFileLoader.prototype._unpackBinaryV2 = function (binaryReader) {
  6026. var ChunkFormat = {
  6027. JSON: 0x4E4F534A,
  6028. BIN: 0x004E4942
  6029. };
  6030. var length = binaryReader.readUint32();
  6031. if (length !== binaryReader.getLength()) {
  6032. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  6033. }
  6034. // JSON chunk
  6035. var chunkLength = binaryReader.readUint32();
  6036. var chunkFormat = binaryReader.readUint32();
  6037. if (chunkFormat !== ChunkFormat.JSON) {
  6038. throw new Error("First chunk format is not JSON");
  6039. }
  6040. var json = GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength));
  6041. // Look for BIN chunk
  6042. var bin = null;
  6043. while (binaryReader.getPosition() < binaryReader.getLength()) {
  6044. var chunkLength_1 = binaryReader.readUint32();
  6045. var chunkFormat_1 = binaryReader.readUint32();
  6046. switch (chunkFormat_1) {
  6047. case ChunkFormat.JSON: {
  6048. throw new Error("Unexpected JSON chunk");
  6049. }
  6050. case ChunkFormat.BIN: {
  6051. bin = binaryReader.readUint8Array(chunkLength_1);
  6052. break;
  6053. }
  6054. default: {
  6055. // ignore unrecognized chunkFormat
  6056. binaryReader.skipBytes(chunkLength_1);
  6057. break;
  6058. }
  6059. }
  6060. }
  6061. return {
  6062. json: json,
  6063. bin: bin
  6064. };
  6065. };
  6066. GLTFFileLoader._parseVersion = function (version) {
  6067. if (version === "1.0" || version === "1.0.1") {
  6068. return {
  6069. major: 1,
  6070. minor: 0
  6071. };
  6072. }
  6073. var match = (version + "").match(/^(\d+)\.(\d+)/);
  6074. if (!match) {
  6075. return null;
  6076. }
  6077. return {
  6078. major: parseInt(match[1]),
  6079. minor: parseInt(match[2])
  6080. };
  6081. };
  6082. GLTFFileLoader._compareVersion = function (a, b) {
  6083. if (a.major > b.major) {
  6084. return 1;
  6085. }
  6086. if (a.major < b.major) {
  6087. return -1;
  6088. }
  6089. if (a.minor > b.minor) {
  6090. return 1;
  6091. }
  6092. if (a.minor < b.minor) {
  6093. return -1;
  6094. }
  6095. return 0;
  6096. };
  6097. GLTFFileLoader._decodeBufferToText = function (buffer) {
  6098. var result = "";
  6099. var length = buffer.byteLength;
  6100. for (var i = 0; i < length; i++) {
  6101. result += String.fromCharCode(buffer[i]);
  6102. }
  6103. return result;
  6104. };
  6105. /** @hidden */
  6106. GLTFFileLoader.prototype._logOpen = function (message) {
  6107. this._log(message);
  6108. this._logIndentLevel++;
  6109. };
  6110. /** @hidden */
  6111. GLTFFileLoader.prototype._logClose = function () {
  6112. --this._logIndentLevel;
  6113. };
  6114. GLTFFileLoader.prototype._logEnabled = function (message) {
  6115. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  6116. babylonjs_1.Tools.Log("" + spaces + message);
  6117. };
  6118. GLTFFileLoader.prototype._logDisabled = function (message) {
  6119. };
  6120. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  6121. babylonjs_1.Tools.StartPerformanceCounter(counterName);
  6122. };
  6123. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  6124. };
  6125. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  6126. babylonjs_1.Tools.EndPerformanceCounter(counterName);
  6127. };
  6128. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  6129. };
  6130. // ----------
  6131. // V1 options
  6132. // ----------
  6133. /**
  6134. * 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.
  6135. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  6136. * Defaults to true.
  6137. * @hidden
  6138. */
  6139. GLTFFileLoader.IncrementalLoading = true;
  6140. /**
  6141. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  6142. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  6143. * @hidden
  6144. */
  6145. GLTFFileLoader.HomogeneousCoordinates = false;
  6146. GLTFFileLoader._logSpaces = " ";
  6147. return GLTFFileLoader;
  6148. }());
  6149. exports.GLTFFileLoader = GLTFFileLoader;
  6150. var BinaryReader = /** @class */ (function () {
  6151. function BinaryReader(arrayBuffer) {
  6152. this._arrayBuffer = arrayBuffer;
  6153. this._dataView = new DataView(arrayBuffer);
  6154. this._byteOffset = 0;
  6155. }
  6156. BinaryReader.prototype.getPosition = function () {
  6157. return this._byteOffset;
  6158. };
  6159. BinaryReader.prototype.getLength = function () {
  6160. return this._arrayBuffer.byteLength;
  6161. };
  6162. BinaryReader.prototype.readUint32 = function () {
  6163. var value = this._dataView.getUint32(this._byteOffset, true);
  6164. this._byteOffset += 4;
  6165. return value;
  6166. };
  6167. BinaryReader.prototype.readUint8Array = function (length) {
  6168. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  6169. this._byteOffset += length;
  6170. return value;
  6171. };
  6172. BinaryReader.prototype.skipBytes = function (length) {
  6173. this._byteOffset += length;
  6174. };
  6175. return BinaryReader;
  6176. }());
  6177. if (babylonjs_1.SceneLoader) {
  6178. babylonjs_1.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  6179. }
  6180. /***/ }),
  6181. /***/ "babylonjs":
  6182. /*!****************************************************************************************************!*\
  6183. !*** external {"root":"BABYLON","commonjs":"babylonjs","commonjs2":"babylonjs","amd":"babylonjs"} ***!
  6184. \****************************************************************************************************/
  6185. /*! no static exports found */
  6186. /***/ (function(module, exports) {
  6187. module.exports = __WEBPACK_EXTERNAL_MODULE_babylonjs__;
  6188. /***/ })
  6189. /******/ });
  6190. });
  6191. //# sourceMappingURL=babylon.glTFFileLoader.js.map