babylonjs.loaders.js 337 KB

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