babylon.glTFFileLoader.js 308 KB

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