babylon.glTFFileLoader.js 222 KB

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