babylon.glTFFileLoader.js 268 KB

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