babylon.glTFFileLoader.js 299 KB

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