babylon.glTFFileLoader.js 203 KB

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