babylon.glTFFileLoader.js 184 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816
  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._parse = function (data) {
  30. if (data instanceof ArrayBuffer) {
  31. return GLTFFileLoader._parseBinary(data);
  32. }
  33. return {
  34. json: JSON.parse(data),
  35. bin: null
  36. };
  37. };
  38. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  39. var loaderVersion = { major: 2, minor: 0 };
  40. var asset = loaderData.json.asset || {};
  41. var version = GLTFFileLoader._parseVersion(asset.version);
  42. if (!version) {
  43. BABYLON.Tools.Error("Invalid version");
  44. return null;
  45. }
  46. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  47. if (minVersion) {
  48. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  49. BABYLON.Tools.Error("Incompatible version");
  50. return null;
  51. }
  52. }
  53. var loaders = {
  54. 1: GLTFFileLoader.GLTFLoaderV1,
  55. 2: GLTFFileLoader.GLTFLoaderV2
  56. };
  57. var loader = loaders[version.major];
  58. if (loader === undefined) {
  59. BABYLON.Tools.Error("Unsupported version");
  60. return null;
  61. }
  62. if (loader === null) {
  63. BABYLON.Tools.Error("v" + version.major + " loader is not available");
  64. return null;
  65. }
  66. return loader;
  67. };
  68. GLTFFileLoader._parseBinary = function (data) {
  69. var Binary = {
  70. Magic: 0x46546C67
  71. };
  72. var binaryReader = new BinaryReader(data);
  73. var magic = binaryReader.readUint32();
  74. if (magic !== Binary.Magic) {
  75. BABYLON.Tools.Error("Unexpected magic: " + magic);
  76. return null;
  77. }
  78. var version = binaryReader.readUint32();
  79. switch (version) {
  80. case 1: return GLTFFileLoader._parseV1(binaryReader);
  81. case 2: return GLTFFileLoader._parseV2(binaryReader);
  82. }
  83. BABYLON.Tools.Error("Unsupported version: " + version);
  84. return null;
  85. };
  86. GLTFFileLoader._parseV1 = function (binaryReader) {
  87. var ContentFormat = {
  88. JSON: 0
  89. };
  90. var length = binaryReader.readUint32();
  91. if (length != binaryReader.getLength()) {
  92. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  93. return null;
  94. }
  95. var contentLength = binaryReader.readUint32();
  96. var contentFormat = binaryReader.readUint32();
  97. var content;
  98. switch (contentFormat) {
  99. case ContentFormat.JSON:
  100. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  101. break;
  102. default:
  103. BABYLON.Tools.Error("Unexpected content format: " + contentFormat);
  104. return null;
  105. }
  106. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  107. var body = binaryReader.readUint8Array(bytesRemaining);
  108. return {
  109. json: content,
  110. bin: body
  111. };
  112. };
  113. GLTFFileLoader._parseV2 = function (binaryReader) {
  114. var ChunkFormat = {
  115. JSON: 0x4E4F534A,
  116. BIN: 0x004E4942
  117. };
  118. var length = binaryReader.readUint32();
  119. if (length !== binaryReader.getLength()) {
  120. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  121. return null;
  122. }
  123. // JSON chunk
  124. var chunkLength = binaryReader.readUint32();
  125. var chunkFormat = binaryReader.readUint32();
  126. if (chunkFormat !== ChunkFormat.JSON) {
  127. BABYLON.Tools.Error("First chunk format is not JSON");
  128. return null;
  129. }
  130. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  131. // Look for BIN chunk
  132. var bin = null;
  133. while (binaryReader.getPosition() < binaryReader.getLength()) {
  134. chunkLength = binaryReader.readUint32();
  135. chunkFormat = binaryReader.readUint32();
  136. switch (chunkFormat) {
  137. case ChunkFormat.JSON:
  138. BABYLON.Tools.Error("Unexpected JSON chunk");
  139. return null;
  140. case ChunkFormat.BIN:
  141. bin = binaryReader.readUint8Array(chunkLength);
  142. break;
  143. default:
  144. // ignore unrecognized chunkFormat
  145. binaryReader.skipBytes(chunkLength);
  146. break;
  147. }
  148. }
  149. return {
  150. json: json,
  151. bin: bin
  152. };
  153. };
  154. GLTFFileLoader._parseVersion = function (version) {
  155. if (!version) {
  156. return null;
  157. }
  158. var parts = version.split(".");
  159. if (parts.length === 0) {
  160. return null;
  161. }
  162. var major = parseInt(parts[0]);
  163. if (major > 1 && parts.length != 2) {
  164. return null;
  165. }
  166. var minor = parseInt(parts[1]);
  167. return {
  168. major: major,
  169. minor: parseInt(parts[0])
  170. };
  171. };
  172. GLTFFileLoader._compareVersion = function (a, b) {
  173. if (a.major > b.major)
  174. return 1;
  175. if (a.major < b.major)
  176. return -1;
  177. if (a.minor > b.minor)
  178. return 1;
  179. if (a.minor < b.minor)
  180. return -1;
  181. return 0;
  182. };
  183. GLTFFileLoader._decodeBufferToText = function (view) {
  184. var result = "";
  185. var length = view.byteLength;
  186. for (var i = 0; i < length; ++i) {
  187. result += String.fromCharCode(view[i]);
  188. }
  189. return result;
  190. };
  191. return GLTFFileLoader;
  192. }());
  193. GLTFFileLoader.GLTFLoaderV1 = null;
  194. GLTFFileLoader.GLTFLoaderV2 = null;
  195. GLTFFileLoader.HomogeneousCoordinates = false;
  196. GLTFFileLoader.IncrementalLoading = true;
  197. BABYLON.GLTFFileLoader = GLTFFileLoader;
  198. var BinaryReader = (function () {
  199. function BinaryReader(arrayBuffer) {
  200. this._arrayBuffer = arrayBuffer;
  201. this._dataView = new DataView(arrayBuffer);
  202. this._byteOffset = 0;
  203. }
  204. BinaryReader.prototype.getPosition = function () {
  205. return this._byteOffset;
  206. };
  207. BinaryReader.prototype.getLength = function () {
  208. return this._arrayBuffer.byteLength;
  209. };
  210. BinaryReader.prototype.readUint32 = function () {
  211. var value = this._dataView.getUint32(this._byteOffset, true);
  212. this._byteOffset += 4;
  213. return value;
  214. };
  215. BinaryReader.prototype.readUint8Array = function (length) {
  216. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  217. this._byteOffset += length;
  218. return value;
  219. };
  220. BinaryReader.prototype.skipBytes = function (length) {
  221. this._byteOffset += length;
  222. };
  223. return BinaryReader;
  224. }());
  225. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  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. foundBone = false;
  756. for (var k = 0; k < children.length; k++) {
  757. if (children[k] === id) {
  758. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  759. foundBone = true;
  760. break;
  761. }
  762. }
  763. if (foundBone) {
  764. break;
  765. }
  766. }
  767. // Create bone
  768. var mat = configureBoneTransformation(node);
  769. if (!parentBone && nodesToRoot.length > 0) {
  770. parentBone = getNodeToRoot(nodesToRoot, id);
  771. if (parentBone) {
  772. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  773. nodesToRootToAdd.push(parentBone);
  774. }
  775. }
  776. }
  777. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  778. bone.id = id;
  779. }
  780. // Polish
  781. var bones = newSkeleton.bones;
  782. newSkeleton.bones = [];
  783. for (var i = 0; i < skins.jointNames.length; i++) {
  784. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  785. if (!jointNode) {
  786. continue;
  787. }
  788. for (var j = 0; j < bones.length; j++) {
  789. if (bones[j].id === jointNode.id) {
  790. newSkeleton.bones.push(bones[j]);
  791. break;
  792. }
  793. }
  794. }
  795. newSkeleton.prepare();
  796. // Finish
  797. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  798. newSkeleton.bones.push(nodesToRootToAdd[i]);
  799. }
  800. return newSkeleton;
  801. };
  802. /**
  803. * Imports a mesh and its geometries
  804. */
  805. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  806. if (!newMesh) {
  807. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  808. newMesh.id = id;
  809. }
  810. if (!node.babylonNode) {
  811. return newMesh;
  812. }
  813. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  814. if (!newMesh.material) {
  815. newMesh.material = multiMat;
  816. }
  817. var vertexData = new BABYLON.VertexData();
  818. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  819. var verticesStarts = [];
  820. var verticesCounts = [];
  821. var indexStarts = [];
  822. var indexCounts = [];
  823. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  824. var meshID = meshes[meshIndex];
  825. var mesh = gltfRuntime.meshes[meshID];
  826. if (!mesh) {
  827. continue;
  828. }
  829. // Positions, normals and UVs
  830. for (var i = 0; i < mesh.primitives.length; i++) {
  831. // Temporary vertex data
  832. var tempVertexData = new BABYLON.VertexData();
  833. var primitive = mesh.primitives[i];
  834. if (primitive.mode !== 4) {
  835. // continue;
  836. }
  837. var attributes = primitive.attributes;
  838. var accessor = null;
  839. var buffer = null;
  840. // Set positions, normal and uvs
  841. for (var semantic in attributes) {
  842. // Link accessor and buffer view
  843. accessor = gltfRuntime.accessors[attributes[semantic]];
  844. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  845. if (semantic === "NORMAL") {
  846. tempVertexData.normals = new Float32Array(buffer.length);
  847. tempVertexData.normals.set(buffer);
  848. }
  849. else if (semantic === "POSITION") {
  850. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  851. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  852. for (var j = 0; j < buffer.length; j += 4) {
  853. tempVertexData.positions[j] = buffer[j];
  854. tempVertexData.positions[j + 1] = buffer[j + 1];
  855. tempVertexData.positions[j + 2] = buffer[j + 2];
  856. }
  857. }
  858. else {
  859. tempVertexData.positions = new Float32Array(buffer.length);
  860. tempVertexData.positions.set(buffer);
  861. }
  862. verticesCounts.push(tempVertexData.positions.length);
  863. }
  864. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  865. var channel = Number(semantic.split("_")[1]);
  866. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  867. var uvs = new Float32Array(buffer.length);
  868. uvs.set(buffer);
  869. normalizeUVs(uvs);
  870. tempVertexData.set(uvs, uvKind);
  871. }
  872. else if (semantic === "JOINT") {
  873. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  874. tempVertexData.matricesIndices.set(buffer);
  875. }
  876. else if (semantic === "WEIGHT") {
  877. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  878. tempVertexData.matricesWeights.set(buffer);
  879. }
  880. else if (semantic === "COLOR") {
  881. tempVertexData.colors = new Float32Array(buffer.length);
  882. tempVertexData.colors.set(buffer);
  883. }
  884. }
  885. // Indices
  886. accessor = gltfRuntime.accessors[primitive.indices];
  887. if (accessor) {
  888. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  889. tempVertexData.indices = new Int32Array(buffer.length);
  890. tempVertexData.indices.set(buffer);
  891. indexCounts.push(tempVertexData.indices.length);
  892. }
  893. else {
  894. // Set indices on the fly
  895. var indices = [];
  896. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  897. indices.push(j);
  898. }
  899. tempVertexData.indices = new Int32Array(indices);
  900. indexCounts.push(tempVertexData.indices.length);
  901. }
  902. vertexData.merge(tempVertexData);
  903. tempVertexData = undefined;
  904. // Sub material
  905. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  906. multiMat.subMaterials.push(material === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  907. // Update vertices start and index start
  908. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  909. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  910. }
  911. }
  912. // Apply geometry
  913. geometry.setAllVerticesData(vertexData, false);
  914. newMesh.computeWorldMatrix(true);
  915. // Apply submeshes
  916. newMesh.subMeshes = [];
  917. var index = 0;
  918. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  919. var meshID = meshes[meshIndex];
  920. var mesh = gltfRuntime.meshes[meshID];
  921. if (!mesh) {
  922. continue;
  923. }
  924. for (var i = 0; i < mesh.primitives.length; i++) {
  925. if (mesh.primitives[i].mode !== 4) {
  926. //continue;
  927. }
  928. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  929. index++;
  930. }
  931. }
  932. // Finish
  933. return newMesh;
  934. };
  935. /**
  936. * Configure node transformation from position, rotation and scaling
  937. */
  938. var configureNode = function (newNode, position, rotation, scaling) {
  939. if (newNode.position) {
  940. newNode.position = position;
  941. }
  942. if (newNode.rotationQuaternion || newNode.rotation) {
  943. newNode.rotationQuaternion = rotation;
  944. }
  945. if (newNode.scaling) {
  946. newNode.scaling = scaling;
  947. }
  948. };
  949. /**
  950. * Configures node from transformation matrix
  951. */
  952. var configureNodeFromMatrix = function (newNode, node, parent) {
  953. if (node.matrix) {
  954. var position = new BABYLON.Vector3(0, 0, 0);
  955. var rotation = new BABYLON.Quaternion();
  956. var scaling = new BABYLON.Vector3(0, 0, 0);
  957. var mat = BABYLON.Matrix.FromArray(node.matrix);
  958. mat.decompose(scaling, rotation, position);
  959. configureNode(newNode, position, rotation, scaling);
  960. }
  961. else {
  962. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  963. }
  964. newNode.computeWorldMatrix(true);
  965. };
  966. /**
  967. * Imports a node
  968. */
  969. var importNode = function (gltfRuntime, node, id, parent) {
  970. var lastNode = null;
  971. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  972. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  973. return null;
  974. }
  975. }
  976. // Meshes
  977. if (node.skin) {
  978. if (node.meshes) {
  979. var skin = gltfRuntime.skins[node.skin];
  980. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  981. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  982. if (newMesh.skeleton === null) {
  983. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  984. if (!skin.babylonSkeleton) {
  985. skin.babylonSkeleton = newMesh.skeleton;
  986. }
  987. }
  988. lastNode = newMesh;
  989. }
  990. }
  991. else if (node.meshes) {
  992. /**
  993. * Improve meshes property
  994. */
  995. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  996. lastNode = newMesh;
  997. }
  998. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  999. var light = gltfRuntime.lights[node.light];
  1000. if (light) {
  1001. if (light.type === "ambient") {
  1002. var ambienLight = light[light.type];
  1003. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1004. hemiLight.name = node.name;
  1005. if (ambienLight.color) {
  1006. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  1007. }
  1008. lastNode = hemiLight;
  1009. }
  1010. else if (light.type === "directional") {
  1011. var directionalLight = light[light.type];
  1012. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1013. dirLight.name = node.name;
  1014. if (directionalLight.color) {
  1015. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  1016. }
  1017. lastNode = dirLight;
  1018. }
  1019. else if (light.type === "point") {
  1020. var pointLight = light[light.type];
  1021. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1022. ptLight.name = node.name;
  1023. if (pointLight.color) {
  1024. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  1025. }
  1026. lastNode = ptLight;
  1027. }
  1028. else if (light.type === "spot") {
  1029. var spotLight = light[light.type];
  1030. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  1031. spLight.name = node.name;
  1032. if (spotLight.color) {
  1033. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  1034. }
  1035. if (spotLight.fallOfAngle) {
  1036. spLight.angle = spotLight.fallOfAngle;
  1037. }
  1038. if (spotLight.fallOffExponent) {
  1039. spLight.exponent = spotLight.fallOffExponent;
  1040. }
  1041. lastNode = spLight;
  1042. }
  1043. }
  1044. }
  1045. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  1046. var camera = gltfRuntime.cameras[node.camera];
  1047. if (camera) {
  1048. if (camera.type === "orthographic") {
  1049. var orthographicCamera = camera[camera.type];
  1050. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1051. orthoCamera.name = node.name;
  1052. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  1053. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1054. lastNode = orthoCamera;
  1055. }
  1056. else if (camera.type === "perspective") {
  1057. var perspectiveCamera = camera[camera.type];
  1058. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  1059. persCamera.name = node.name;
  1060. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  1061. if (!perspectiveCamera.aspectRatio) {
  1062. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  1063. }
  1064. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  1065. persCamera.maxZ = perspectiveCamera.zfar;
  1066. persCamera.minZ = perspectiveCamera.znear;
  1067. }
  1068. lastNode = persCamera;
  1069. }
  1070. }
  1071. }
  1072. // Empty node
  1073. if (!node.jointName) {
  1074. if (node.babylonNode) {
  1075. return node.babylonNode;
  1076. }
  1077. else if (lastNode === null) {
  1078. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  1079. node.babylonNode = dummy;
  1080. lastNode = dummy;
  1081. }
  1082. }
  1083. if (lastNode !== null) {
  1084. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  1085. configureNodeFromMatrix(lastNode, node, parent);
  1086. }
  1087. else {
  1088. var translation = node.translation || [0, 0, 0];
  1089. var rotation = node.rotation || [0, 0, 0, 1];
  1090. var scale = node.scale || [1, 1, 1];
  1091. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  1092. }
  1093. lastNode.updateCache(true);
  1094. node.babylonNode = lastNode;
  1095. }
  1096. return lastNode;
  1097. };
  1098. /**
  1099. * Traverses nodes and creates them
  1100. */
  1101. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  1102. var node = gltfRuntime.nodes[id];
  1103. var newNode = null;
  1104. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  1105. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  1106. meshIncluded = true;
  1107. }
  1108. else {
  1109. meshIncluded = false;
  1110. }
  1111. }
  1112. else {
  1113. meshIncluded = true;
  1114. }
  1115. if (!node.jointName && meshIncluded) {
  1116. newNode = importNode(gltfRuntime, node, id, parent);
  1117. if (newNode !== null) {
  1118. newNode.id = id;
  1119. newNode.parent = parent;
  1120. }
  1121. }
  1122. if (node.children) {
  1123. for (var i = 0; i < node.children.length; i++) {
  1124. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  1125. }
  1126. }
  1127. };
  1128. /**
  1129. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  1130. */
  1131. var postLoad = function (gltfRuntime) {
  1132. // Nodes
  1133. var currentScene = gltfRuntime.currentScene;
  1134. if (currentScene) {
  1135. for (var i = 0; i < currentScene.nodes.length; i++) {
  1136. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1137. }
  1138. }
  1139. else {
  1140. for (var thing in gltfRuntime.scenes) {
  1141. currentScene = gltfRuntime.scenes[thing];
  1142. for (var i = 0; i < currentScene.nodes.length; i++) {
  1143. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1144. }
  1145. }
  1146. }
  1147. // Set animations
  1148. loadAnimations(gltfRuntime);
  1149. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  1150. var skeleton = gltfRuntime.scene.skeletons[i];
  1151. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  1152. }
  1153. };
  1154. /**
  1155. * onBind shaderrs callback to set uniforms and matrices
  1156. */
  1157. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  1158. var materialValues = material.values || technique.parameters;
  1159. for (var unif in unTreatedUniforms) {
  1160. var uniform = unTreatedUniforms[unif];
  1161. var type = uniform.type;
  1162. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  1163. if (uniform.semantic && !uniform.source && !uniform.node) {
  1164. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  1165. }
  1166. else if (uniform.semantic && (uniform.source || uniform.node)) {
  1167. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  1168. if (source === null) {
  1169. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  1170. }
  1171. if (source === null) {
  1172. continue;
  1173. }
  1174. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  1175. }
  1176. }
  1177. else {
  1178. var value = materialValues[technique.uniforms[unif]];
  1179. if (!value) {
  1180. continue;
  1181. }
  1182. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1183. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  1184. if (texture === null || texture === undefined) {
  1185. continue;
  1186. }
  1187. shaderMaterial.getEffect().setTexture(unif, texture);
  1188. }
  1189. else {
  1190. GLTF1.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  1191. }
  1192. }
  1193. }
  1194. onSuccess(shaderMaterial);
  1195. };
  1196. /**
  1197. * Prepare uniforms to send the only one time
  1198. * Loads the appropriate textures
  1199. */
  1200. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  1201. var materialValues = material.values || technique.parameters;
  1202. var techniqueUniforms = technique.uniforms;
  1203. /**
  1204. * Prepare values here (not matrices)
  1205. */
  1206. for (var unif in unTreatedUniforms) {
  1207. var uniform = unTreatedUniforms[unif];
  1208. var type = uniform.type;
  1209. var value = materialValues[techniqueUniforms[unif]];
  1210. if (value === undefined) {
  1211. // In case the value is the same for all materials
  1212. value = uniform.value;
  1213. }
  1214. if (!value) {
  1215. continue;
  1216. }
  1217. var onLoadTexture = function (uniformName) {
  1218. return function (texture) {
  1219. if (uniform.value) {
  1220. // Static uniform
  1221. shaderMaterial.setTexture(uniformName, texture);
  1222. delete unTreatedUniforms[uniformName];
  1223. }
  1224. };
  1225. };
  1226. // Texture (sampler2D)
  1227. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  1228. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  1229. }
  1230. else {
  1231. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1232. // Static uniform
  1233. delete unTreatedUniforms[unif];
  1234. }
  1235. }
  1236. }
  1237. };
  1238. /**
  1239. * Shader compilation failed
  1240. */
  1241. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1242. return function (effect, error) {
  1243. BABYLON.Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1244. shaderMaterial.dispose(true);
  1245. onError();
  1246. };
  1247. };
  1248. /**
  1249. * Shader compilation success
  1250. */
  1251. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1252. return function (_) {
  1253. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1254. shaderMaterial.onBind = function (mesh) {
  1255. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1256. };
  1257. };
  1258. };
  1259. /**
  1260. * Returns the appropriate uniform if already handled by babylon
  1261. */
  1262. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1263. for (var unif in technique.uniforms) {
  1264. var uniform = technique.uniforms[unif];
  1265. var uniformParameter = technique.parameters[uniform];
  1266. if (tokenizer.currentIdentifier === unif) {
  1267. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1268. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1269. if (transformIndex !== -1) {
  1270. delete unTreatedUniforms[unif];
  1271. return babylonTransforms[transformIndex];
  1272. }
  1273. }
  1274. }
  1275. }
  1276. return tokenizer.currentIdentifier;
  1277. };
  1278. /**
  1279. * All shaders loaded. Create materials one by one
  1280. */
  1281. var importMaterials = function (gltfRuntime) {
  1282. // Create materials
  1283. for (var mat in gltfRuntime.materials) {
  1284. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1285. }
  1286. };
  1287. /**
  1288. * Implementation of the base glTF spec
  1289. */
  1290. var GLTFLoaderBase = (function () {
  1291. function GLTFLoaderBase() {
  1292. }
  1293. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1294. var gltfRuntime = {
  1295. extensions: {},
  1296. accessors: {},
  1297. buffers: {},
  1298. bufferViews: {},
  1299. meshes: {},
  1300. lights: {},
  1301. cameras: {},
  1302. nodes: {},
  1303. images: {},
  1304. textures: {},
  1305. shaders: {},
  1306. programs: {},
  1307. samplers: {},
  1308. techniques: {},
  1309. materials: {},
  1310. animations: {},
  1311. skins: {},
  1312. extensionsUsed: [],
  1313. scenes: {},
  1314. buffersCount: 0,
  1315. shaderscount: 0,
  1316. scene: scene,
  1317. rootUrl: rootUrl,
  1318. loadedBufferCount: 0,
  1319. loadedBufferViews: {},
  1320. loadedShaderCount: 0,
  1321. importOnlyMeshes: false,
  1322. dummyNodes: []
  1323. };
  1324. // Parse
  1325. if (parsedData.extensions) {
  1326. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1327. }
  1328. if (parsedData.extensionsUsed) {
  1329. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1330. }
  1331. if (parsedData.buffers) {
  1332. parseBuffers(parsedData.buffers, gltfRuntime);
  1333. }
  1334. if (parsedData.bufferViews) {
  1335. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1336. }
  1337. if (parsedData.accessors) {
  1338. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1339. }
  1340. if (parsedData.meshes) {
  1341. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1342. }
  1343. if (parsedData.lights) {
  1344. parseObject(parsedData.lights, "lights", gltfRuntime);
  1345. }
  1346. if (parsedData.cameras) {
  1347. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1348. }
  1349. if (parsedData.nodes) {
  1350. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1351. }
  1352. if (parsedData.images) {
  1353. parseObject(parsedData.images, "images", gltfRuntime);
  1354. }
  1355. if (parsedData.textures) {
  1356. parseObject(parsedData.textures, "textures", gltfRuntime);
  1357. }
  1358. if (parsedData.shaders) {
  1359. parseShaders(parsedData.shaders, gltfRuntime);
  1360. }
  1361. if (parsedData.programs) {
  1362. parseObject(parsedData.programs, "programs", gltfRuntime);
  1363. }
  1364. if (parsedData.samplers) {
  1365. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1366. }
  1367. if (parsedData.techniques) {
  1368. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1369. }
  1370. if (parsedData.materials) {
  1371. parseObject(parsedData.materials, "materials", gltfRuntime);
  1372. }
  1373. if (parsedData.animations) {
  1374. parseObject(parsedData.animations, "animations", gltfRuntime);
  1375. }
  1376. if (parsedData.skins) {
  1377. parseObject(parsedData.skins, "skins", gltfRuntime);
  1378. }
  1379. if (parsedData.scenes) {
  1380. gltfRuntime.scenes = parsedData.scenes;
  1381. }
  1382. if (parsedData.scene && parsedData.scenes) {
  1383. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1384. }
  1385. return gltfRuntime;
  1386. };
  1387. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  1388. var buffer = gltfRuntime.buffers[id];
  1389. if (GLTF1.GLTFUtils.IsBase64(buffer.uri)) {
  1390. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(buffer.uri))); });
  1391. }
  1392. else {
  1393. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, null, true, onError);
  1394. }
  1395. };
  1396. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1397. var texture = gltfRuntime.textures[id];
  1398. if (!texture || !texture.source) {
  1399. onError();
  1400. return;
  1401. }
  1402. if (texture.babylonTexture) {
  1403. onSuccess(null);
  1404. return;
  1405. }
  1406. var source = gltfRuntime.images[texture.source];
  1407. if (GLTF1.GLTFUtils.IsBase64(source.uri)) {
  1408. setTimeout(function () { return onSuccess(new Uint8Array(GLTF1.GLTFUtils.DecodeBase64(source.uri))); });
  1409. }
  1410. else {
  1411. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1412. }
  1413. };
  1414. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1415. var texture = gltfRuntime.textures[id];
  1416. if (texture.babylonTexture) {
  1417. onSuccess(texture.babylonTexture);
  1418. return;
  1419. }
  1420. var sampler = gltfRuntime.samplers[texture.sampler];
  1421. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1422. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1423. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1424. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1425. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1426. var blob = new Blob([buffer]);
  1427. var blobURL = URL.createObjectURL(blob);
  1428. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1429. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1430. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  1431. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  1432. newTexture.name = id;
  1433. texture.babylonTexture = newTexture;
  1434. onSuccess(newTexture);
  1435. };
  1436. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1437. var shader = gltfRuntime.shaders[id];
  1438. if (GLTF1.GLTFUtils.IsBase64(shader.uri)) {
  1439. var shaderString = atob(shader.uri.split(",")[1]);
  1440. onSuccess(shaderString);
  1441. }
  1442. else {
  1443. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, onError);
  1444. }
  1445. };
  1446. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1447. var material = gltfRuntime.materials[id];
  1448. var technique = gltfRuntime.techniques[material.technique];
  1449. if (!technique) {
  1450. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1451. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1452. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1453. onSuccess(defaultMaterial);
  1454. return;
  1455. }
  1456. var program = gltfRuntime.programs[technique.program];
  1457. var states = technique.states;
  1458. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1459. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1460. var newVertexShader = "";
  1461. var newPixelShader = "";
  1462. var vertexTokenizer = new Tokenizer(vertexShader);
  1463. var pixelTokenizer = new Tokenizer(pixelShader);
  1464. var unTreatedUniforms = {};
  1465. var uniforms = [];
  1466. var attributes = [];
  1467. var samplers = [];
  1468. // Fill uniform, sampler2D and attributes
  1469. for (var unif in technique.uniforms) {
  1470. var uniform = technique.uniforms[unif];
  1471. var uniformParameter = technique.parameters[uniform];
  1472. unTreatedUniforms[unif] = uniformParameter;
  1473. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1474. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1475. if (transformIndex !== -1) {
  1476. uniforms.push(babylonTransforms[transformIndex]);
  1477. delete unTreatedUniforms[unif];
  1478. }
  1479. else {
  1480. uniforms.push(unif);
  1481. }
  1482. }
  1483. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  1484. samplers.push(unif);
  1485. }
  1486. else {
  1487. uniforms.push(unif);
  1488. }
  1489. }
  1490. for (var attr in technique.attributes) {
  1491. var attribute = technique.attributes[attr];
  1492. var attributeParameter = technique.parameters[attribute];
  1493. if (attributeParameter.semantic) {
  1494. attributes.push(getAttribute(attributeParameter));
  1495. }
  1496. }
  1497. // Configure vertex shader
  1498. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1499. var tokenType = vertexTokenizer.currentToken;
  1500. if (tokenType !== ETokenType.IDENTIFIER) {
  1501. newVertexShader += vertexTokenizer.currentString;
  1502. continue;
  1503. }
  1504. var foundAttribute = false;
  1505. for (var attr in technique.attributes) {
  1506. var attribute = technique.attributes[attr];
  1507. var attributeParameter = technique.parameters[attribute];
  1508. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1509. newVertexShader += getAttribute(attributeParameter);
  1510. foundAttribute = true;
  1511. break;
  1512. }
  1513. }
  1514. if (foundAttribute) {
  1515. continue;
  1516. }
  1517. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1518. }
  1519. // Configure pixel shader
  1520. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1521. var tokenType = pixelTokenizer.currentToken;
  1522. if (tokenType !== ETokenType.IDENTIFIER) {
  1523. newPixelShader += pixelTokenizer.currentString;
  1524. continue;
  1525. }
  1526. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1527. }
  1528. // Create shader material
  1529. var shaderPath = {
  1530. vertex: program.vertexShader + id,
  1531. fragment: program.fragmentShader + id
  1532. };
  1533. var options = {
  1534. attributes: attributes,
  1535. uniforms: uniforms,
  1536. samplers: samplers,
  1537. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1538. };
  1539. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1540. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1541. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1542. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1543. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1544. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1545. if (states && states.functions) {
  1546. var functions = states.functions;
  1547. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  1548. shaderMaterial.backFaceCulling = false;
  1549. }
  1550. var blendFunc = functions.blendFuncSeparate;
  1551. if (blendFunc) {
  1552. 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) {
  1553. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1554. }
  1555. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1556. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1557. }
  1558. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1559. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1560. }
  1561. 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) {
  1562. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1563. }
  1564. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  1565. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1566. }
  1567. 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) {
  1568. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1569. }
  1570. }
  1571. }
  1572. };
  1573. return GLTFLoaderBase;
  1574. }());
  1575. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  1576. /**
  1577. * glTF V1 Loader
  1578. */
  1579. var GLTFLoader = (function () {
  1580. function GLTFLoader() {
  1581. }
  1582. GLTFLoader.RegisterExtension = function (extension) {
  1583. if (GLTFLoader.Extensions[extension.name]) {
  1584. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1585. return;
  1586. }
  1587. GLTFLoader.Extensions[extension.name] = extension;
  1588. };
  1589. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError, onProgress) {
  1590. var _this = this;
  1591. scene.useRightHandedSystem = true;
  1592. var gltfRuntime = GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1593. gltfRuntime.importOnlyMeshes = true;
  1594. if (meshesNames === "") {
  1595. gltfRuntime.importMeshesNames = [];
  1596. }
  1597. else if (typeof meshesNames === "string") {
  1598. gltfRuntime.importMeshesNames = [meshesNames];
  1599. }
  1600. else if (meshesNames && !(meshesNames instanceof Array)) {
  1601. gltfRuntime.importMeshesNames = [meshesNames];
  1602. }
  1603. else {
  1604. gltfRuntime.importMeshesNames = [];
  1605. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1606. }
  1607. // Create nodes
  1608. _this._createNodes(gltfRuntime);
  1609. var meshes = [];
  1610. var skeletons = [];
  1611. // Fill arrays of meshes and skeletons
  1612. for (var nde in gltfRuntime.nodes) {
  1613. var node = gltfRuntime.nodes[nde];
  1614. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1615. meshes.push(node.babylonNode);
  1616. }
  1617. }
  1618. for (var skl in gltfRuntime.skins) {
  1619. var skin = gltfRuntime.skins[skl];
  1620. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1621. skeletons.push(skin.babylonSkeleton);
  1622. }
  1623. }
  1624. // Load buffers, shaders, materials, etc.
  1625. _this._loadBuffersAsync(gltfRuntime, function () {
  1626. _this._loadShadersAsync(gltfRuntime, function () {
  1627. importMaterials(gltfRuntime);
  1628. postLoad(gltfRuntime);
  1629. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1630. onSuccess(meshes, null, skeletons);
  1631. }
  1632. });
  1633. }, onProgress);
  1634. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1635. onSuccess(meshes, null, skeletons);
  1636. }
  1637. }, onError);
  1638. return true;
  1639. };
  1640. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1641. var _this = this;
  1642. scene.useRightHandedSystem = true;
  1643. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1644. // Load runtime extensios
  1645. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  1646. // Create nodes
  1647. _this._createNodes(gltfRuntime);
  1648. // Load buffers, shaders, materials, etc.
  1649. _this._loadBuffersAsync(gltfRuntime, function () {
  1650. _this._loadShadersAsync(gltfRuntime, function () {
  1651. importMaterials(gltfRuntime);
  1652. postLoad(gltfRuntime);
  1653. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1654. onSuccess();
  1655. }
  1656. });
  1657. });
  1658. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1659. onSuccess();
  1660. }
  1661. }, onError);
  1662. }, onError);
  1663. };
  1664. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1665. var hasShaders = false;
  1666. var processShader = function (sha, shader) {
  1667. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1668. gltfRuntime.loadedShaderCount++;
  1669. if (shaderString) {
  1670. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1671. }
  1672. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1673. onload();
  1674. }
  1675. }, function () {
  1676. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1677. });
  1678. };
  1679. for (var sha in gltfRuntime.shaders) {
  1680. hasShaders = true;
  1681. var shader = gltfRuntime.shaders[sha];
  1682. if (shader) {
  1683. processShader.bind(this, sha, shader)();
  1684. }
  1685. else {
  1686. BABYLON.Tools.Error("No shader named: " + sha);
  1687. }
  1688. }
  1689. if (!hasShaders) {
  1690. onload();
  1691. }
  1692. };
  1693. ;
  1694. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onload, onProgress) {
  1695. var hasBuffers = false;
  1696. var processBuffer = function (buf, buffer) {
  1697. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1698. gltfRuntime.loadedBufferCount++;
  1699. if (bufferView) {
  1700. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1701. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1702. }
  1703. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1704. }
  1705. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1706. onload();
  1707. }
  1708. }, function () {
  1709. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1710. });
  1711. };
  1712. for (var buf in gltfRuntime.buffers) {
  1713. hasBuffers = true;
  1714. var buffer = gltfRuntime.buffers[buf];
  1715. if (buffer) {
  1716. processBuffer.bind(this, buf, buffer)();
  1717. }
  1718. else {
  1719. BABYLON.Tools.Error("No buffer named: " + buf);
  1720. }
  1721. }
  1722. if (!hasBuffers) {
  1723. onload();
  1724. }
  1725. };
  1726. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  1727. var currentScene = gltfRuntime.currentScene;
  1728. if (currentScene) {
  1729. // Only one scene even if multiple scenes are defined
  1730. for (var i = 0; i < currentScene.nodes.length; i++) {
  1731. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1732. }
  1733. }
  1734. else {
  1735. // Load all scenes
  1736. for (var thing in gltfRuntime.scenes) {
  1737. currentScene = gltfRuntime.scenes[thing];
  1738. for (var i = 0; i < currentScene.nodes.length; i++) {
  1739. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1740. }
  1741. }
  1742. }
  1743. };
  1744. return GLTFLoader;
  1745. }());
  1746. GLTFLoader.Extensions = {};
  1747. GLTF1.GLTFLoader = GLTFLoader;
  1748. ;
  1749. BABYLON.GLTFFileLoader.GLTFLoaderV1 = new GLTFLoader();
  1750. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  1751. })(BABYLON || (BABYLON = {}));
  1752. //# sourceMappingURL=babylon.glTFLoader.js.map
  1753. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  1754. var BABYLON;
  1755. (function (BABYLON) {
  1756. var GLTF1;
  1757. (function (GLTF1) {
  1758. /**
  1759. * Utils functions for GLTF
  1760. */
  1761. var GLTFUtils = (function () {
  1762. function GLTFUtils() {
  1763. }
  1764. /**
  1765. * Sets the given "parameter" matrix
  1766. * @param scene: the {BABYLON.Scene} object
  1767. * @param source: the source node where to pick the matrix
  1768. * @param parameter: the GLTF technique parameter
  1769. * @param uniformName: the name of the shader's uniform
  1770. * @param shaderMaterial: the shader material
  1771. */
  1772. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1773. var mat = null;
  1774. if (parameter.semantic === "MODEL") {
  1775. mat = source.getWorldMatrix();
  1776. }
  1777. else if (parameter.semantic === "PROJECTION") {
  1778. mat = scene.getProjectionMatrix();
  1779. }
  1780. else if (parameter.semantic === "VIEW") {
  1781. mat = scene.getViewMatrix();
  1782. }
  1783. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1784. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1785. }
  1786. else if (parameter.semantic === "MODELVIEW") {
  1787. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1788. }
  1789. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1790. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1791. }
  1792. else if (parameter.semantic === "MODELINVERSE") {
  1793. mat = source.getWorldMatrix().invert();
  1794. }
  1795. else if (parameter.semantic === "VIEWINVERSE") {
  1796. mat = scene.getViewMatrix().invert();
  1797. }
  1798. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1799. mat = scene.getProjectionMatrix().invert();
  1800. }
  1801. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1802. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1803. }
  1804. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1805. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1806. }
  1807. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1808. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  1809. }
  1810. else {
  1811. debugger;
  1812. }
  1813. switch (parameter.type) {
  1814. case GLTF1.EParameterType.FLOAT_MAT2:
  1815. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  1816. break;
  1817. case GLTF1.EParameterType.FLOAT_MAT3:
  1818. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  1819. break;
  1820. case GLTF1.EParameterType.FLOAT_MAT4:
  1821. shaderMaterial.setMatrix(uniformName, mat);
  1822. break;
  1823. default: break;
  1824. }
  1825. };
  1826. /**
  1827. * Sets the given "parameter" matrix
  1828. * @param shaderMaterial: the shader material
  1829. * @param uniform: the name of the shader's uniform
  1830. * @param value: the value of the uniform
  1831. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1832. */
  1833. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1834. switch (type) {
  1835. case GLTF1.EParameterType.FLOAT:
  1836. shaderMaterial.setFloat(uniform, value);
  1837. return true;
  1838. case GLTF1.EParameterType.FLOAT_VEC2:
  1839. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  1840. return true;
  1841. case GLTF1.EParameterType.FLOAT_VEC3:
  1842. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  1843. return true;
  1844. case GLTF1.EParameterType.FLOAT_VEC4:
  1845. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  1846. return true;
  1847. default: return false;
  1848. }
  1849. };
  1850. /**
  1851. * If the uri is a base64 string
  1852. * @param uri: the uri to test
  1853. */
  1854. GLTFUtils.IsBase64 = function (uri) {
  1855. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1856. };
  1857. /**
  1858. * Decode the base64 uri
  1859. * @param uri: the uri to decode
  1860. */
  1861. GLTFUtils.DecodeBase64 = function (uri) {
  1862. var decodedString = atob(uri.split(",")[1]);
  1863. var bufferLength = decodedString.length;
  1864. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1865. for (var i = 0; i < bufferLength; i++) {
  1866. bufferView[i] = decodedString.charCodeAt(i);
  1867. }
  1868. return bufferView.buffer;
  1869. };
  1870. /**
  1871. * Returns the wrap mode of the texture
  1872. * @param mode: the mode value
  1873. */
  1874. GLTFUtils.GetWrapMode = function (mode) {
  1875. switch (mode) {
  1876. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1877. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1878. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1879. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1880. }
  1881. };
  1882. /**
  1883. * Returns the byte stride giving an accessor
  1884. * @param accessor: the GLTF accessor objet
  1885. */
  1886. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1887. // Needs this function since "byteStride" isn't requiered in glTF format
  1888. var type = accessor.type;
  1889. switch (type) {
  1890. case "VEC2": return 2;
  1891. case "VEC3": return 3;
  1892. case "VEC4": return 4;
  1893. case "MAT2": return 4;
  1894. case "MAT3": return 9;
  1895. case "MAT4": return 16;
  1896. default: return 1;
  1897. }
  1898. };
  1899. /**
  1900. * Returns the texture filter mode giving a mode value
  1901. * @param mode: the filter mode value
  1902. */
  1903. GLTFUtils.GetTextureFilterMode = function (mode) {
  1904. switch (mode) {
  1905. case GLTF1.ETextureFilterType.LINEAR:
  1906. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1907. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1908. case GLTF1.ETextureFilterType.NEAREST:
  1909. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1910. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1911. }
  1912. };
  1913. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  1914. var byteOffset = bufferView.byteOffset + byteOffset;
  1915. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  1916. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1917. throw new Error("Buffer access is out of range");
  1918. }
  1919. var buffer = loadedBufferView.buffer;
  1920. byteOffset += loadedBufferView.byteOffset;
  1921. switch (componentType) {
  1922. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1923. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1924. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1925. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1926. default: return new Float32Array(buffer, byteOffset, byteLength);
  1927. }
  1928. };
  1929. /**
  1930. * Returns a buffer from its accessor
  1931. * @param gltfRuntime: the GLTF runtime
  1932. * @param accessor: the GLTF accessor
  1933. */
  1934. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1935. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1936. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1937. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1938. };
  1939. /**
  1940. * Decodes a buffer view into a string
  1941. * @param view: the buffer view
  1942. */
  1943. GLTFUtils.DecodeBufferToText = function (view) {
  1944. var result = "";
  1945. var length = view.byteLength;
  1946. for (var i = 0; i < length; ++i) {
  1947. result += String.fromCharCode(view[i]);
  1948. }
  1949. return result;
  1950. };
  1951. /**
  1952. * Returns the default material of gltf. Related to
  1953. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  1954. * @param scene: the Babylon.js scene
  1955. */
  1956. GLTFUtils.GetDefaultMaterial = function (scene) {
  1957. if (!GLTFUtils._DefaultMaterial) {
  1958. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  1959. "precision highp float;",
  1960. "",
  1961. "uniform mat4 worldView;",
  1962. "uniform mat4 projection;",
  1963. "",
  1964. "attribute vec3 position;",
  1965. "",
  1966. "void main(void)",
  1967. "{",
  1968. " gl_Position = projection * worldView * vec4(position, 1.0);",
  1969. "}"
  1970. ].join("\n");
  1971. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  1972. "precision highp float;",
  1973. "",
  1974. "uniform vec4 u_emission;",
  1975. "",
  1976. "void main(void)",
  1977. "{",
  1978. " gl_FragColor = u_emission;",
  1979. "}"
  1980. ].join("\n");
  1981. var shaderPath = {
  1982. vertex: "GLTFDefaultMaterial",
  1983. fragment: "GLTFDefaultMaterial"
  1984. };
  1985. var options = {
  1986. attributes: ["position"],
  1987. uniforms: ["worldView", "projection", "u_emission"],
  1988. samplers: [],
  1989. needAlphaBlending: false
  1990. };
  1991. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  1992. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  1993. }
  1994. return GLTFUtils._DefaultMaterial;
  1995. };
  1996. return GLTFUtils;
  1997. }());
  1998. // The GLTF default material
  1999. GLTFUtils._DefaultMaterial = null;
  2000. GLTF1.GLTFUtils = GLTFUtils;
  2001. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2002. })(BABYLON || (BABYLON = {}));
  2003. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  2004. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2005. var BABYLON;
  2006. (function (BABYLON) {
  2007. var GLTF1;
  2008. (function (GLTF1) {
  2009. var GLTFLoaderExtension = (function () {
  2010. function GLTFLoaderExtension(name) {
  2011. this._name = name;
  2012. }
  2013. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  2014. get: function () {
  2015. return this._name;
  2016. },
  2017. enumerable: true,
  2018. configurable: true
  2019. });
  2020. /**
  2021. * Defines an override for loading the runtime
  2022. * Return true to stop further extensions from loading the runtime
  2023. */
  2024. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2025. return false;
  2026. };
  2027. /**
  2028. * Defines an onverride for creating gltf runtime
  2029. * Return true to stop further extensions from creating the runtime
  2030. */
  2031. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2032. return false;
  2033. };
  2034. /**
  2035. * Defines an override for loading buffers
  2036. * Return true to stop further extensions from loading this buffer
  2037. */
  2038. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2039. return false;
  2040. };
  2041. /**
  2042. * Defines an override for loading texture buffers
  2043. * Return true to stop further extensions from loading this texture data
  2044. */
  2045. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2046. return false;
  2047. };
  2048. /**
  2049. * Defines an override for creating textures
  2050. * Return true to stop further extensions from loading this texture
  2051. */
  2052. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2053. return false;
  2054. };
  2055. /**
  2056. * Defines an override for loading shader strings
  2057. * Return true to stop further extensions from loading this shader data
  2058. */
  2059. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2060. return false;
  2061. };
  2062. /**
  2063. * Defines an override for loading materials
  2064. * Return true to stop further extensions from loading this material
  2065. */
  2066. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2067. return false;
  2068. };
  2069. // ---------
  2070. // Utilities
  2071. // ---------
  2072. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2073. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2074. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  2075. }, function () {
  2076. setTimeout(function () {
  2077. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2078. });
  2079. });
  2080. };
  2081. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2082. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2083. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  2084. }, function () {
  2085. setTimeout(function () {
  2086. onSuccess();
  2087. });
  2088. });
  2089. };
  2090. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  2091. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2092. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2093. }, function () {
  2094. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  2095. });
  2096. };
  2097. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  2098. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  2099. };
  2100. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2101. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2102. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2103. }, function () {
  2104. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  2105. });
  2106. };
  2107. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2108. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2109. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2110. }, function () {
  2111. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  2112. });
  2113. };
  2114. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2115. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2116. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2117. }, function () {
  2118. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  2119. });
  2120. };
  2121. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  2122. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  2123. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2124. }, function () {
  2125. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  2126. });
  2127. };
  2128. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  2129. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  2130. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  2131. if (func(loaderExtension)) {
  2132. return;
  2133. }
  2134. }
  2135. defaultFunc();
  2136. };
  2137. return GLTFLoaderExtension;
  2138. }());
  2139. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  2140. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2141. })(BABYLON || (BABYLON = {}));
  2142. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  2143. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2144. var __extends = (this && this.__extends) || (function () {
  2145. var extendStatics = Object.setPrototypeOf ||
  2146. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2147. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2148. return function (d, b) {
  2149. extendStatics(d, b);
  2150. function __() { this.constructor = d; }
  2151. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2152. };
  2153. })();
  2154. var BABYLON;
  2155. (function (BABYLON) {
  2156. var GLTF1;
  2157. (function (GLTF1) {
  2158. var BinaryExtensionBufferName = "binary_glTF";
  2159. var EContentFormat;
  2160. (function (EContentFormat) {
  2161. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  2162. })(EContentFormat || (EContentFormat = {}));
  2163. ;
  2164. ;
  2165. ;
  2166. var GLTFBinaryExtension = (function (_super) {
  2167. __extends(GLTFBinaryExtension, _super);
  2168. function GLTFBinaryExtension() {
  2169. return _super.call(this, "KHR_binary_glTF") || this;
  2170. }
  2171. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  2172. var extensionsUsed = data.json.extensionsUsed;
  2173. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1) {
  2174. return false;
  2175. }
  2176. this._bin = data.bin;
  2177. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  2178. return true;
  2179. };
  2180. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2181. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  2182. return false;
  2183. }
  2184. if (id !== BinaryExtensionBufferName) {
  2185. return false;
  2186. }
  2187. onSuccess(this._bin);
  2188. return true;
  2189. };
  2190. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  2191. var texture = gltfRuntime.textures[id];
  2192. var source = gltfRuntime.images[texture.source];
  2193. if (!source.extensions || !(this.name in source.extensions)) {
  2194. return false;
  2195. }
  2196. var sourceExt = source.extensions[this.name];
  2197. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  2198. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2199. onSuccess(buffer);
  2200. return true;
  2201. };
  2202. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  2203. var shader = gltfRuntime.shaders[id];
  2204. if (!shader.extensions || !(this.name in shader.extensions)) {
  2205. return false;
  2206. }
  2207. var binaryExtensionShader = shader.extensions[this.name];
  2208. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  2209. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  2210. setTimeout(function () {
  2211. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  2212. onSuccess(shaderString);
  2213. });
  2214. return true;
  2215. };
  2216. return GLTFBinaryExtension;
  2217. }(GLTF1.GLTFLoaderExtension));
  2218. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  2219. var BinaryReader = (function () {
  2220. function BinaryReader(arrayBuffer) {
  2221. this._arrayBuffer = arrayBuffer;
  2222. this._dataView = new DataView(arrayBuffer);
  2223. this._byteOffset = 0;
  2224. }
  2225. BinaryReader.prototype.getUint32 = function () {
  2226. var value = this._dataView.getUint32(this._byteOffset, true);
  2227. this._byteOffset += 4;
  2228. return value;
  2229. };
  2230. BinaryReader.prototype.getUint8Array = function (length) {
  2231. if (!length) {
  2232. length = this._arrayBuffer.byteLength - this._byteOffset;
  2233. }
  2234. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  2235. this._byteOffset += length;
  2236. return value;
  2237. };
  2238. return BinaryReader;
  2239. }());
  2240. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  2241. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2242. })(BABYLON || (BABYLON = {}));
  2243. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  2244. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2245. var __extends = (this && this.__extends) || (function () {
  2246. var extendStatics = Object.setPrototypeOf ||
  2247. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2248. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2249. return function (d, b) {
  2250. extendStatics(d, b);
  2251. function __() { this.constructor = d; }
  2252. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2253. };
  2254. })();
  2255. var BABYLON;
  2256. (function (BABYLON) {
  2257. var GLTF1;
  2258. (function (GLTF1) {
  2259. ;
  2260. ;
  2261. ;
  2262. var GLTFMaterialsCommonExtension = (function (_super) {
  2263. __extends(GLTFMaterialsCommonExtension, _super);
  2264. function GLTFMaterialsCommonExtension() {
  2265. return _super.call(this, "KHR_materials_common") || this;
  2266. }
  2267. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  2268. if (!gltfRuntime.extensions)
  2269. return false;
  2270. var extension = gltfRuntime.extensions[this.name];
  2271. if (!extension)
  2272. return false;
  2273. // Create lights
  2274. var lights = extension.lights;
  2275. if (lights) {
  2276. for (var thing in lights) {
  2277. var light = lights[thing];
  2278. switch (light.type) {
  2279. case "ambient":
  2280. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  2281. var ambient = light.ambient;
  2282. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  2283. break;
  2284. case "point":
  2285. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  2286. var point = light.point;
  2287. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  2288. break;
  2289. case "directional":
  2290. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  2291. var directional = light.directional;
  2292. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  2293. break;
  2294. case "spot":
  2295. var spot = light.spot;
  2296. 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);
  2297. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  2298. break;
  2299. default:
  2300. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  2301. break;
  2302. }
  2303. }
  2304. }
  2305. return false;
  2306. };
  2307. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  2308. var material = gltfRuntime.materials[id];
  2309. if (!material || !material.extensions)
  2310. return false;
  2311. var extension = material.extensions[this.name];
  2312. if (!extension)
  2313. return false;
  2314. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  2315. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  2316. if (extension.technique === "CONSTANT") {
  2317. standardMaterial.disableLighting = true;
  2318. }
  2319. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  2320. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  2321. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  2322. // Ambient
  2323. if (typeof extension.values.ambient === "string") {
  2324. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  2325. }
  2326. else {
  2327. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  2328. }
  2329. // Diffuse
  2330. if (typeof extension.values.diffuse === "string") {
  2331. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  2332. }
  2333. else {
  2334. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  2335. }
  2336. // Emission
  2337. if (typeof extension.values.emission === "string") {
  2338. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  2339. }
  2340. else {
  2341. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  2342. }
  2343. // Specular
  2344. if (typeof extension.values.specular === "string") {
  2345. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  2346. }
  2347. else {
  2348. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  2349. }
  2350. return true;
  2351. };
  2352. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  2353. // Create buffer from texture url
  2354. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  2355. // Create texture from buffer
  2356. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  2357. }, onError);
  2358. };
  2359. return GLTFMaterialsCommonExtension;
  2360. }(GLTF1.GLTFLoaderExtension));
  2361. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  2362. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  2363. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  2364. })(BABYLON || (BABYLON = {}));
  2365. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  2366. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2367. var BABYLON;
  2368. (function (BABYLON) {
  2369. var GLTF2;
  2370. (function (GLTF2) {
  2371. /**
  2372. * Enums
  2373. */
  2374. var EComponentType;
  2375. (function (EComponentType) {
  2376. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  2377. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  2378. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  2379. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  2380. EComponentType[EComponentType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  2381. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  2382. })(EComponentType = GLTF2.EComponentType || (GLTF2.EComponentType = {}));
  2383. var EMeshPrimitiveMode;
  2384. (function (EMeshPrimitiveMode) {
  2385. EMeshPrimitiveMode[EMeshPrimitiveMode["POINTS"] = 0] = "POINTS";
  2386. EMeshPrimitiveMode[EMeshPrimitiveMode["LINES"] = 1] = "LINES";
  2387. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_LOOP"] = 2] = "LINE_LOOP";
  2388. EMeshPrimitiveMode[EMeshPrimitiveMode["LINE_STRIP"] = 3] = "LINE_STRIP";
  2389. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLES"] = 4] = "TRIANGLES";
  2390. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  2391. EMeshPrimitiveMode[EMeshPrimitiveMode["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  2392. })(EMeshPrimitiveMode = GLTF2.EMeshPrimitiveMode || (GLTF2.EMeshPrimitiveMode = {}));
  2393. var ETextureMagFilter;
  2394. (function (ETextureMagFilter) {
  2395. ETextureMagFilter[ETextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  2396. ETextureMagFilter[ETextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  2397. })(ETextureMagFilter = GLTF2.ETextureMagFilter || (GLTF2.ETextureMagFilter = {}));
  2398. var ETextureMinFilter;
  2399. (function (ETextureMinFilter) {
  2400. ETextureMinFilter[ETextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  2401. ETextureMinFilter[ETextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  2402. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  2403. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  2404. ETextureMinFilter[ETextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  2405. ETextureMinFilter[ETextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  2406. })(ETextureMinFilter = GLTF2.ETextureMinFilter || (GLTF2.ETextureMinFilter = {}));
  2407. var ETextureWrapMode;
  2408. (function (ETextureWrapMode) {
  2409. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  2410. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  2411. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  2412. })(ETextureWrapMode = GLTF2.ETextureWrapMode || (GLTF2.ETextureWrapMode = {}));
  2413. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2414. })(BABYLON || (BABYLON = {}));
  2415. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  2416. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2417. var BABYLON;
  2418. (function (BABYLON) {
  2419. var GLTF2;
  2420. (function (GLTF2) {
  2421. var getNodeID = function (index) {
  2422. return "node" + index;
  2423. };
  2424. var loadAnimation = function (runtime, animation, animationIndex) {
  2425. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  2426. var channel = animation.channels[channelIndex];
  2427. if (!channel) {
  2428. BABYLON.Tools.Warn("[Animation " + animationIndex + "] Channel " + channelIndex + " does not exist");
  2429. continue;
  2430. }
  2431. var samplerIndex = channel.sampler;
  2432. if (samplerIndex === undefined) {
  2433. BABYLON.Tools.Warn("[Animation " + animationIndex + ", Channel + " + samplerIndex + "] Sampler is not defined");
  2434. continue;
  2435. }
  2436. var sampler = animation.samplers[samplerIndex];
  2437. if (!sampler) {
  2438. BABYLON.Tools.Warn("[Animation " + animationIndex + ", Channel + " + channelIndex + "] Sampler " + samplerIndex + " does not exist");
  2439. continue;
  2440. }
  2441. if (!channel.target) {
  2442. BABYLON.Tools.Warn("[Animation " + animationIndex + ", Channel + " + channelIndex + "] Target does not exist");
  2443. continue;
  2444. }
  2445. var targetNode = runtime.babylonScene.getNodeByID(getNodeID(channel.target.node));
  2446. if (!targetNode) {
  2447. BABYLON.Tools.Warn("[Animation " + animationIndex + ", Channel + " + channelIndex + "] Target node " + channel.target.node + " does not exist");
  2448. continue;
  2449. }
  2450. var targetPath = {
  2451. "translation": "position",
  2452. "rotation": "rotationQuaternion",
  2453. "scale": "scaling",
  2454. "weights": "influence"
  2455. }[channel.target.path];
  2456. if (!targetPath) {
  2457. BABYLON.Tools.Warn("[Animation " + animationIndex + ", Channel + " + channelIndex + "] Target path " + channel.target.path + " is invalid");
  2458. continue;
  2459. }
  2460. var inputBuffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, runtime.gltf.accessors[sampler.input]);
  2461. var outputBuffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, runtime.gltf.accessors[sampler.output]);
  2462. var outputBufferOffset = 0;
  2463. var animationType = {
  2464. "position": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  2465. "rotationQuaternion": BABYLON.Animation.ANIMATIONTYPE_QUATERNION,
  2466. "scale": BABYLON.Animation.ANIMATIONTYPE_VECTOR3,
  2467. "influence": BABYLON.Animation.ANIMATIONTYPE_FLOAT,
  2468. }[targetPath];
  2469. var getNextOutputValue = {
  2470. "position": function () {
  2471. var value = BABYLON.Vector3.FromArray(outputBuffer, outputBufferOffset);
  2472. outputBufferOffset += 3;
  2473. return value;
  2474. },
  2475. "rotationQuaternion": function () {
  2476. var value = BABYLON.Quaternion.FromArray(outputBuffer, outputBufferOffset);
  2477. outputBufferOffset += 4;
  2478. return value;
  2479. },
  2480. "scale": function () {
  2481. var value = BABYLON.Vector3.FromArray(outputBuffer, outputBufferOffset);
  2482. outputBufferOffset += 3;
  2483. return value;
  2484. },
  2485. "influence": function () {
  2486. var numTargets = targetNode.morphTargetManager.numTargets;
  2487. var value = new Array(numTargets);
  2488. for (var i = 0; i < numTargets; i++) {
  2489. value[i] = outputBuffer[outputBufferOffset++];
  2490. }
  2491. return value;
  2492. },
  2493. }[targetPath];
  2494. var getNextKey = {
  2495. "LINEAR": function (frameIndex) { return ({
  2496. frame: inputBuffer[frameIndex],
  2497. value: getNextOutputValue()
  2498. }); },
  2499. "CUBICSPLINE": function (frameIndex) { return ({
  2500. frame: inputBuffer[frameIndex],
  2501. inTangent: getNextOutputValue(),
  2502. value: getNextOutputValue(),
  2503. outTangent: getNextOutputValue()
  2504. }); },
  2505. }[sampler.interpolation];
  2506. if (!getNextKey) {
  2507. BABYLON.Tools.Warn("[Animation " + animationIndex + ", Channel + " + channelIndex + "] Sampler interpolation '" + sampler.interpolation + "' is invalid");
  2508. continue;
  2509. }
  2510. var keys = new Array(inputBuffer.length);
  2511. for (var frameIndex = 0; frameIndex < inputBuffer.length; frameIndex++) {
  2512. keys[frameIndex] = getNextKey(frameIndex);
  2513. }
  2514. if (targetPath === "influence") {
  2515. var targetMesh = targetNode;
  2516. for (var targetIndex = 0; targetIndex < targetMesh.morphTargetManager.numTargets; targetIndex++) {
  2517. var morphTarget = targetMesh.morphTargetManager.getTarget(targetIndex);
  2518. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  2519. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  2520. babylonAnimation.setKeys(keys.map(function (key) { return ({
  2521. frame: key.frame,
  2522. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  2523. value: key.value[targetIndex],
  2524. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  2525. }); }));
  2526. morphTarget.animations.push(babylonAnimation);
  2527. runtime.babylonScene.beginAnimation(morphTarget, 0, inputBuffer[inputBuffer.length - 1], true);
  2528. }
  2529. }
  2530. else {
  2531. var animationName = animation.name || "anim" + animationIndex;
  2532. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  2533. babylonAnimation.setKeys(keys);
  2534. targetNode.animations.push(babylonAnimation);
  2535. runtime.babylonScene.beginAnimation(targetNode, 0, inputBuffer[inputBuffer.length - 1], true);
  2536. }
  2537. }
  2538. };
  2539. /**
  2540. * Loads and creates animations
  2541. */
  2542. var loadAnimations = function (runtime) {
  2543. var animations = runtime.gltf.animations;
  2544. if (!animations || animations.length === 0) {
  2545. return;
  2546. }
  2547. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  2548. var animation = animations[animationIndex];
  2549. if (!animation) {
  2550. BABYLON.Tools.Warn("Animation " + animationIndex + " not found");
  2551. continue;
  2552. }
  2553. if (!animation.channels || animation.channels.length === 0) {
  2554. BABYLON.Tools.Warn("Animation " + animationIndex + " has no channels");
  2555. }
  2556. if (!animation.samplers || animation.samplers.length === 0) {
  2557. BABYLON.Tools.Warn("Animation " + animationIndex + " has no samplers");
  2558. continue;
  2559. }
  2560. loadAnimation(runtime, animation, animationIndex);
  2561. }
  2562. };
  2563. /**
  2564. * Returns the bones transformation matrix
  2565. */
  2566. var configureBoneTransformation = function (node) {
  2567. var mat = null;
  2568. if (node.translation || node.rotation || node.scale) {
  2569. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  2570. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  2571. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  2572. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  2573. }
  2574. else {
  2575. mat = node.matrix ? BABYLON.Matrix.FromArray(node.matrix) : BABYLON.Matrix.Identity();
  2576. }
  2577. return mat;
  2578. };
  2579. /**
  2580. * Returns the parent bone
  2581. */
  2582. var getParentBone = function (runtime, skin, index, newSkeleton) {
  2583. // Try to find
  2584. var nodeStringID = getNodeID(index);
  2585. for (var i = 0; i < newSkeleton.bones.length; i++) {
  2586. if (newSkeleton.bones[i].id === nodeStringID) {
  2587. return newSkeleton.bones[i].getParent();
  2588. }
  2589. }
  2590. // Not found, search in gltf nodes
  2591. var joints = skin.joints;
  2592. for (var j = 0; j < joints.length; j++) {
  2593. var parentID = joints[j];
  2594. var parent = runtime.gltf.nodes[parentID];
  2595. var children = parent.children;
  2596. for (var i = 0; i < children.length; i++) {
  2597. var childID = children[i];
  2598. var child = runtime.gltf.nodes[childID];
  2599. if (!nodeIsInJoints(skin, childID)) {
  2600. continue;
  2601. }
  2602. if (childID === index) {
  2603. var mat = configureBoneTransformation(parent);
  2604. var bone = new BABYLON.Bone(parent.name || getNodeID(parentID), newSkeleton, getParentBone(runtime, skin, parentID, newSkeleton), mat);
  2605. bone.id = getNodeID(parentID);
  2606. return bone;
  2607. }
  2608. }
  2609. }
  2610. return null;
  2611. };
  2612. /**
  2613. * Returns the appropriate root node
  2614. */
  2615. var getNodeToRoot = function (nodesToRoot, index) {
  2616. for (var i = 0; i < nodesToRoot.length; i++) {
  2617. var nodeToRoot = nodesToRoot[i];
  2618. if (nodeToRoot.node.children) {
  2619. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  2620. var child = nodeToRoot.node.children[j];
  2621. if (child === index) {
  2622. return nodeToRoot.bone;
  2623. }
  2624. }
  2625. }
  2626. }
  2627. return null;
  2628. };
  2629. /**
  2630. * Returns the node with the node index
  2631. */
  2632. var getJointNode = function (runtime, index) {
  2633. var node = runtime.gltf.nodes[index];
  2634. if (node) {
  2635. return {
  2636. node: node,
  2637. index: index
  2638. };
  2639. }
  2640. return null;
  2641. };
  2642. /**
  2643. * Checks if a nodes is in joints
  2644. */
  2645. var nodeIsInJoints = function (skin, index) {
  2646. for (var i = 0; i < skin.joints.length; i++) {
  2647. if (skin.joints[i] === index) {
  2648. return true;
  2649. }
  2650. }
  2651. return false;
  2652. };
  2653. /**
  2654. * Fills the nodes to root for bones and builds hierarchy
  2655. */
  2656. var getNodesToRoot = function (runtime, newSkeleton, skin, nodesToRoot) {
  2657. // Creates nodes for root
  2658. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  2659. var node = runtime.gltf.nodes[i];
  2660. if (nodeIsInJoints(skin, i)) {
  2661. continue;
  2662. }
  2663. // Create node to root bone
  2664. var mat = configureBoneTransformation(node);
  2665. var bone = new BABYLON.Bone(node.name || getNodeID(i), newSkeleton, null, mat);
  2666. bone.id = getNodeID(i);
  2667. nodesToRoot.push({ bone: bone, node: node, index: i });
  2668. }
  2669. // Parenting
  2670. for (var i = 0; i < nodesToRoot.length; i++) {
  2671. var nodeToRoot = nodesToRoot[i];
  2672. var children = nodeToRoot.node.children;
  2673. if (children) {
  2674. for (var j = 0; j < children.length; j++) {
  2675. var child = null;
  2676. for (var k = 0; k < nodesToRoot.length; k++) {
  2677. if (nodesToRoot[k].index === children[j]) {
  2678. child = nodesToRoot[k];
  2679. break;
  2680. }
  2681. }
  2682. if (child) {
  2683. child.bone._parent = nodeToRoot.bone;
  2684. nodeToRoot.bone.children.push(child.bone);
  2685. }
  2686. }
  2687. }
  2688. }
  2689. };
  2690. /**
  2691. * Imports a skeleton
  2692. */
  2693. var importSkeleton = function (runtime, skinNode, skin) {
  2694. var name = skin.name || "skin" + skinNode.skin;
  2695. var babylonSkeleton = skin.babylonSkeleton;
  2696. if (!babylonSkeleton) {
  2697. babylonSkeleton = new BABYLON.Skeleton(name, "skin" + skinNode.skin, runtime.babylonScene);
  2698. }
  2699. if (!skin.babylonSkeleton) {
  2700. return babylonSkeleton;
  2701. }
  2702. // Matrices
  2703. var accessor = runtime.gltf.accessors[skin.inverseBindMatrices];
  2704. var buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  2705. // Find the root bones
  2706. var nodesToRoot = [];
  2707. var nodesToRootToAdd = [];
  2708. getNodesToRoot(runtime, babylonSkeleton, skin, nodesToRoot);
  2709. babylonSkeleton.bones = [];
  2710. // Joints
  2711. for (var i = 0; i < skin.joints.length; i++) {
  2712. var jointNode = getJointNode(runtime, skin.joints[i]);
  2713. var node = jointNode.node;
  2714. if (!node) {
  2715. BABYLON.Tools.Warn("Joint index " + skin.joints[i] + " does not exist");
  2716. continue;
  2717. }
  2718. var index = jointNode.index;
  2719. var stringID = getNodeID(index);
  2720. // Optimize, if the bone already exists...
  2721. var existingBone = runtime.babylonScene.getBoneByID(stringID);
  2722. if (existingBone) {
  2723. babylonSkeleton.bones.push(existingBone);
  2724. continue;
  2725. }
  2726. // Search for parent bone
  2727. var foundBone = false;
  2728. var parentBone = null;
  2729. for (var j = 0; j < i; j++) {
  2730. var joint = getJointNode(runtime, skin.joints[j]).node;
  2731. if (!joint) {
  2732. BABYLON.Tools.Warn("Joint index " + skin.joints[j] + " does not exist when looking for parent");
  2733. continue;
  2734. }
  2735. var children = joint.children;
  2736. foundBone = false;
  2737. for (var k = 0; k < children.length; k++) {
  2738. if (children[k] === index) {
  2739. parentBone = getParentBone(runtime, skin, skin.joints[j], babylonSkeleton);
  2740. foundBone = true;
  2741. break;
  2742. }
  2743. }
  2744. if (foundBone) {
  2745. break;
  2746. }
  2747. }
  2748. // Create bone
  2749. var mat = configureBoneTransformation(node);
  2750. if (!parentBone && nodesToRoot.length > 0) {
  2751. parentBone = getNodeToRoot(nodesToRoot, index);
  2752. if (parentBone) {
  2753. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  2754. nodesToRootToAdd.push(parentBone);
  2755. }
  2756. }
  2757. }
  2758. var bone = new BABYLON.Bone(node.name || stringID, babylonSkeleton, parentBone, mat);
  2759. bone.id = stringID;
  2760. }
  2761. // Polish
  2762. var bones = babylonSkeleton.bones;
  2763. babylonSkeleton.bones = [];
  2764. for (var i = 0; i < skin.joints.length; i++) {
  2765. var jointNode = getJointNode(runtime, skin.joints[i]);
  2766. if (!jointNode) {
  2767. continue;
  2768. }
  2769. var jointNodeStringId = getNodeID(jointNode.index);
  2770. for (var j = 0; j < bones.length; j++) {
  2771. if (bones[j].id === jointNodeStringId) {
  2772. babylonSkeleton.bones.push(bones[j]);
  2773. break;
  2774. }
  2775. }
  2776. }
  2777. babylonSkeleton.prepare();
  2778. // Finish
  2779. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  2780. babylonSkeleton.bones.push(nodesToRootToAdd[i]);
  2781. }
  2782. return babylonSkeleton;
  2783. };
  2784. /**
  2785. * Gets a material
  2786. */
  2787. var getMaterial = function (runtime, index) {
  2788. if (index === undefined) {
  2789. return GLTF2.GLTFUtils.GetDefaultMaterial(runtime);
  2790. }
  2791. var materials = runtime.gltf.materials;
  2792. if (!materials || index < 0 || index >= materials.length) {
  2793. BABYLON.Tools.Error("Invalid material index");
  2794. return GLTF2.GLTFUtils.GetDefaultMaterial(runtime);
  2795. }
  2796. var material = runtime.gltf.materials[index].babylonMaterial;
  2797. if (!material) {
  2798. return GLTF2.GLTFUtils.GetDefaultMaterial(runtime);
  2799. }
  2800. return material;
  2801. };
  2802. /**
  2803. * Imports a mesh and its geometries
  2804. */
  2805. var importMesh = function (runtime, node, mesh) {
  2806. var name = mesh.name || node.name || "mesh" + node.mesh;
  2807. var babylonMesh = node.babylonNode;
  2808. if (!babylonMesh) {
  2809. babylonMesh = new BABYLON.Mesh(name, runtime.babylonScene);
  2810. }
  2811. if (!node.babylonNode) {
  2812. return babylonMesh;
  2813. }
  2814. var multiMat = new BABYLON.MultiMaterial(name, runtime.babylonScene);
  2815. if (!babylonMesh.material) {
  2816. babylonMesh.material = multiMat;
  2817. }
  2818. var vertexData = new BABYLON.VertexData();
  2819. var geometry = new BABYLON.Geometry(name, runtime.babylonScene, vertexData, false, babylonMesh);
  2820. var verticesStarts = [];
  2821. var verticesCounts = [];
  2822. var indexStarts = [];
  2823. var indexCounts = [];
  2824. var morphTargetManager;
  2825. // Positions, normals and UVs
  2826. for (var primitiveIndex = 0; primitiveIndex < mesh.primitives.length; primitiveIndex++) {
  2827. // Temporary vertex data
  2828. var tempVertexData = new BABYLON.VertexData();
  2829. var primitive = mesh.primitives[primitiveIndex];
  2830. if (primitive.mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  2831. // continue;
  2832. }
  2833. var attributes = primitive.attributes;
  2834. var accessor = null;
  2835. var buffer = null;
  2836. // Set positions, normal and uvs
  2837. for (var semantic in attributes) {
  2838. // Link accessor and buffer view
  2839. accessor = runtime.gltf.accessors[attributes[semantic]];
  2840. buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  2841. if (semantic === "NORMAL") {
  2842. tempVertexData.normals = buffer;
  2843. }
  2844. else if (semantic === "POSITION") {
  2845. tempVertexData.positions = buffer;
  2846. verticesCounts.push(tempVertexData.positions.length);
  2847. }
  2848. else if (semantic === "TANGENT") {
  2849. tempVertexData.tangents = buffer;
  2850. }
  2851. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  2852. var channel = Number(semantic.split("_")[1]);
  2853. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  2854. tempVertexData.set(buffer, uvKind);
  2855. }
  2856. else if (semantic === "JOINT") {
  2857. tempVertexData.matricesIndices = buffer;
  2858. }
  2859. else if (semantic === "WEIGHT") {
  2860. tempVertexData.matricesWeights = buffer;
  2861. }
  2862. else if (semantic === "COLOR_0") {
  2863. tempVertexData.colors = buffer;
  2864. }
  2865. else {
  2866. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  2867. }
  2868. }
  2869. // Indices
  2870. accessor = runtime.gltf.accessors[primitive.indices];
  2871. if (accessor) {
  2872. buffer = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  2873. tempVertexData.indices = buffer;
  2874. indexCounts.push(tempVertexData.indices.length);
  2875. }
  2876. else {
  2877. // Set indices on the fly
  2878. tempVertexData.indices = new Uint32Array(tempVertexData.positions.length / 3);
  2879. for (var index = 0; index < tempVertexData.indices.length; index++) {
  2880. tempVertexData.indices[index] = index;
  2881. }
  2882. indexCounts.push(tempVertexData.indices.length);
  2883. }
  2884. vertexData.merge(tempVertexData);
  2885. tempVertexData = undefined;
  2886. // Sub material
  2887. var material = getMaterial(runtime, primitive.material);
  2888. multiMat.subMaterials.push(material);
  2889. // Morph Targets
  2890. if (primitive.targets) {
  2891. for (var targetsIndex = 0; targetsIndex < primitive.targets.length; targetsIndex++) {
  2892. var target = primitive.targets[targetsIndex];
  2893. var weight = 0.0;
  2894. if (node.weights) {
  2895. weight = node.weights[targetsIndex];
  2896. }
  2897. else if (mesh.weights) {
  2898. weight = mesh.weights[targetsIndex];
  2899. }
  2900. var morph = new BABYLON.MorphTarget("morph" + targetsIndex, weight);
  2901. for (var semantic in target) {
  2902. // Link accessor and buffer view
  2903. accessor = runtime.gltf.accessors[target[semantic]];
  2904. var values = GLTF2.GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  2905. if (accessor.name) {
  2906. morph.name = accessor.name;
  2907. }
  2908. // glTF stores morph target information as deltas
  2909. // while babylon.js expects the final data.
  2910. // As a result we have to add the original data to the delta to calculate
  2911. // the final data.
  2912. if (semantic === "NORMAL") {
  2913. for (var i = 0; i < values.length; i++) {
  2914. values[i] += vertexData.normals[i];
  2915. }
  2916. morph.setNormals(values);
  2917. }
  2918. else if (semantic === "POSITION") {
  2919. for (var i = 0; i < values.length; i++) {
  2920. values[i] += vertexData.positions[i];
  2921. }
  2922. morph.setPositions(values);
  2923. }
  2924. else if (semantic === "TANGENT") {
  2925. // Tangent data for morph targets is stored as xyz delta.
  2926. // The vertexData.tangent is stored as xyzw.
  2927. // So we need to skip every fourth vertexData.tangent.
  2928. for (var i = 0, j = 0; i < values.length; i++, j++) {
  2929. values[i] += vertexData.tangents[j];
  2930. if ((i + 1) % 3 == 0) {
  2931. j++;
  2932. }
  2933. }
  2934. morph.setTangents(values);
  2935. }
  2936. else {
  2937. BABYLON.Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  2938. }
  2939. }
  2940. if (morph.getPositions()) {
  2941. if (!morphTargetManager) {
  2942. morphTargetManager = new BABYLON.MorphTargetManager();
  2943. babylonMesh.morphTargetManager = morphTargetManager;
  2944. }
  2945. morphTargetManager.addTarget(morph);
  2946. }
  2947. else {
  2948. BABYLON.Tools.Warn("Not adding morph target '" + morph.name + "' because it has no position data");
  2949. }
  2950. }
  2951. }
  2952. // Update vertices start and index start
  2953. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  2954. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  2955. }
  2956. // Apply geometry
  2957. geometry.setAllVerticesData(vertexData, false);
  2958. babylonMesh.computeWorldMatrix(true);
  2959. // Apply submeshes
  2960. babylonMesh.subMeshes = [];
  2961. for (var primitiveIndex = 0; primitiveIndex < mesh.primitives.length; primitiveIndex++) {
  2962. if (mesh.primitives[primitiveIndex].mode !== GLTF2.EMeshPrimitiveMode.TRIANGLES) {
  2963. //continue;
  2964. }
  2965. var subMesh = new BABYLON.SubMesh(primitiveIndex, verticesStarts[primitiveIndex], verticesCounts[primitiveIndex], indexStarts[primitiveIndex], indexCounts[primitiveIndex], babylonMesh, babylonMesh, true);
  2966. }
  2967. // Finish
  2968. return babylonMesh;
  2969. };
  2970. /**
  2971. * Configures node transformation
  2972. */
  2973. var configureNode = function (babylonNode, node) {
  2974. var position = BABYLON.Vector3.Zero();
  2975. var rotation = BABYLON.Quaternion.Identity();
  2976. var scaling = new BABYLON.Vector3(1, 1, 1);
  2977. if (node.matrix) {
  2978. var mat = BABYLON.Matrix.FromArray(node.matrix);
  2979. mat.decompose(scaling, rotation, position);
  2980. }
  2981. else {
  2982. if (node.translation) {
  2983. position = BABYLON.Vector3.FromArray(node.translation);
  2984. }
  2985. if (node.rotation) {
  2986. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  2987. }
  2988. if (node.scale) {
  2989. scaling = BABYLON.Vector3.FromArray(node.scale);
  2990. }
  2991. }
  2992. babylonNode.position = position;
  2993. babylonNode.rotationQuaternion = rotation;
  2994. if (babylonNode instanceof BABYLON.Mesh) {
  2995. var mesh = babylonNode;
  2996. mesh.scaling = scaling;
  2997. }
  2998. };
  2999. /**
  3000. * Imports a node
  3001. */
  3002. var importNode = function (runtime, node) {
  3003. var babylonNode = null;
  3004. if (runtime.importOnlyMeshes && (node.skin !== undefined || node.mesh !== undefined)) {
  3005. if (runtime.importMeshesNames.length > 0 && runtime.importMeshesNames.indexOf(node.name) === -1) {
  3006. return null;
  3007. }
  3008. }
  3009. // Meshes
  3010. if (node.skin !== undefined) {
  3011. if (node.mesh !== undefined) {
  3012. var skin = runtime.gltf.skins[node.skin];
  3013. var newMesh = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  3014. var newSkeleton = importSkeleton(runtime, node, skin);
  3015. if (newSkeleton) {
  3016. newMesh.skeleton = newSkeleton;
  3017. skin.babylonSkeleton = newSkeleton;
  3018. }
  3019. babylonNode = newMesh;
  3020. }
  3021. }
  3022. else if (node.mesh !== undefined) {
  3023. babylonNode = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  3024. }
  3025. else if (node.camera !== undefined && !node.babylonNode && !runtime.importOnlyMeshes) {
  3026. var camera = runtime.gltf.cameras[node.camera];
  3027. if (camera !== undefined) {
  3028. if (camera.type === "orthographic") {
  3029. var orthographicCamera = camera.orthographic;
  3030. var orthoCamera = new BABYLON.FreeCamera(node.name || "camera" + node.camera, BABYLON.Vector3.Zero(), runtime.babylonScene);
  3031. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  3032. orthoCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  3033. babylonNode = orthoCamera;
  3034. }
  3035. else if (camera.type === "perspective") {
  3036. var perspectiveCamera = camera.perspective;
  3037. var persCamera = new BABYLON.FreeCamera(node.name || "camera" + node.camera, BABYLON.Vector3.Zero(), runtime.babylonScene);
  3038. persCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  3039. if (!perspectiveCamera.aspectRatio) {
  3040. perspectiveCamera.aspectRatio = runtime.babylonScene.getEngine().getRenderWidth() / runtime.babylonScene.getEngine().getRenderHeight();
  3041. }
  3042. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  3043. persCamera.maxZ = perspectiveCamera.zfar;
  3044. persCamera.minZ = perspectiveCamera.znear;
  3045. }
  3046. babylonNode = persCamera;
  3047. }
  3048. }
  3049. }
  3050. // Empty node
  3051. if (node.babylonNode) {
  3052. return node.babylonNode;
  3053. }
  3054. else if (babylonNode === null) {
  3055. var dummy = new BABYLON.Mesh(node.name || "mesh" + node.mesh, runtime.babylonScene);
  3056. node.babylonNode = dummy;
  3057. babylonNode = dummy;
  3058. }
  3059. if (babylonNode !== null) {
  3060. configureNode(babylonNode, node);
  3061. babylonNode.updateCache(true);
  3062. node.babylonNode = babylonNode;
  3063. }
  3064. return babylonNode;
  3065. };
  3066. /**
  3067. * Traverses nodes and creates them
  3068. */
  3069. var traverseNodes = function (runtime, index, parent, meshIncluded) {
  3070. var node = runtime.gltf.nodes[index];
  3071. var newNode = null;
  3072. if (runtime.importOnlyMeshes && !meshIncluded) {
  3073. if (runtime.importMeshesNames.indexOf(node.name) !== -1 || runtime.importMeshesNames.length === 0) {
  3074. meshIncluded = true;
  3075. }
  3076. else {
  3077. meshIncluded = false;
  3078. }
  3079. }
  3080. else {
  3081. meshIncluded = true;
  3082. }
  3083. if (meshIncluded) {
  3084. newNode = importNode(runtime, node);
  3085. if (newNode !== null) {
  3086. newNode.id = getNodeID(index);
  3087. newNode.parent = parent;
  3088. }
  3089. }
  3090. if (node.children) {
  3091. for (var i = 0; i < node.children.length; i++) {
  3092. traverseNodes(runtime, node.children[i], newNode, meshIncluded);
  3093. }
  3094. }
  3095. };
  3096. var importScene = function (runtime) {
  3097. var scene = runtime.gltf.scene || 0;
  3098. var scenes = runtime.gltf.scenes;
  3099. if (scenes) {
  3100. var nodes = scenes[scene].nodes;
  3101. for (var i = 0; i < nodes.length; i++) {
  3102. traverseNodes(runtime, nodes[i], null);
  3103. }
  3104. }
  3105. else {
  3106. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  3107. traverseNodes(runtime, i, null);
  3108. }
  3109. }
  3110. };
  3111. /**
  3112. * do stuff after buffers are loaded (e.g. hook up materials, load animations, etc.)
  3113. */
  3114. var postLoad = function (runtime) {
  3115. importScene(runtime);
  3116. // Set animations
  3117. loadAnimations(runtime);
  3118. for (var i = 0; i < runtime.babylonScene.skeletons.length; i++) {
  3119. var skeleton = runtime.babylonScene.skeletons[i];
  3120. runtime.babylonScene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  3121. }
  3122. // Revoke object urls created during load
  3123. if (runtime.gltf.textures) {
  3124. for (var i = 0; i < runtime.gltf.textures.length; i++) {
  3125. var texture = runtime.gltf.textures[i];
  3126. if (texture.blobURL) {
  3127. URL.revokeObjectURL(texture.blobURL);
  3128. }
  3129. }
  3130. }
  3131. };
  3132. var BinaryReader = (function () {
  3133. function BinaryReader(arrayBuffer) {
  3134. this._arrayBuffer = arrayBuffer;
  3135. this._dataView = new DataView(arrayBuffer);
  3136. this._byteOffset = 0;
  3137. }
  3138. BinaryReader.prototype.getPosition = function () {
  3139. return this._byteOffset;
  3140. };
  3141. BinaryReader.prototype.getLength = function () {
  3142. return this._arrayBuffer.byteLength;
  3143. };
  3144. BinaryReader.prototype.readUint32 = function () {
  3145. var value = this._dataView.getUint32(this._byteOffset, true);
  3146. this._byteOffset += 4;
  3147. return value;
  3148. };
  3149. BinaryReader.prototype.readUint8Array = function (length) {
  3150. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  3151. this._byteOffset += length;
  3152. return value;
  3153. };
  3154. BinaryReader.prototype.skipBytes = function (length) {
  3155. this._byteOffset += length;
  3156. };
  3157. return BinaryReader;
  3158. }());
  3159. /**
  3160. * glTF File Loader Plugin
  3161. */
  3162. var GLTFLoader = (function () {
  3163. function GLTFLoader() {
  3164. }
  3165. GLTFLoader.RegisterExtension = function (extension) {
  3166. if (GLTFLoader.Extensions[extension.name]) {
  3167. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  3168. return;
  3169. }
  3170. GLTFLoader.Extensions[extension.name] = extension;
  3171. };
  3172. GLTFLoader.LoadMaterial = function (runtime, index) {
  3173. var material = runtime.gltf.materials[index];
  3174. if (!material)
  3175. return null;
  3176. material.babylonMaterial = new BABYLON.PBRMaterial(material.name || "mat" + index, runtime.babylonScene);
  3177. material.babylonMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3178. material.babylonMaterial.useScalarInLinearSpace = true;
  3179. return material;
  3180. };
  3181. GLTFLoader.LoadMetallicRoughnessMaterialPropertiesAsync = function (runtime, material, onSuccess, onError) {
  3182. // Ensure metallic workflow
  3183. material.babylonMaterial.metallic = 1;
  3184. material.babylonMaterial.roughness = 1;
  3185. var properties = material.pbrMetallicRoughness;
  3186. if (!properties) {
  3187. onSuccess();
  3188. return;
  3189. }
  3190. //
  3191. // Load Factors
  3192. //
  3193. material.babylonMaterial.albedoColor = properties.baseColorFactor ? BABYLON.Color3.FromArray(properties.baseColorFactor) : new BABYLON.Color3(1, 1, 1);
  3194. material.babylonMaterial.metallic = properties.metallicFactor || 1;
  3195. material.babylonMaterial.roughness = properties.roughnessFactor || 1;
  3196. //
  3197. // Load Textures
  3198. //
  3199. if (!properties.baseColorTexture && !properties.metallicRoughnessTexture) {
  3200. onSuccess();
  3201. return;
  3202. }
  3203. var checkSuccess = function () {
  3204. if ((!properties.baseColorTexture || material.babylonMaterial.albedoTexture) &&
  3205. (!properties.metallicRoughnessTexture || material.babylonMaterial.metallicTexture)) {
  3206. onSuccess();
  3207. }
  3208. };
  3209. if (properties.baseColorTexture) {
  3210. GLTFLoader.LoadTextureAsync(runtime, properties.baseColorTexture, function (texture) {
  3211. material.babylonMaterial.albedoTexture = texture;
  3212. GLTFLoader.LoadAlphaProperties(runtime, material);
  3213. checkSuccess();
  3214. }, function () {
  3215. BABYLON.Tools.Error("Failed to load base color texture");
  3216. onError();
  3217. });
  3218. }
  3219. if (properties.metallicRoughnessTexture) {
  3220. GLTFLoader.LoadTextureAsync(runtime, properties.metallicRoughnessTexture, function (texture) {
  3221. material.babylonMaterial.metallicTexture = texture;
  3222. material.babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  3223. material.babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  3224. material.babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  3225. checkSuccess();
  3226. }, function () {
  3227. BABYLON.Tools.Error("Failed to load metallic roughness texture");
  3228. onError();
  3229. });
  3230. }
  3231. };
  3232. GLTFLoader.LoadCommonMaterialPropertiesAsync = function (runtime, material, onSuccess, onError) {
  3233. //
  3234. // Load Factors
  3235. //
  3236. material.babylonMaterial.useEmissiveAsIllumination = (material.emissiveFactor || material.emissiveTexture) ? true : false;
  3237. material.babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  3238. if (material.doubleSided) {
  3239. material.babylonMaterial.backFaceCulling = false;
  3240. material.babylonMaterial.twoSidedLighting = true;
  3241. }
  3242. //
  3243. // Load Textures
  3244. //
  3245. if (!material.normalTexture && !material.occlusionTexture && !material.emissiveTexture) {
  3246. onSuccess();
  3247. return;
  3248. }
  3249. var checkSuccess = function () {
  3250. if ((!material.normalTexture || material.babylonMaterial.bumpTexture) &&
  3251. (!material.occlusionTexture || material.babylonMaterial.ambientTexture) &&
  3252. (!material.emissiveTexture || material.babylonMaterial.emissiveTexture)) {
  3253. onSuccess();
  3254. }
  3255. };
  3256. if (material.normalTexture) {
  3257. GLTFLoader.LoadTextureAsync(runtime, material.normalTexture, function (babylonTexture) {
  3258. material.babylonMaterial.bumpTexture = babylonTexture;
  3259. if (material.normalTexture.scale !== undefined) {
  3260. material.babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  3261. }
  3262. checkSuccess();
  3263. }, function () {
  3264. BABYLON.Tools.Error("Failed to load normal texture");
  3265. onError();
  3266. });
  3267. }
  3268. if (material.occlusionTexture) {
  3269. GLTFLoader.LoadTextureAsync(runtime, material.occlusionTexture, function (babylonTexture) {
  3270. material.babylonMaterial.ambientTexture = babylonTexture;
  3271. material.babylonMaterial.useAmbientInGrayScale = true;
  3272. if (material.occlusionTexture.strength !== undefined) {
  3273. material.babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  3274. }
  3275. checkSuccess();
  3276. }, function () {
  3277. BABYLON.Tools.Error("Failed to load occlusion texture");
  3278. onError();
  3279. });
  3280. }
  3281. if (material.emissiveTexture) {
  3282. GLTFLoader.LoadTextureAsync(runtime, material.emissiveTexture, function (babylonTexture) {
  3283. material.babylonMaterial.emissiveTexture = babylonTexture;
  3284. checkSuccess();
  3285. }, function () {
  3286. BABYLON.Tools.Error("Failed to load emissive texture");
  3287. onError();
  3288. });
  3289. }
  3290. };
  3291. GLTFLoader.LoadAlphaProperties = function (runtime, material) {
  3292. var alphaMode = material.alphaMode || "OPAQUE";
  3293. switch (alphaMode) {
  3294. case "OPAQUE":
  3295. // default is opaque
  3296. break;
  3297. case "MASK":
  3298. material.babylonMaterial.albedoTexture.hasAlpha = true;
  3299. material.babylonMaterial.useAlphaFromAlbedoTexture = false;
  3300. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  3301. break;
  3302. case "BLEND":
  3303. material.babylonMaterial.albedoTexture.hasAlpha = true;
  3304. material.babylonMaterial.useAlphaFromAlbedoTexture = true;
  3305. material.babylonMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  3306. break;
  3307. default:
  3308. BABYLON.Tools.Error("Invalid alpha mode '" + material.alphaMode + "'");
  3309. }
  3310. };
  3311. GLTFLoader.LoadTextureAsync = function (runtime, textureInfo, onSuccess, onError) {
  3312. var texture = runtime.gltf.textures[textureInfo.index];
  3313. var texCoord = textureInfo.texCoord || 0;
  3314. if (!texture || texture.source === undefined) {
  3315. onError();
  3316. return;
  3317. }
  3318. if (texture.babylonTextures) {
  3319. var babylonTexture = texture.babylonTextures[texCoord];
  3320. if (!babylonTexture) {
  3321. for (var i = 0; i < texture.babylonTextures.length; i++) {
  3322. babylonTexture = texture.babylonTextures[i];
  3323. if (babylonTexture) {
  3324. babylonTexture = babylonTexture.clone();
  3325. babylonTexture.coordinatesIndex = texCoord;
  3326. break;
  3327. }
  3328. }
  3329. }
  3330. onSuccess(babylonTexture);
  3331. return;
  3332. }
  3333. var source = runtime.gltf.images[texture.source];
  3334. var sourceURL = runtime.rootUrl + source.uri;
  3335. if (texture.blobURL) {
  3336. sourceURL = texture.blobURL;
  3337. }
  3338. else {
  3339. if (source.uri === undefined) {
  3340. var bufferView = runtime.gltf.bufferViews[source.bufferView];
  3341. var buffer = GLTF2.GLTFUtils.GetBufferFromBufferView(runtime, bufferView, 0, bufferView.byteLength, GLTF2.EComponentType.UNSIGNED_BYTE);
  3342. texture.blobURL = URL.createObjectURL(new Blob([buffer], { type: source.mimeType }));
  3343. sourceURL = texture.blobURL;
  3344. }
  3345. else if (GLTF2.GLTFUtils.IsBase64(source.uri)) {
  3346. var decodedBuffer = new Uint8Array(GLTF2.GLTFUtils.DecodeBase64(source.uri));
  3347. texture.blobURL = URL.createObjectURL(new Blob([decodedBuffer], { type: source.mimeType }));
  3348. sourceURL = texture.blobURL;
  3349. }
  3350. }
  3351. GLTFLoader._createTextureAsync(runtime, texture, texCoord, sourceURL, onSuccess, onError);
  3352. };
  3353. GLTFLoader._createTextureAsync = function (runtime, texture, texCoord, url, onSuccess, onError) {
  3354. var sampler = (texture.sampler === undefined ? {} : runtime.gltf.samplers[texture.sampler]);
  3355. var noMipMaps = (sampler.minFilter === GLTF2.ETextureMinFilter.NEAREST || sampler.minFilter === GLTF2.ETextureMinFilter.LINEAR);
  3356. var samplingMode = GLTF2.GLTFUtils.GetTextureFilterMode(sampler.minFilter);
  3357. var babylonTexture = new BABYLON.Texture(url, runtime.babylonScene, noMipMaps, false, samplingMode, function () {
  3358. onSuccess(babylonTexture);
  3359. }, onError);
  3360. babylonTexture.coordinatesIndex = texCoord;
  3361. babylonTexture.wrapU = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapS);
  3362. babylonTexture.wrapV = GLTF2.GLTFUtils.GetWrapMode(sampler.wrapT);
  3363. babylonTexture.name = texture.name;
  3364. // Cache the texture
  3365. texture.babylonTextures = texture.babylonTextures || [];
  3366. texture.babylonTextures[texCoord] = babylonTexture;
  3367. };
  3368. /**
  3369. * Import meshes
  3370. */
  3371. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  3372. scene.useRightHandedSystem = true;
  3373. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, true);
  3374. if (!runtime) {
  3375. onError();
  3376. return;
  3377. }
  3378. if (meshesNames === "") {
  3379. runtime.importMeshesNames = [];
  3380. }
  3381. else if (typeof meshesNames === "string") {
  3382. runtime.importMeshesNames = [meshesNames];
  3383. }
  3384. else if (meshesNames && !(meshesNames instanceof Array)) {
  3385. runtime.importMeshesNames = [meshesNames];
  3386. }
  3387. else {
  3388. runtime.importMeshesNames = [];
  3389. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  3390. }
  3391. // Load scene
  3392. importScene(runtime);
  3393. var meshes = [];
  3394. var skeletons = [];
  3395. // Fill arrays of meshes and skeletons
  3396. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  3397. var node = runtime.gltf.nodes[i];
  3398. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  3399. meshes.push(node.babylonNode);
  3400. }
  3401. }
  3402. for (var i = 0; i < runtime.gltf.skins.length; i++) {
  3403. var skin = runtime.gltf.skins[i];
  3404. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  3405. skeletons.push(skin.babylonSkeleton);
  3406. }
  3407. }
  3408. // Load buffers, materials, etc.
  3409. GLTFLoader._loadBuffersAsync(runtime, function () {
  3410. GLTFLoader._loadMaterialsAsync(runtime, function () {
  3411. postLoad(runtime);
  3412. onSuccess(meshes, null, skeletons);
  3413. }, onError);
  3414. }, onError);
  3415. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  3416. onSuccess(meshes, null, skeletons);
  3417. }
  3418. };
  3419. /**
  3420. * Load scene
  3421. */
  3422. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  3423. scene.useRightHandedSystem = true;
  3424. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, false);
  3425. if (!runtime) {
  3426. onError();
  3427. return;
  3428. }
  3429. importScene(runtime);
  3430. GLTFLoader._loadBuffersAsync(runtime, function () {
  3431. GLTFLoader._loadMaterialsAsync(runtime, function () {
  3432. postLoad(runtime);
  3433. onSuccess();
  3434. }, onError);
  3435. }, onError);
  3436. };
  3437. GLTFLoader._loadBuffersAsync = function (runtime, onSuccess, onError) {
  3438. var _this = this;
  3439. if (runtime.gltf.buffers.length == 0) {
  3440. onSuccess();
  3441. return;
  3442. }
  3443. var successCount = 0;
  3444. runtime.gltf.buffers.forEach(function (buffer, index) {
  3445. _this._loadBufferAsync(runtime, index, function () {
  3446. if (++successCount === runtime.gltf.buffers.length) {
  3447. onSuccess();
  3448. }
  3449. }, onError);
  3450. });
  3451. };
  3452. GLTFLoader._loadBufferAsync = function (runtime, index, onSuccess, onError) {
  3453. var buffer = runtime.gltf.buffers[index];
  3454. if (buffer.uri === undefined) {
  3455. // buffer.loadedBufferView should already be set
  3456. onSuccess();
  3457. }
  3458. else if (GLTF2.GLTFUtils.IsBase64(buffer.uri)) {
  3459. var data = GLTF2.GLTFUtils.DecodeBase64(buffer.uri);
  3460. setTimeout(function () {
  3461. buffer.loadedBufferView = new Uint8Array(data);
  3462. onSuccess();
  3463. });
  3464. }
  3465. else {
  3466. BABYLON.Tools.LoadFile(runtime.rootUrl + buffer.uri, function (data) {
  3467. buffer.loadedBufferView = new Uint8Array(data);
  3468. onSuccess();
  3469. }, null, null, true, onError);
  3470. }
  3471. };
  3472. GLTFLoader._loadMaterialsAsync = function (runtime, onSuccess, onError) {
  3473. var materials = runtime.gltf.materials;
  3474. if (!materials || materials.length === 0) {
  3475. onSuccess();
  3476. return;
  3477. }
  3478. var successCount = 0;
  3479. for (var i = 0; i < materials.length; i++) {
  3480. GLTF2.GLTFLoaderExtension.LoadMaterialAsync(runtime, i, function () {
  3481. if (++successCount === materials.length) {
  3482. onSuccess();
  3483. }
  3484. }, onError);
  3485. }
  3486. };
  3487. GLTFLoader._createRuntime = function (scene, data, rootUrl, importOnlyMeshes) {
  3488. var runtime = {
  3489. gltf: data.json,
  3490. babylonScene: scene,
  3491. rootUrl: rootUrl,
  3492. importOnlyMeshes: importOnlyMeshes,
  3493. };
  3494. var binaryBuffer;
  3495. var buffers = runtime.gltf.buffers;
  3496. if (buffers.length > 0 && buffers[0].uri === undefined) {
  3497. binaryBuffer = buffers[0];
  3498. }
  3499. if (data.bin) {
  3500. if (!binaryBuffer) {
  3501. BABYLON.Tools.Error("Unexpected BIN chunk");
  3502. return null;
  3503. }
  3504. if (binaryBuffer.byteLength != data.bin.byteLength) {
  3505. BABYLON.Tools.Error("Binary buffer length from JSON does not match chunk length");
  3506. return null;
  3507. }
  3508. binaryBuffer.loadedBufferView = data.bin;
  3509. }
  3510. GLTF2.GLTFLoaderExtension.PostCreateRuntime(runtime);
  3511. return runtime;
  3512. };
  3513. return GLTFLoader;
  3514. }());
  3515. GLTFLoader.Extensions = {};
  3516. GLTF2.GLTFLoader = GLTFLoader;
  3517. BABYLON.GLTFFileLoader.GLTFLoaderV2 = new GLTFLoader();
  3518. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3519. })(BABYLON || (BABYLON = {}));
  3520. //# sourceMappingURL=babylon.glTFLoader.js.map
  3521. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  3522. var BABYLON;
  3523. (function (BABYLON) {
  3524. var GLTF2;
  3525. (function (GLTF2) {
  3526. /**
  3527. * Utils functions for GLTF
  3528. */
  3529. var GLTFUtils = (function () {
  3530. function GLTFUtils() {
  3531. }
  3532. /**
  3533. * If the uri is a base64 string
  3534. * @param uri: the uri to test
  3535. */
  3536. GLTFUtils.IsBase64 = function (uri) {
  3537. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  3538. };
  3539. /**
  3540. * Decode the base64 uri
  3541. * @param uri: the uri to decode
  3542. */
  3543. GLTFUtils.DecodeBase64 = function (uri) {
  3544. var decodedString = atob(uri.split(",")[1]);
  3545. var bufferLength = decodedString.length;
  3546. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  3547. for (var i = 0; i < bufferLength; i++) {
  3548. bufferView[i] = decodedString.charCodeAt(i);
  3549. }
  3550. return bufferView.buffer;
  3551. };
  3552. /**
  3553. * Returns the wrap mode of the texture
  3554. * @param mode: the mode value
  3555. */
  3556. GLTFUtils.GetWrapMode = function (mode) {
  3557. switch (mode) {
  3558. case GLTF2.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  3559. case GLTF2.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  3560. case GLTF2.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3561. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  3562. }
  3563. };
  3564. /**
  3565. * Returns the byte stride giving an accessor
  3566. * @param accessor: the GLTF accessor objet
  3567. */
  3568. GLTFUtils.GetByteStrideFromType = function (accessor) {
  3569. // Needs this function since "byteStride" isn't requiered in glTF format
  3570. var type = accessor.type;
  3571. switch (type) {
  3572. case "VEC2": return 2;
  3573. case "VEC3": return 3;
  3574. case "VEC4": return 4;
  3575. case "MAT2": return 4;
  3576. case "MAT3": return 9;
  3577. case "MAT4": return 16;
  3578. default: return 1;
  3579. }
  3580. };
  3581. /**
  3582. * Returns the texture filter mode giving a mode value
  3583. * @param mode: the filter mode value
  3584. */
  3585. GLTFUtils.GetTextureFilterMode = function (mode) {
  3586. switch (mode) {
  3587. case GLTF2.ETextureMinFilter.LINEAR:
  3588. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_NEAREST:
  3589. case GLTF2.ETextureMinFilter.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  3590. case GLTF2.ETextureMinFilter.NEAREST:
  3591. case GLTF2.ETextureMinFilter.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  3592. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  3593. }
  3594. };
  3595. GLTFUtils.GetBufferFromBufferView = function (runtime, bufferView, byteOffset, byteLength, componentType) {
  3596. byteOffset += (bufferView.byteOffset || 0);
  3597. var loadedBufferView = runtime.gltf.buffers[bufferView.buffer].loadedBufferView;
  3598. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  3599. throw new Error("Buffer access is out of range");
  3600. }
  3601. var buffer = loadedBufferView.buffer;
  3602. byteOffset += loadedBufferView.byteOffset;
  3603. switch (componentType) {
  3604. case GLTF2.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  3605. case GLTF2.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  3606. case GLTF2.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  3607. case GLTF2.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  3608. case GLTF2.EComponentType.UNSIGNED_INT: return new Uint32Array(buffer, byteOffset, byteLength);
  3609. default: return new Float32Array(buffer, byteOffset, byteLength);
  3610. }
  3611. };
  3612. /**
  3613. * Returns a buffer from its accessor
  3614. * @param runtime: the GLTF runtime
  3615. * @param accessor: the GLTF accessor
  3616. */
  3617. GLTFUtils.GetBufferFromAccessor = function (runtime, accessor) {
  3618. var bufferView = runtime.gltf.bufferViews[accessor.bufferView];
  3619. var byteOffset = accessor.byteOffset || 0;
  3620. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  3621. return GLTFUtils.GetBufferFromBufferView(runtime, bufferView, byteOffset, byteLength, accessor.componentType);
  3622. };
  3623. /**
  3624. * Decodes a buffer view into a string
  3625. * @param view: the buffer view
  3626. */
  3627. GLTFUtils.DecodeBufferToText = function (view) {
  3628. var result = "";
  3629. var length = view.byteLength;
  3630. for (var i = 0; i < length; ++i) {
  3631. result += String.fromCharCode(view[i]);
  3632. }
  3633. return result;
  3634. };
  3635. /**
  3636. * Returns the default material of gltf.
  3637. * @param scene: the Babylon.js scene
  3638. */
  3639. GLTFUtils.GetDefaultMaterial = function (runtime) {
  3640. if (!runtime.defaultMaterial) {
  3641. var material = new BABYLON.PBRMaterial("gltf_default", runtime.babylonScene);
  3642. material.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  3643. material.metallic = 1;
  3644. material.roughness = 1;
  3645. runtime.defaultMaterial = material;
  3646. }
  3647. return runtime.defaultMaterial;
  3648. };
  3649. return GLTFUtils;
  3650. }());
  3651. GLTF2.GLTFUtils = GLTFUtils;
  3652. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3653. })(BABYLON || (BABYLON = {}));
  3654. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  3655. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  3656. var BABYLON;
  3657. (function (BABYLON) {
  3658. var GLTF2;
  3659. (function (GLTF2) {
  3660. var GLTFLoaderExtension = (function () {
  3661. function GLTFLoaderExtension(name) {
  3662. this._name = name;
  3663. }
  3664. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  3665. get: function () {
  3666. return this._name;
  3667. },
  3668. enumerable: true,
  3669. configurable: true
  3670. });
  3671. GLTFLoaderExtension.prototype.postCreateRuntime = function (runtime) { };
  3672. // Return true to stop other extensions from loading materials.
  3673. GLTFLoaderExtension.prototype.loadMaterialAsync = function (runtime, index, onSuccess, onError) { return false; };
  3674. // ---------
  3675. // Utilities
  3676. // ---------
  3677. GLTFLoaderExtension.PostCreateRuntime = function (runtime) {
  3678. for (var extensionName in GLTF2.GLTFLoader.Extensions) {
  3679. var extension = GLTF2.GLTFLoader.Extensions[extensionName];
  3680. extension.postCreateRuntime(runtime);
  3681. }
  3682. };
  3683. GLTFLoaderExtension.LoadMaterialAsync = function (runtime, index, onSuccess, onError) {
  3684. for (var extensionName in GLTF2.GLTFLoader.Extensions) {
  3685. var extension = GLTF2.GLTFLoader.Extensions[extensionName];
  3686. if (extension.loadMaterialAsync(runtime, index, onSuccess, onError)) {
  3687. return;
  3688. }
  3689. }
  3690. var material = GLTF2.GLTFLoader.LoadMaterial(runtime, index);
  3691. if (!material) {
  3692. onSuccess();
  3693. return;
  3694. }
  3695. var metallicRoughnessPropertiesSuccess = false;
  3696. var commonPropertiesSuccess = false;
  3697. var checkSuccess = function () {
  3698. if (metallicRoughnessPropertiesSuccess && commonPropertiesSuccess) {
  3699. onSuccess();
  3700. }
  3701. };
  3702. GLTF2.GLTFLoader.LoadMetallicRoughnessMaterialPropertiesAsync(runtime, material, function () {
  3703. metallicRoughnessPropertiesSuccess = true;
  3704. checkSuccess();
  3705. }, onError);
  3706. GLTF2.GLTFLoader.LoadCommonMaterialPropertiesAsync(runtime, material, function () {
  3707. commonPropertiesSuccess = true;
  3708. checkSuccess();
  3709. }, onError);
  3710. };
  3711. return GLTFLoaderExtension;
  3712. }());
  3713. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  3714. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3715. })(BABYLON || (BABYLON = {}));
  3716. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  3717. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  3718. var __extends = (this && this.__extends) || (function () {
  3719. var extendStatics = Object.setPrototypeOf ||
  3720. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3721. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3722. return function (d, b) {
  3723. extendStatics(d, b);
  3724. function __() { this.constructor = d; }
  3725. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3726. };
  3727. })();
  3728. var BABYLON;
  3729. (function (BABYLON) {
  3730. var GLTF2;
  3731. (function (GLTF2) {
  3732. var GLTFMaterialsPbrSpecularGlossinessExtension = (function (_super) {
  3733. __extends(GLTFMaterialsPbrSpecularGlossinessExtension, _super);
  3734. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  3735. return _super.call(this, "KHR_materials_pbrSpecularGlossiness") || this;
  3736. }
  3737. GLTFMaterialsPbrSpecularGlossinessExtension.prototype.loadMaterialAsync = function (runtime, index, onSuccess, onError) {
  3738. var material = GLTF2.GLTFLoader.LoadMaterial(runtime, index);
  3739. if (!material || !material.extensions)
  3740. return false;
  3741. var properties = material.extensions[this.name];
  3742. if (!properties)
  3743. return false;
  3744. //
  3745. // Load Factors
  3746. //
  3747. material.babylonMaterial.albedoColor = properties.diffuseFactor ? BABYLON.Color3.FromArray(properties.diffuseFactor) : new BABYLON.Color3(1, 1, 1);
  3748. material.babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : new BABYLON.Color3(1, 1, 1);
  3749. material.babylonMaterial.microSurface = properties.glossinessFactor === undefined ? 1 : properties.glossinessFactor;
  3750. //
  3751. // Load Textures
  3752. //
  3753. var commonMaterialPropertiesSuccess = false;
  3754. var checkSuccess = function () {
  3755. if ((!properties.diffuseTexture || material.babylonMaterial.albedoTexture) &&
  3756. (!properties.specularGlossinessTexture || material.babylonMaterial.reflectivityTexture) &&
  3757. commonMaterialPropertiesSuccess) {
  3758. onSuccess();
  3759. }
  3760. };
  3761. if (properties.diffuseTexture) {
  3762. GLTF2.GLTFLoader.LoadTextureAsync(runtime, properties.diffuseTexture, function (texture) {
  3763. material.babylonMaterial.albedoTexture = texture;
  3764. GLTF2.GLTFLoader.LoadAlphaProperties(runtime, material);
  3765. checkSuccess();
  3766. }, function () {
  3767. BABYLON.Tools.Warn("Failed to load diffuse texture");
  3768. onError();
  3769. });
  3770. }
  3771. if (properties.specularGlossinessTexture) {
  3772. GLTF2.GLTFLoader.LoadTextureAsync(runtime, properties.specularGlossinessTexture, function (texture) {
  3773. material.babylonMaterial.reflectivityTexture = texture;
  3774. material.babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  3775. checkSuccess();
  3776. }, function () {
  3777. BABYLON.Tools.Warn("Failed to load metallic roughness texture");
  3778. onError();
  3779. });
  3780. }
  3781. GLTF2.GLTFLoader.LoadCommonMaterialPropertiesAsync(runtime, material, function () {
  3782. commonMaterialPropertiesSuccess = true;
  3783. checkSuccess();
  3784. }, onError);
  3785. return true;
  3786. };
  3787. return GLTFMaterialsPbrSpecularGlossinessExtension;
  3788. }(GLTF2.GLTFLoaderExtension));
  3789. GLTF2.GLTFMaterialsPbrSpecularGlossinessExtension = GLTFMaterialsPbrSpecularGlossinessExtension;
  3790. GLTF2.GLTFLoader.RegisterExtension(new GLTFMaterialsPbrSpecularGlossinessExtension());
  3791. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3792. })(BABYLON || (BABYLON = {}));
  3793. //# sourceMappingURL=babylon.glTFMaterialsPbrSpecularGlossinessExtension.js.map