babylon.glTFFileLoader.js 271 KB

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