babylon.glTFFileLoader.js 177 KB

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