babylon.glTFFileLoader.js 169 KB

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