babylon.glTFFileLoader.js 308 KB

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