babylon.glTFFileLoader.js 191 KB

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