babylon.glTFFileLoader.js 236 KB

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