babylon.glTFFileLoader.js 271 KB

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