babylonjs.loaders.js 307 KB

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