babylon.glTFFileLoader.js 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056
  1. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  2. var BABYLON;
  3. (function (BABYLON) {
  4. /**
  5. * Enums
  6. */
  7. var EComponentType;
  8. (function (EComponentType) {
  9. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  10. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  11. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  12. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  13. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  14. })(EComponentType = BABYLON.EComponentType || (BABYLON.EComponentType = {}));
  15. var EShaderType;
  16. (function (EShaderType) {
  17. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  18. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  19. })(EShaderType = BABYLON.EShaderType || (BABYLON.EShaderType = {}));
  20. var EParameterType;
  21. (function (EParameterType) {
  22. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  23. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  24. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  25. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  26. EParameterType[EParameterType["INT"] = 5124] = "INT";
  27. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  28. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  29. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  30. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  31. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  32. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  33. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  34. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  35. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  36. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  37. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  38. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  39. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  40. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  41. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  42. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  43. })(EParameterType = BABYLON.EParameterType || (BABYLON.EParameterType = {}));
  44. var ETextureWrapMode;
  45. (function (ETextureWrapMode) {
  46. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  47. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  48. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  49. })(ETextureWrapMode = BABYLON.ETextureWrapMode || (BABYLON.ETextureWrapMode = {}));
  50. var ETextureFilterType;
  51. (function (ETextureFilterType) {
  52. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  53. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  54. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  55. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  56. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  57. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  58. })(ETextureFilterType = BABYLON.ETextureFilterType || (BABYLON.ETextureFilterType = {}));
  59. var ETextureFormat;
  60. (function (ETextureFormat) {
  61. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  62. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  63. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  64. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  65. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  66. })(ETextureFormat = BABYLON.ETextureFormat || (BABYLON.ETextureFormat = {}));
  67. var ECullingType;
  68. (function (ECullingType) {
  69. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  70. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  71. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  72. })(ECullingType = BABYLON.ECullingType || (BABYLON.ECullingType = {}));
  73. var EBlendingFunction;
  74. (function (EBlendingFunction) {
  75. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  76. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  77. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  78. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  79. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  80. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  81. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  82. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  83. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  84. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  85. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  86. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  87. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  88. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  89. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  90. })(EBlendingFunction = BABYLON.EBlendingFunction || (BABYLON.EBlendingFunction = {}));
  91. })(BABYLON || (BABYLON = {}));
  92. //# sourceMappingURL=babylon.glTFFileLoaderInterfaces.js.map
  93. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  94. var BABYLON;
  95. (function (BABYLON) {
  96. /**
  97. * Tokenizer. Used for shaders compatibility
  98. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  99. */
  100. var ETokenType;
  101. (function (ETokenType) {
  102. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  103. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  104. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  105. })(ETokenType || (ETokenType = {}));
  106. var Tokenizer = (function () {
  107. function Tokenizer(toParse) {
  108. this._pos = 0;
  109. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  110. this._toParse = toParse;
  111. this._maxPos = toParse.length;
  112. }
  113. Tokenizer.prototype.getNextToken = function () {
  114. if (this.isEnd())
  115. return ETokenType.END_OF_INPUT;
  116. this.currentString = this.read();
  117. this.currentToken = ETokenType.UNKNOWN;
  118. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  119. this.currentToken = ETokenType.IDENTIFIER;
  120. this.currentIdentifier = this.currentString;
  121. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  122. this.currentIdentifier += this.currentString;
  123. this.forward();
  124. }
  125. }
  126. return this.currentToken;
  127. };
  128. Tokenizer.prototype.peek = function () {
  129. return this._toParse[this._pos];
  130. };
  131. Tokenizer.prototype.read = function () {
  132. return this._toParse[this._pos++];
  133. };
  134. Tokenizer.prototype.forward = function () {
  135. this._pos++;
  136. };
  137. Tokenizer.prototype.isEnd = function () {
  138. return this._pos >= this._maxPos;
  139. };
  140. return Tokenizer;
  141. }());
  142. /**
  143. * Values
  144. */
  145. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  146. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  147. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  148. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  149. /**
  150. * Parse
  151. */
  152. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  153. for (var buf in parsedBuffers) {
  154. var parsedBuffer = parsedBuffers[buf];
  155. gltfRuntime.buffers[buf] = parsedBuffer;
  156. gltfRuntime.buffersCount++;
  157. }
  158. };
  159. var parseShaders = function (parsedShaders, gltfRuntime) {
  160. for (var sha in parsedShaders) {
  161. var parsedShader = parsedShaders[sha];
  162. gltfRuntime.shaders[sha] = parsedShader;
  163. gltfRuntime.shaderscount++;
  164. }
  165. };
  166. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  167. for (var object in parsedObjects) {
  168. var parsedObject = parsedObjects[object];
  169. gltfRuntime[runtimeProperty][object] = parsedObject;
  170. }
  171. };
  172. /**
  173. * Utils
  174. */
  175. var normalizeUVs = function (buffer) {
  176. if (!buffer) {
  177. return;
  178. }
  179. for (var i = 0; i < buffer.length / 2; i++) {
  180. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  181. }
  182. };
  183. var replaceInString = function (str, searchValue, replaceValue) {
  184. while (str.indexOf(searchValue) !== -1) {
  185. str = str.replace(searchValue, replaceValue);
  186. }
  187. return str;
  188. };
  189. var getAttribute = function (attributeParameter) {
  190. if (attributeParameter.semantic === "NORMAL") {
  191. return "normal";
  192. }
  193. else if (attributeParameter.semantic === "POSITION") {
  194. return "position";
  195. }
  196. else if (attributeParameter.semantic === "JOINT") {
  197. return "matricesIndices";
  198. }
  199. else if (attributeParameter.semantic === "WEIGHT") {
  200. return "matricesWeights";
  201. }
  202. else if (attributeParameter.semantic === "COLOR") {
  203. return "color";
  204. }
  205. else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  206. var channel = Number(attributeParameter.semantic.split("_")[1]);
  207. return "uv" + (channel === 0 ? "" : channel + 1);
  208. }
  209. };
  210. /**
  211. * Returns the animation path (glTF -> Babylon)
  212. */
  213. var getAnimationPath = function (path) {
  214. var index = glTFAnimationPaths.indexOf(path);
  215. if (index !== -1) {
  216. return babylonAnimationPaths[index];
  217. }
  218. return path;
  219. };
  220. /**
  221. * Loads and creates animations
  222. */
  223. var loadAnimations = function (gltfRuntime) {
  224. for (var anim in gltfRuntime.animations) {
  225. var animation = gltfRuntime.animations[anim];
  226. var lastAnimation = null;
  227. for (var i = 0; i < animation.channels.length; i++) {
  228. // Get parameters and load buffers
  229. var channel = animation.channels[i];
  230. var sampler = animation.samplers[channel.sampler];
  231. if (!sampler) {
  232. continue;
  233. }
  234. var inputData = null;
  235. var outputData = null;
  236. if (animation.parameters) {
  237. inputData = animation.parameters[sampler.input];
  238. outputData = animation.parameters[sampler.output];
  239. }
  240. else {
  241. inputData = sampler.input;
  242. outputData = sampler.output;
  243. }
  244. var bufferInput = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  245. var bufferOutput = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  246. var targetID = channel.target.id;
  247. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  248. if (targetNode === null) {
  249. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  250. }
  251. if (targetNode === null) {
  252. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  253. continue;
  254. }
  255. var isBone = targetNode instanceof BABYLON.Bone;
  256. // Get target path (position, rotation or scaling)
  257. var targetPath = channel.target.path;
  258. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  259. if (targetPathIndex !== -1) {
  260. targetPath = babylonAnimationPaths[targetPathIndex];
  261. }
  262. // Determine animation type
  263. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  264. if (!isBone) {
  265. if (targetPath === "rotationQuaternion") {
  266. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  267. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  268. }
  269. else {
  270. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  271. }
  272. }
  273. // Create animation and key frames
  274. var babylonAnimation = null;
  275. var keys = [];
  276. var arrayOffset = 0;
  277. var modifyKey = false;
  278. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  279. babylonAnimation = lastAnimation;
  280. modifyKey = true;
  281. }
  282. if (!modifyKey) {
  283. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  284. }
  285. // For each frame
  286. for (var j = 0; j < bufferInput.length; j++) {
  287. var value = null;
  288. if (targetPath === "rotationQuaternion") {
  289. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  290. arrayOffset += 4;
  291. }
  292. else {
  293. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  294. arrayOffset += 3;
  295. }
  296. if (isBone) {
  297. var bone = targetNode;
  298. var translation = BABYLON.Vector3.Zero();
  299. var rotationQuaternion = new BABYLON.Quaternion();
  300. var scaling = BABYLON.Vector3.Zero();
  301. // Warning on decompose
  302. var mat = bone.getBaseMatrix();
  303. if (modifyKey) {
  304. mat = lastAnimation.getKeys()[j].value;
  305. }
  306. mat.decompose(scaling, rotationQuaternion, translation);
  307. if (targetPath === "position") {
  308. translation = value;
  309. }
  310. else if (targetPath === "rotationQuaternion") {
  311. rotationQuaternion = value;
  312. }
  313. else {
  314. scaling = value;
  315. }
  316. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  317. }
  318. if (!modifyKey) {
  319. keys.push({
  320. frame: bufferInput[j],
  321. value: value
  322. });
  323. }
  324. else {
  325. lastAnimation.getKeys()[j].value = value;
  326. }
  327. }
  328. // Finish
  329. if (!modifyKey) {
  330. babylonAnimation.setKeys(keys);
  331. targetNode.animations.push(babylonAnimation);
  332. }
  333. lastAnimation = babylonAnimation;
  334. gltfRuntime.scene.stopAnimation(targetNode);
  335. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  336. }
  337. }
  338. };
  339. /**
  340. * Returns the bones transformation matrix
  341. */
  342. var configureBoneTransformation = function (node) {
  343. var mat = null;
  344. if (node.translation || node.rotation || node.scale) {
  345. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  346. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  347. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  348. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  349. }
  350. else {
  351. mat = BABYLON.Matrix.FromArray(node.matrix);
  352. }
  353. return mat;
  354. };
  355. /**
  356. * Returns the parent bone
  357. */
  358. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  359. // Try to find
  360. for (var i = 0; i < newSkeleton.bones.length; i++) {
  361. if (newSkeleton.bones[i].name === jointName) {
  362. return newSkeleton.bones[i];
  363. }
  364. }
  365. // Not found, search in gltf nodes
  366. var nodes = gltfRuntime.nodes;
  367. for (var nde in nodes) {
  368. var node = nodes[nde];
  369. if (!node.jointName) {
  370. continue;
  371. }
  372. var children = node.children;
  373. for (var i = 0; i < children.length; i++) {
  374. var child = gltfRuntime.nodes[children[i]];
  375. if (!child.jointName) {
  376. continue;
  377. }
  378. if (child.jointName === jointName) {
  379. var mat = configureBoneTransformation(node);
  380. var bone = new BABYLON.Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  381. bone.id = nde;
  382. return bone;
  383. }
  384. }
  385. }
  386. return null;
  387. };
  388. /**
  389. * Returns the appropriate root node
  390. */
  391. var getNodeToRoot = function (nodesToRoot, id) {
  392. for (var i = 0; i < nodesToRoot.length; i++) {
  393. var nodeToRoot = nodesToRoot[i];
  394. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  395. var child = nodeToRoot.node.children[j];
  396. if (child === id) {
  397. return nodeToRoot.bone;
  398. }
  399. }
  400. }
  401. return null;
  402. };
  403. /**
  404. * Returns the node with the joint name
  405. */
  406. var getJointNode = function (gltfRuntime, jointName) {
  407. var nodes = gltfRuntime.nodes;
  408. var node = nodes[jointName];
  409. if (node) {
  410. return {
  411. node: node,
  412. id: jointName
  413. };
  414. }
  415. for (var nde in nodes) {
  416. node = nodes[nde];
  417. if (node.jointName === jointName) {
  418. return {
  419. node: node,
  420. id: nde
  421. };
  422. }
  423. }
  424. return null;
  425. };
  426. /**
  427. * Checks if a nodes is in joints
  428. */
  429. var nodeIsInJoints = function (skins, id) {
  430. for (var i = 0; i < skins.jointNames.length; i++) {
  431. if (skins.jointNames[i] === id) {
  432. return true;
  433. }
  434. }
  435. return false;
  436. };
  437. /**
  438. * Fills the nodes to root for bones and builds hierarchy
  439. */
  440. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  441. // Creates nodes for root
  442. for (var nde in gltfRuntime.nodes) {
  443. var node = gltfRuntime.nodes[nde];
  444. var id = nde;
  445. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  446. continue;
  447. }
  448. // Create node to root bone
  449. var mat = configureBoneTransformation(node);
  450. var bone = new BABYLON.Bone(node.name, newSkeleton, null, mat);
  451. bone.id = id;
  452. nodesToRoot.push({ bone: bone, node: node, id: id });
  453. }
  454. // Parenting
  455. for (var i = 0; i < nodesToRoot.length; i++) {
  456. var nodeToRoot = nodesToRoot[i];
  457. var children = nodeToRoot.node.children;
  458. for (var j = 0; j < children.length; j++) {
  459. var child = null;
  460. for (var k = 0; k < nodesToRoot.length; k++) {
  461. if (nodesToRoot[k].id === children[j]) {
  462. child = nodesToRoot[k];
  463. break;
  464. }
  465. }
  466. if (child) {
  467. child.bone._parent = nodeToRoot.bone;
  468. nodeToRoot.bone.children.push(child.bone);
  469. }
  470. }
  471. }
  472. };
  473. var printMat = function (m) {
  474. console.log(m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  475. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  476. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  477. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n");
  478. };
  479. /**
  480. * Imports a skeleton
  481. */
  482. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  483. if (!newSkeleton) {
  484. newSkeleton = new BABYLON.Skeleton(skins.name, "", gltfRuntime.scene);
  485. }
  486. if (!skins.babylonSkeleton) {
  487. return newSkeleton;
  488. }
  489. // Matrices
  490. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  491. var buffer = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  492. var bindShapeMatrix = BABYLON.Matrix.FromArray(skins.bindShapeMatrix);
  493. // Find the root bones
  494. var nodesToRoot = [];
  495. var nodesToRootToAdd = [];
  496. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  497. newSkeleton.bones = [];
  498. if (nodesToRoot.length === 0) {
  499. newSkeleton.needInitialSkinMatrix = true;
  500. }
  501. // Joints
  502. for (var i = 0; i < skins.jointNames.length; i++) {
  503. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  504. var node = jointNode.node;
  505. if (!node) {
  506. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  507. continue;
  508. }
  509. var id = jointNode.id;
  510. // Optimize, if the bone already exists...
  511. var existingBone = gltfRuntime.scene.getBoneByID(id);
  512. if (existingBone) {
  513. newSkeleton.bones.push(existingBone);
  514. continue;
  515. }
  516. // Search for parent bone
  517. var foundBone = false;
  518. var parentBone = null;
  519. for (var j = 0; j < i; j++) {
  520. var joint = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  521. if (!joint) {
  522. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  523. continue;
  524. }
  525. var children = joint.children;
  526. foundBone = false;
  527. for (var k = 0; k < children.length; k++) {
  528. if (children[k] === id) {
  529. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  530. foundBone = true;
  531. break;
  532. }
  533. }
  534. if (foundBone) {
  535. break;
  536. }
  537. }
  538. // Create bone
  539. var mat = configureBoneTransformation(node);
  540. if (!parentBone && nodesToRoot.length > 0) {
  541. parentBone = getNodeToRoot(nodesToRoot, id);
  542. if (parentBone) {
  543. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  544. nodesToRootToAdd.push(parentBone);
  545. }
  546. }
  547. }
  548. var bone = new BABYLON.Bone(node.jointName, newSkeleton, parentBone, mat);
  549. bone.id = id;
  550. }
  551. // Polish
  552. var bones = newSkeleton.bones;
  553. newSkeleton.bones = [];
  554. for (var i = 0; i < skins.jointNames.length; i++) {
  555. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  556. if (!jointNode) {
  557. continue;
  558. }
  559. for (var j = 0; j < bones.length; j++) {
  560. if (bones[j].id === jointNode.id) {
  561. newSkeleton.bones.push(bones[j]);
  562. break;
  563. }
  564. }
  565. }
  566. newSkeleton.prepare();
  567. // Finish
  568. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  569. newSkeleton.bones.push(nodesToRootToAdd[i]);
  570. }
  571. return newSkeleton;
  572. };
  573. /**
  574. * Imports a mesh and its geometries
  575. */
  576. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  577. if (!newMesh) {
  578. newMesh = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  579. newMesh.id = id;
  580. }
  581. if (!node.babylonNode) {
  582. return newMesh;
  583. }
  584. var multiMat = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  585. if (!newMesh.material) {
  586. newMesh.material = multiMat;
  587. }
  588. var vertexData = new BABYLON.VertexData();
  589. var geometry = new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  590. var verticesStarts = [];
  591. var verticesCounts = [];
  592. var indexStarts = [];
  593. var indexCounts = [];
  594. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  595. var meshID = meshes[meshIndex];
  596. var mesh = gltfRuntime.meshes[meshID];
  597. if (!mesh) {
  598. continue;
  599. }
  600. // Positions, normals and UVs
  601. for (var i = 0; i < mesh.primitives.length; i++) {
  602. // Temporary vertex data
  603. var tempVertexData = new BABYLON.VertexData();
  604. var primitive = mesh.primitives[i];
  605. if (primitive.mode !== 4) {
  606. }
  607. var attributes = primitive.attributes;
  608. var accessor = null;
  609. var buffer = null;
  610. // Set positions, normal and uvs
  611. for (var semantic in attributes) {
  612. // Link accessor and buffer view
  613. accessor = gltfRuntime.accessors[attributes[semantic]];
  614. buffer = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  615. if (semantic === "NORMAL") {
  616. tempVertexData.normals = new Float32Array(buffer.length);
  617. tempVertexData.normals.set(buffer);
  618. }
  619. else if (semantic === "POSITION") {
  620. if (GLTFFileLoader.HomogeneousCoordinates) {
  621. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  622. for (var j = 0; j < buffer.length; j += 4) {
  623. tempVertexData.positions[j] = buffer[j];
  624. tempVertexData.positions[j + 1] = buffer[j + 1];
  625. tempVertexData.positions[j + 2] = buffer[j + 2];
  626. }
  627. }
  628. else {
  629. tempVertexData.positions = new Float32Array(buffer.length);
  630. tempVertexData.positions.set(buffer);
  631. }
  632. verticesCounts.push(tempVertexData.positions.length);
  633. }
  634. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  635. var channel = Number(semantic.split("_")[1]);
  636. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  637. var uvs = new Float32Array(buffer.length);
  638. uvs.set(buffer);
  639. normalizeUVs(uvs);
  640. tempVertexData.set(uvs, uvKind);
  641. }
  642. else if (semantic === "JOINT") {
  643. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  644. tempVertexData.matricesIndices.set(buffer);
  645. }
  646. else if (semantic === "WEIGHT") {
  647. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  648. tempVertexData.matricesWeights.set(buffer);
  649. }
  650. else if (semantic === "COLOR") {
  651. tempVertexData.colors = new Float32Array(buffer.length);
  652. tempVertexData.colors.set(buffer);
  653. }
  654. }
  655. // Indices
  656. accessor = gltfRuntime.accessors[primitive.indices];
  657. if (accessor) {
  658. buffer = BABYLON.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  659. tempVertexData.indices = new Int32Array(buffer.length);
  660. tempVertexData.indices.set(buffer);
  661. indexCounts.push(tempVertexData.indices.length);
  662. }
  663. else {
  664. // Set indices on the fly
  665. var indices = [];
  666. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  667. indices.push(j);
  668. }
  669. tempVertexData.indices = new Int32Array(indices);
  670. indexCounts.push(tempVertexData.indices.length);
  671. }
  672. vertexData.merge(tempVertexData);
  673. tempVertexData = undefined;
  674. // Sub material
  675. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  676. multiMat.subMaterials.push(material === null ? BABYLON.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  677. // Update vertices start and index start
  678. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  679. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  680. }
  681. }
  682. // Apply geometry
  683. geometry.setAllVerticesData(vertexData, false);
  684. newMesh.computeWorldMatrix(true);
  685. // Apply submeshes
  686. newMesh.subMeshes = [];
  687. var index = 0;
  688. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  689. var meshID = meshes[meshIndex];
  690. var mesh = gltfRuntime.meshes[meshID];
  691. if (!mesh) {
  692. continue;
  693. }
  694. for (var i = 0; i < mesh.primitives.length; i++) {
  695. if (mesh.primitives[i].mode !== 4) {
  696. }
  697. var subMesh = new BABYLON.SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  698. index++;
  699. }
  700. }
  701. // Finish
  702. return newMesh;
  703. };
  704. /**
  705. * Configure node transformation from position, rotation and scaling
  706. */
  707. var configureNode = function (newNode, position, rotation, scaling) {
  708. if (newNode.position) {
  709. newNode.position = position;
  710. }
  711. if (newNode.rotationQuaternion || newNode.rotation) {
  712. newNode.rotationQuaternion = rotation;
  713. }
  714. if (newNode.scaling) {
  715. newNode.scaling = scaling;
  716. }
  717. };
  718. /**
  719. * Configures node from transformation matrix
  720. */
  721. var configureNodeFromMatrix = function (newNode, node, parent) {
  722. if (node.matrix) {
  723. var position = new BABYLON.Vector3(0, 0, 0);
  724. var rotation = new BABYLON.Quaternion();
  725. var scaling = new BABYLON.Vector3(0, 0, 0);
  726. var mat = BABYLON.Matrix.FromArray(node.matrix);
  727. mat.decompose(scaling, rotation, position);
  728. configureNode(newNode, position, rotation, scaling);
  729. newNode.computeWorldMatrix(true);
  730. }
  731. else {
  732. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  733. }
  734. };
  735. /**
  736. * Imports a node
  737. */
  738. var importNode = function (gltfRuntime, node, id, parent) {
  739. var lastNode = null;
  740. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  741. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  742. return null;
  743. }
  744. }
  745. // Meshes
  746. if (node.skin) {
  747. if (node.meshes) {
  748. var skin = gltfRuntime.skins[node.skin];
  749. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  750. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  751. if (newMesh.skeleton === null) {
  752. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  753. if (!skin.babylonSkeleton) {
  754. skin.babylonSkeleton = newMesh.skeleton;
  755. }
  756. }
  757. lastNode = newMesh;
  758. }
  759. }
  760. else if (node.meshes) {
  761. /**
  762. * Improve meshes property
  763. */
  764. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  765. lastNode = newMesh;
  766. }
  767. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  768. var light = gltfRuntime.lights[node.light];
  769. if (light) {
  770. if (light.type === "ambient") {
  771. var ambienLight = light[light.type];
  772. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  773. hemiLight.name = node.name;
  774. if (ambienLight.color) {
  775. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  776. }
  777. lastNode = hemiLight;
  778. }
  779. else if (light.type === "directional") {
  780. var directionalLight = light[light.type];
  781. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  782. dirLight.name = node.name;
  783. if (directionalLight.color) {
  784. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  785. }
  786. lastNode = dirLight;
  787. }
  788. else if (light.type === "point") {
  789. var pointLight = light[light.type];
  790. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  791. ptLight.name = node.name;
  792. if (pointLight.color) {
  793. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  794. }
  795. lastNode = ptLight;
  796. }
  797. else if (light.type === "spot") {
  798. var spotLight = light[light.type];
  799. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  800. spLight.name = node.name;
  801. if (spotLight.color) {
  802. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  803. }
  804. if (spotLight.fallOfAngle) {
  805. spLight.angle = spotLight.fallOfAngle;
  806. }
  807. if (spotLight.fallOffExponent) {
  808. spLight.exponent = spotLight.fallOffExponent;
  809. }
  810. lastNode = spLight;
  811. }
  812. }
  813. }
  814. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  815. var camera = gltfRuntime.cameras[node.camera];
  816. if (camera) {
  817. if (camera.type === "orthographic") {
  818. var orthographicCamera = camera[camera.type];
  819. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  820. orthoCamera.name = node.name;
  821. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  822. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  823. lastNode = orthoCamera;
  824. }
  825. else if (camera.type === "perspective") {
  826. var perspectiveCamera = camera[camera.type];
  827. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  828. persCamera.name = node.name;
  829. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  830. if (!perspectiveCamera.aspectRatio) {
  831. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  832. }
  833. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  834. persCamera.maxZ = perspectiveCamera.zfar;
  835. persCamera.minZ = perspectiveCamera.znear;
  836. }
  837. lastNode = persCamera;
  838. }
  839. }
  840. }
  841. // Empty node
  842. if (!node.jointName) {
  843. if (node.babylonNode) {
  844. return node.babylonNode;
  845. }
  846. else if (lastNode === null) {
  847. var dummy = new BABYLON.Mesh(node.name, gltfRuntime.scene);
  848. node.babylonNode = dummy;
  849. lastNode = dummy;
  850. }
  851. }
  852. if (lastNode !== null) {
  853. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  854. configureNodeFromMatrix(lastNode, node, parent);
  855. }
  856. else {
  857. var translation = node.translation || [0, 0, 0];
  858. var rotation = node.rotation || [0, 0, 0, 1];
  859. var scale = node.scale || [1, 1, 1];
  860. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.RotationAxis(BABYLON.Vector3.FromArray(rotation).normalize(), rotation[3]), BABYLON.Vector3.FromArray(scale));
  861. }
  862. lastNode.updateCache(true);
  863. node.babylonNode = lastNode;
  864. }
  865. return lastNode;
  866. };
  867. /**
  868. * Traverses nodes and creates them
  869. */
  870. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  871. var node = gltfRuntime.nodes[id];
  872. var newNode = null;
  873. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  874. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  875. meshIncluded = true;
  876. }
  877. else {
  878. meshIncluded = false;
  879. }
  880. }
  881. else {
  882. meshIncluded = true;
  883. }
  884. if (!node.jointName && meshIncluded) {
  885. newNode = importNode(gltfRuntime, node, id, parent);
  886. if (newNode !== null) {
  887. newNode.id = id;
  888. newNode.parent = parent;
  889. }
  890. }
  891. if (node.children) {
  892. for (var i = 0; i < node.children.length; i++) {
  893. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  894. }
  895. }
  896. };
  897. /**
  898. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  899. */
  900. var postLoad = function (gltfRuntime) {
  901. // Nodes
  902. var currentScene = gltfRuntime.currentScene;
  903. if (currentScene) {
  904. for (var i = 0; i < currentScene.nodes.length; i++) {
  905. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  906. }
  907. }
  908. else {
  909. for (var thing in gltfRuntime.scenes) {
  910. currentScene = gltfRuntime.scenes[thing];
  911. for (var i = 0; i < currentScene.nodes.length; i++) {
  912. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  913. }
  914. }
  915. }
  916. // Set animations
  917. loadAnimations(gltfRuntime);
  918. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  919. var skeleton = gltfRuntime.scene.skeletons[i];
  920. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  921. }
  922. };
  923. /**
  924. * onBind shaderrs callback to set uniforms and matrices
  925. */
  926. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  927. var materialValues = material.values || technique.parameters;
  928. for (var unif in unTreatedUniforms) {
  929. var uniform = unTreatedUniforms[unif];
  930. var type = uniform.type;
  931. if (type === BABYLON.EParameterType.FLOAT_MAT2 || type === BABYLON.EParameterType.FLOAT_MAT3 || type === BABYLON.EParameterType.FLOAT_MAT4) {
  932. if (uniform.semantic && !uniform.source && !uniform.node) {
  933. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  934. }
  935. else if (uniform.semantic && (uniform.source || uniform.node)) {
  936. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  937. if (source === null) {
  938. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  939. }
  940. if (source === null) {
  941. continue;
  942. }
  943. BABYLON.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  944. }
  945. }
  946. else {
  947. var value = materialValues[technique.uniforms[unif]];
  948. if (!value) {
  949. continue;
  950. }
  951. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  952. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  953. if (texture === null || texture === undefined) {
  954. continue;
  955. }
  956. shaderMaterial.getEffect().setTexture(unif, texture);
  957. }
  958. else {
  959. BABYLON.GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  960. }
  961. }
  962. }
  963. onSuccess(shaderMaterial);
  964. };
  965. /**
  966. * Prepare uniforms to send the only one time
  967. * Loads the appropriate textures
  968. */
  969. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  970. var materialValues = material.values || technique.parameters;
  971. var techniqueUniforms = technique.uniforms;
  972. /**
  973. * Prepare values here (not matrices)
  974. */
  975. for (var unif in unTreatedUniforms) {
  976. var uniform = unTreatedUniforms[unif];
  977. var type = uniform.type;
  978. var value = materialValues[techniqueUniforms[unif]];
  979. if (value === undefined) {
  980. // In case the value is the same for all materials
  981. value = uniform.value;
  982. }
  983. if (!value) {
  984. continue;
  985. }
  986. var onLoadTexture = function (uniformName) {
  987. return function (texture) {
  988. if (uniform.value) {
  989. // Static uniform
  990. shaderMaterial.setTexture(uniformName, texture);
  991. delete unTreatedUniforms[uniformName];
  992. }
  993. };
  994. };
  995. // Texture (sampler2D)
  996. if (type === BABYLON.EParameterType.SAMPLER_2D) {
  997. BABYLON.GLTFFileLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  998. }
  999. else {
  1000. if (uniform.value && BABYLON.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  1001. // Static uniform
  1002. delete unTreatedUniforms[unif];
  1003. }
  1004. }
  1005. }
  1006. };
  1007. /**
  1008. * Shader compilation failed
  1009. */
  1010. var onShaderCompileError = function (program, shaderMaterial, onError) {
  1011. return function (effect, error) {
  1012. BABYLON.Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  1013. shaderMaterial.dispose(true);
  1014. onError();
  1015. };
  1016. };
  1017. /**
  1018. * Shader compilation success
  1019. */
  1020. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  1021. return function (_) {
  1022. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  1023. shaderMaterial.onBind = function (mesh) {
  1024. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  1025. };
  1026. };
  1027. };
  1028. /**
  1029. * Returns the appropriate uniform if already handled by babylon
  1030. */
  1031. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  1032. for (var unif in technique.uniforms) {
  1033. var uniform = technique.uniforms[unif];
  1034. var uniformParameter = technique.parameters[uniform];
  1035. if (tokenizer.currentIdentifier === unif) {
  1036. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  1037. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1038. if (transformIndex !== -1) {
  1039. delete unTreatedUniforms[unif];
  1040. return babylonTransforms[transformIndex];
  1041. }
  1042. }
  1043. }
  1044. }
  1045. return tokenizer.currentIdentifier;
  1046. };
  1047. /**
  1048. * All shaders loaded. Create materials one by one
  1049. */
  1050. var importMaterials = function (gltfRuntime) {
  1051. // Create materials
  1052. for (var mat in gltfRuntime.materials) {
  1053. BABYLON.GLTFFileLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  1054. }
  1055. };
  1056. /**
  1057. * Implementation of the base glTF spec
  1058. */
  1059. var GLTFFileLoaderBase = (function () {
  1060. function GLTFFileLoaderBase() {
  1061. }
  1062. GLTFFileLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  1063. var gltfRuntime = {
  1064. accessors: {},
  1065. buffers: {},
  1066. bufferViews: {},
  1067. meshes: {},
  1068. lights: {},
  1069. cameras: {},
  1070. nodes: {},
  1071. images: {},
  1072. textures: {},
  1073. shaders: {},
  1074. programs: {},
  1075. samplers: {},
  1076. techniques: {},
  1077. materials: {},
  1078. animations: {},
  1079. skins: {},
  1080. extensionsUsed: [],
  1081. scenes: {},
  1082. buffersCount: 0,
  1083. shaderscount: 0,
  1084. scene: scene,
  1085. rootUrl: rootUrl,
  1086. loadedBufferCount: 0,
  1087. loadedBufferViews: {},
  1088. loadedShaderCount: 0,
  1089. importOnlyMeshes: false,
  1090. dummyNodes: []
  1091. };
  1092. // Parse
  1093. if (parsedData.extensionsUsed) {
  1094. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1095. }
  1096. if (parsedData.buffers) {
  1097. parseBuffers(parsedData.buffers, gltfRuntime);
  1098. }
  1099. if (parsedData.bufferViews) {
  1100. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1101. }
  1102. if (parsedData.accessors) {
  1103. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1104. }
  1105. if (parsedData.meshes) {
  1106. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1107. }
  1108. if (parsedData.lights) {
  1109. parseObject(parsedData.lights, "lights", gltfRuntime);
  1110. }
  1111. if (parsedData.cameras) {
  1112. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1113. }
  1114. if (parsedData.nodes) {
  1115. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1116. }
  1117. if (parsedData.images) {
  1118. parseObject(parsedData.images, "images", gltfRuntime);
  1119. }
  1120. if (parsedData.textures) {
  1121. parseObject(parsedData.textures, "textures", gltfRuntime);
  1122. }
  1123. if (parsedData.shaders) {
  1124. parseShaders(parsedData.shaders, gltfRuntime);
  1125. }
  1126. if (parsedData.programs) {
  1127. parseObject(parsedData.programs, "programs", gltfRuntime);
  1128. }
  1129. if (parsedData.samplers) {
  1130. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1131. }
  1132. if (parsedData.techniques) {
  1133. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1134. }
  1135. if (parsedData.materials) {
  1136. parseObject(parsedData.materials, "materials", gltfRuntime);
  1137. }
  1138. if (parsedData.animations) {
  1139. parseObject(parsedData.animations, "animations", gltfRuntime);
  1140. }
  1141. if (parsedData.skins) {
  1142. parseObject(parsedData.skins, "skins", gltfRuntime);
  1143. }
  1144. if (parsedData.scenes) {
  1145. gltfRuntime.scenes = parsedData.scenes;
  1146. }
  1147. if (parsedData.scene && parsedData.scenes) {
  1148. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1149. }
  1150. return gltfRuntime;
  1151. };
  1152. GLTFFileLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1153. var buffer = gltfRuntime.buffers[id];
  1154. if (BABYLON.GLTFUtils.IsBase64(buffer.uri)) {
  1155. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.GLTFUtils.DecodeBase64(buffer.uri))); });
  1156. }
  1157. else {
  1158. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1159. }
  1160. };
  1161. GLTFFileLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1162. var texture = gltfRuntime.textures[id];
  1163. if (!texture || !texture.source) {
  1164. onError();
  1165. return;
  1166. }
  1167. if (texture.babylonTexture) {
  1168. onSuccess(null);
  1169. return;
  1170. }
  1171. var source = gltfRuntime.images[texture.source];
  1172. if (BABYLON.GLTFUtils.IsBase64(source.uri)) {
  1173. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.GLTFUtils.DecodeBase64(source.uri))); });
  1174. }
  1175. else {
  1176. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, null, null, true, onError);
  1177. }
  1178. };
  1179. GLTFFileLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1180. var texture = gltfRuntime.textures[id];
  1181. if (texture.babylonTexture) {
  1182. onSuccess(texture.babylonTexture);
  1183. return;
  1184. }
  1185. var sampler = gltfRuntime.samplers[texture.sampler];
  1186. var createMipMaps = (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1187. (sampler.minFilter === BABYLON.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1188. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1189. (sampler.minFilter === BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1190. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1191. var blob = new Blob([buffer]);
  1192. var blobURL = URL.createObjectURL(blob);
  1193. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  1194. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1195. newTexture.wrapU = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapS);
  1196. newTexture.wrapV = BABYLON.GLTFUtils.GetWrapMode(sampler.wrapT);
  1197. newTexture.name = id;
  1198. texture.babylonTexture = newTexture;
  1199. onSuccess(newTexture);
  1200. };
  1201. GLTFFileLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1202. var shader = gltfRuntime.shaders[id];
  1203. if (BABYLON.GLTFUtils.IsBase64(shader.uri)) {
  1204. var shaderString = atob(shader.uri.split(",")[1]);
  1205. onSuccess(shaderString);
  1206. }
  1207. else {
  1208. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, onError);
  1209. }
  1210. };
  1211. GLTFFileLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1212. var material = gltfRuntime.materials[id];
  1213. var technique = gltfRuntime.techniques[material.technique];
  1214. if (!technique) {
  1215. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  1216. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  1217. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1218. onSuccess(defaultMaterial);
  1219. return;
  1220. }
  1221. var program = gltfRuntime.programs[technique.program];
  1222. var states = technique.states;
  1223. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1224. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1225. var newVertexShader = "";
  1226. var newPixelShader = "";
  1227. var vertexTokenizer = new Tokenizer(vertexShader);
  1228. var pixelTokenizer = new Tokenizer(pixelShader);
  1229. var unTreatedUniforms = {};
  1230. var uniforms = [];
  1231. var attributes = [];
  1232. var samplers = [];
  1233. // Fill uniform, sampler2D and attributes
  1234. for (var unif in technique.uniforms) {
  1235. var uniform = technique.uniforms[unif];
  1236. var uniformParameter = technique.parameters[uniform];
  1237. unTreatedUniforms[unif] = uniformParameter;
  1238. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1239. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1240. if (transformIndex !== -1) {
  1241. uniforms.push(babylonTransforms[transformIndex]);
  1242. delete unTreatedUniforms[unif];
  1243. }
  1244. else {
  1245. uniforms.push(unif);
  1246. }
  1247. }
  1248. else if (uniformParameter.type === BABYLON.EParameterType.SAMPLER_2D) {
  1249. samplers.push(unif);
  1250. }
  1251. else {
  1252. uniforms.push(unif);
  1253. }
  1254. }
  1255. for (var attr in technique.attributes) {
  1256. var attribute = technique.attributes[attr];
  1257. var attributeParameter = technique.parameters[attribute];
  1258. if (attributeParameter.semantic) {
  1259. attributes.push(getAttribute(attributeParameter));
  1260. }
  1261. }
  1262. // Configure vertex shader
  1263. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1264. var tokenType = vertexTokenizer.currentToken;
  1265. if (tokenType !== ETokenType.IDENTIFIER) {
  1266. newVertexShader += vertexTokenizer.currentString;
  1267. continue;
  1268. }
  1269. var foundAttribute = false;
  1270. for (var attr in technique.attributes) {
  1271. var attribute = technique.attributes[attr];
  1272. var attributeParameter = technique.parameters[attribute];
  1273. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1274. newVertexShader += getAttribute(attributeParameter);
  1275. foundAttribute = true;
  1276. break;
  1277. }
  1278. }
  1279. if (foundAttribute) {
  1280. continue;
  1281. }
  1282. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1283. }
  1284. // Configure pixel shader
  1285. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1286. var tokenType = pixelTokenizer.currentToken;
  1287. if (tokenType !== ETokenType.IDENTIFIER) {
  1288. newPixelShader += pixelTokenizer.currentString;
  1289. continue;
  1290. }
  1291. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1292. }
  1293. // Create shader material
  1294. var shaderPath = {
  1295. vertex: program.vertexShader + id,
  1296. fragment: program.fragmentShader + id
  1297. };
  1298. var options = {
  1299. attributes: attributes,
  1300. uniforms: uniforms,
  1301. samplers: samplers,
  1302. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1303. };
  1304. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1305. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1306. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1307. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1308. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1309. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  1310. if (states && states.functions) {
  1311. var functions = states.functions;
  1312. if (functions.cullFace && functions.cullFace[0] !== BABYLON.ECullingType.BACK) {
  1313. shaderMaterial.backFaceCulling = false;
  1314. }
  1315. var blendFunc = functions.blendFuncSeparate;
  1316. if (blendFunc) {
  1317. if (blendFunc[0] === BABYLON.EBlendingFunction.SRC_ALPHA && blendFunc[1] === BABYLON.EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1318. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  1319. }
  1320. else if (blendFunc[0] === BABYLON.EBlendingFunction.ONE && blendFunc[1] === BABYLON.EBlendingFunction.ONE && blendFunc[2] === BABYLON.EBlendingFunction.ZERO && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1321. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  1322. }
  1323. else if (blendFunc[0] === BABYLON.EBlendingFunction.SRC_ALPHA && blendFunc[1] === BABYLON.EBlendingFunction.ONE && blendFunc[2] === BABYLON.EBlendingFunction.ZERO && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1324. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  1325. }
  1326. else if (blendFunc[0] === BABYLON.EBlendingFunction.ZERO && blendFunc[1] === BABYLON.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1327. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  1328. }
  1329. else if (blendFunc[0] === BABYLON.EBlendingFunction.DST_COLOR && blendFunc[1] === BABYLON.EBlendingFunction.ZERO && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1330. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  1331. }
  1332. else if (blendFunc[0] === BABYLON.EBlendingFunction.SRC_ALPHA && blendFunc[1] === BABYLON.EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === BABYLON.EBlendingFunction.ONE && blendFunc[3] === BABYLON.EBlendingFunction.ONE) {
  1333. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  1334. }
  1335. }
  1336. }
  1337. };
  1338. return GLTFFileLoaderBase;
  1339. }());
  1340. BABYLON.GLTFFileLoaderBase = GLTFFileLoaderBase;
  1341. /**
  1342. * glTF File Loader Plugin
  1343. */
  1344. var GLTFFileLoader = (function () {
  1345. function GLTFFileLoader() {
  1346. /**
  1347. * Public members
  1348. */
  1349. this.extensions = {
  1350. ".gltf": { isBinary: false },
  1351. ".glb": { isBinary: true }
  1352. };
  1353. }
  1354. GLTFFileLoader.RegisterExtension = function (extension) {
  1355. if (GLTFFileLoader.Extensions[extension.name]) {
  1356. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1357. return;
  1358. }
  1359. GLTFFileLoader.Extensions[extension.name] = extension;
  1360. };
  1361. /**
  1362. * Import meshes
  1363. */
  1364. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onError) {
  1365. var _this = this;
  1366. scene.useRightHandedSystem = true;
  1367. var gltfRuntime = BABYLON.GLTFFileLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1368. gltfRuntime.importOnlyMeshes = true;
  1369. if (meshesNames === "") {
  1370. gltfRuntime.importMeshesNames = [];
  1371. }
  1372. else if (typeof meshesNames === "string") {
  1373. gltfRuntime.importMeshesNames = [meshesNames];
  1374. }
  1375. else if (meshesNames && !(meshesNames instanceof Array)) {
  1376. gltfRuntime.importMeshesNames = [meshesNames];
  1377. }
  1378. else {
  1379. gltfRuntime.importMeshesNames = [];
  1380. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  1381. }
  1382. // Create nodes
  1383. _this._createNodes(gltfRuntime);
  1384. var meshes = [];
  1385. var skeletons = [];
  1386. // Fill arrays of meshes and skeletons
  1387. for (var nde in gltfRuntime.nodes) {
  1388. var node = gltfRuntime.nodes[nde];
  1389. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  1390. meshes.push(node.babylonNode);
  1391. }
  1392. }
  1393. for (var skl in gltfRuntime.skins) {
  1394. var skin = gltfRuntime.skins[skl];
  1395. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  1396. skeletons.push(skin.babylonSkeleton);
  1397. }
  1398. }
  1399. // Load buffers, shaders, materials, etc.
  1400. _this._loadBuffersAsync(gltfRuntime, function () {
  1401. _this._loadShadersAsync(gltfRuntime, function () {
  1402. importMaterials(gltfRuntime);
  1403. postLoad(gltfRuntime);
  1404. if (!GLTFFileLoader.IncrementalLoading && onSuccess) {
  1405. onSuccess(meshes, null, skeletons);
  1406. }
  1407. });
  1408. });
  1409. if (GLTFFileLoader.IncrementalLoading && onSuccess) {
  1410. onSuccess(meshes, null, skeletons);
  1411. }
  1412. }, onError);
  1413. return true;
  1414. };
  1415. /**
  1416. * Load scene
  1417. */
  1418. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1419. var _this = this;
  1420. scene.useRightHandedSystem = true;
  1421. BABYLON.GLTFFileLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  1422. // Create nodes
  1423. _this._createNodes(gltfRuntime);
  1424. // Load buffers, shaders, materials, etc.
  1425. _this._loadBuffersAsync(gltfRuntime, function () {
  1426. _this._loadShadersAsync(gltfRuntime, function () {
  1427. importMaterials(gltfRuntime);
  1428. postLoad(gltfRuntime);
  1429. if (!GLTFFileLoader.IncrementalLoading) {
  1430. onSuccess();
  1431. }
  1432. });
  1433. });
  1434. if (GLTFFileLoader.IncrementalLoading) {
  1435. onSuccess();
  1436. }
  1437. }, onError);
  1438. return true;
  1439. };
  1440. GLTFFileLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  1441. var hasShaders = false;
  1442. var processShader = function (sha, shader) {
  1443. BABYLON.GLTFFileLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  1444. gltfRuntime.loadedShaderCount++;
  1445. if (shaderString) {
  1446. BABYLON.Effect.ShadersStore[sha + (shader.type === BABYLON.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1447. }
  1448. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1449. onload();
  1450. }
  1451. }, function () {
  1452. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1453. });
  1454. };
  1455. for (var sha in gltfRuntime.shaders) {
  1456. hasShaders = true;
  1457. var shader = gltfRuntime.shaders[sha];
  1458. if (shader) {
  1459. processShader.bind(this, sha, shader)();
  1460. }
  1461. else {
  1462. BABYLON.Tools.Error("No shader named: " + sha);
  1463. }
  1464. }
  1465. if (!hasShaders) {
  1466. onload();
  1467. }
  1468. };
  1469. ;
  1470. GLTFFileLoader.prototype._loadBuffersAsync = function (gltfRuntime, onload) {
  1471. var hasBuffers = false;
  1472. var processBuffer = function (buf, buffer) {
  1473. BABYLON.GLTFFileLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  1474. gltfRuntime.loadedBufferCount++;
  1475. if (bufferView) {
  1476. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1477. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1478. }
  1479. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1480. }
  1481. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1482. onload();
  1483. }
  1484. }, function () {
  1485. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1486. });
  1487. };
  1488. for (var buf in gltfRuntime.buffers) {
  1489. hasBuffers = true;
  1490. var buffer = gltfRuntime.buffers[buf];
  1491. if (buffer) {
  1492. processBuffer.bind(this, buf, buffer)();
  1493. }
  1494. else {
  1495. BABYLON.Tools.Error("No buffer named: " + buf);
  1496. }
  1497. }
  1498. if (!hasBuffers) {
  1499. onload();
  1500. }
  1501. };
  1502. // Creates nodes before loading buffers and shaders
  1503. GLTFFileLoader.prototype._createNodes = function (gltfRuntime) {
  1504. var currentScene = gltfRuntime.currentScene;
  1505. if (currentScene) {
  1506. // Only one scene even if multiple scenes are defined
  1507. for (var i = 0; i < currentScene.nodes.length; i++) {
  1508. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1509. }
  1510. }
  1511. else {
  1512. // Load all scenes
  1513. for (var thing in gltfRuntime.scenes) {
  1514. currentScene = gltfRuntime.scenes[thing];
  1515. for (var i = 0; i < currentScene.nodes.length; i++) {
  1516. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1517. }
  1518. }
  1519. }
  1520. };
  1521. return GLTFFileLoader;
  1522. }());
  1523. /**
  1524. * Private members
  1525. */
  1526. // None
  1527. /**
  1528. * Static members
  1529. */
  1530. GLTFFileLoader.HomogeneousCoordinates = false;
  1531. GLTFFileLoader.IncrementalLoading = true;
  1532. GLTFFileLoader.Extensions = {};
  1533. BABYLON.GLTFFileLoader = GLTFFileLoader;
  1534. ;
  1535. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  1536. })(BABYLON || (BABYLON = {}));
  1537. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  1538. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1539. var BABYLON;
  1540. (function (BABYLON) {
  1541. /**
  1542. * Utils functions for GLTF
  1543. */
  1544. var GLTFUtils = (function () {
  1545. function GLTFUtils() {
  1546. }
  1547. /**
  1548. * Sets the given "parameter" matrix
  1549. * @param scene: the {BABYLON.Scene} object
  1550. * @param source: the source node where to pick the matrix
  1551. * @param parameter: the GLTF technique parameter
  1552. * @param uniformName: the name of the shader's uniform
  1553. * @param shaderMaterial: the shader material
  1554. */
  1555. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  1556. var mat = null;
  1557. if (parameter.semantic === "MODEL") {
  1558. mat = source.getWorldMatrix();
  1559. }
  1560. else if (parameter.semantic === "PROJECTION") {
  1561. mat = scene.getProjectionMatrix();
  1562. }
  1563. else if (parameter.semantic === "VIEW") {
  1564. mat = scene.getViewMatrix();
  1565. }
  1566. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  1567. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  1568. }
  1569. else if (parameter.semantic === "MODELVIEW") {
  1570. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  1571. }
  1572. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  1573. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  1574. }
  1575. else if (parameter.semantic === "MODELINVERSE") {
  1576. mat = source.getWorldMatrix().invert();
  1577. }
  1578. else if (parameter.semantic === "VIEWINVERSE") {
  1579. mat = scene.getViewMatrix().invert();
  1580. }
  1581. else if (parameter.semantic === "PROJECTIONINVERSE") {
  1582. mat = scene.getProjectionMatrix().invert();
  1583. }
  1584. else if (parameter.semantic === "MODELVIEWINVERSE") {
  1585. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  1586. }
  1587. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  1588. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  1589. }
  1590. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  1591. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  1592. }
  1593. else {
  1594. debugger;
  1595. }
  1596. switch (parameter.type) {
  1597. case BABYLON.EParameterType.FLOAT_MAT2:
  1598. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  1599. break;
  1600. case BABYLON.EParameterType.FLOAT_MAT3:
  1601. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  1602. break;
  1603. case BABYLON.EParameterType.FLOAT_MAT4:
  1604. shaderMaterial.setMatrix(uniformName, mat);
  1605. break;
  1606. default: break;
  1607. }
  1608. };
  1609. /**
  1610. * Sets the given "parameter" matrix
  1611. * @param shaderMaterial: the shader material
  1612. * @param uniform: the name of the shader's uniform
  1613. * @param value: the value of the uniform
  1614. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  1615. */
  1616. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  1617. switch (type) {
  1618. case BABYLON.EParameterType.FLOAT:
  1619. shaderMaterial.setFloat(uniform, value);
  1620. return true;
  1621. case BABYLON.EParameterType.FLOAT_VEC2:
  1622. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  1623. return true;
  1624. case BABYLON.EParameterType.FLOAT_VEC3:
  1625. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  1626. return true;
  1627. case BABYLON.EParameterType.FLOAT_VEC4:
  1628. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  1629. return true;
  1630. default: return false;
  1631. }
  1632. };
  1633. /**
  1634. * If the uri is a base64 string
  1635. * @param uri: the uri to test
  1636. */
  1637. GLTFUtils.IsBase64 = function (uri) {
  1638. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  1639. };
  1640. /**
  1641. * Decode the base64 uri
  1642. * @param uri: the uri to decode
  1643. */
  1644. GLTFUtils.DecodeBase64 = function (uri) {
  1645. var decodedString = atob(uri.split(",")[1]);
  1646. var bufferLength = decodedString.length;
  1647. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  1648. for (var i = 0; i < bufferLength; i++) {
  1649. bufferView[i] = decodedString.charCodeAt(i);
  1650. }
  1651. return bufferView.buffer;
  1652. };
  1653. /**
  1654. * Returns the wrap mode of the texture
  1655. * @param mode: the mode value
  1656. */
  1657. GLTFUtils.GetWrapMode = function (mode) {
  1658. switch (mode) {
  1659. case BABYLON.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  1660. case BABYLON.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  1661. case BABYLON.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1662. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  1663. }
  1664. };
  1665. /**
  1666. * Returns the byte stride giving an accessor
  1667. * @param accessor: the GLTF accessor objet
  1668. */
  1669. GLTFUtils.GetByteStrideFromType = function (accessor) {
  1670. // Needs this function since "byteStride" isn't requiered in glTF format
  1671. var type = accessor.type;
  1672. switch (type) {
  1673. case "VEC2": return 2;
  1674. case "VEC3": return 3;
  1675. case "VEC4": return 4;
  1676. case "MAT2": return 4;
  1677. case "MAT3": return 9;
  1678. case "MAT4": return 16;
  1679. default: return 1;
  1680. }
  1681. };
  1682. /**
  1683. * Returns the texture filter mode giving a mode value
  1684. * @param mode: the filter mode value
  1685. */
  1686. GLTFUtils.GetTextureFilterMode = function (mode) {
  1687. switch (mode) {
  1688. case BABYLON.ETextureFilterType.LINEAR:
  1689. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  1690. case BABYLON.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  1691. case BABYLON.ETextureFilterType.NEAREST:
  1692. case BABYLON.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  1693. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  1694. }
  1695. };
  1696. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  1697. var byteOffset = bufferView.byteOffset + byteOffset;
  1698. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  1699. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  1700. throw new Error("Buffer access is out of range");
  1701. }
  1702. var buffer = loadedBufferView.buffer;
  1703. byteOffset += loadedBufferView.byteOffset;
  1704. switch (componentType) {
  1705. case BABYLON.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  1706. case BABYLON.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  1707. case BABYLON.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  1708. case BABYLON.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  1709. default: return new Float32Array(buffer, byteOffset, byteLength);
  1710. }
  1711. };
  1712. /**
  1713. * Returns a buffer from its accessor
  1714. * @param gltfRuntime: the GLTF runtime
  1715. * @param accessor: the GLTF accessor
  1716. */
  1717. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  1718. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  1719. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  1720. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  1721. };
  1722. /**
  1723. * Decodes a buffer view into a string
  1724. * @param view: the buffer view
  1725. */
  1726. GLTFUtils.DecodeBufferToText = function (view) {
  1727. var result = "";
  1728. var length = view.byteLength;
  1729. for (var i = 0; i < length; ++i) {
  1730. result += String.fromCharCode(view[i]);
  1731. }
  1732. return result;
  1733. };
  1734. /**
  1735. * Returns the default material of gltf. Related to
  1736. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  1737. * @param scene: the Babylon.js scene
  1738. */
  1739. GLTFUtils.GetDefaultMaterial = function (scene) {
  1740. if (!GLTFUtils._DefaultMaterial) {
  1741. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  1742. "precision highp float;",
  1743. "",
  1744. "uniform mat4 worldView;",
  1745. "uniform mat4 projection;",
  1746. "",
  1747. "attribute vec3 position;",
  1748. "",
  1749. "void main(void)",
  1750. "{",
  1751. " gl_Position = projection * worldView * vec4(position, 1.0);",
  1752. "}"
  1753. ].join("\n");
  1754. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  1755. "precision highp float;",
  1756. "",
  1757. "uniform vec4 u_emission;",
  1758. "",
  1759. "void main(void)",
  1760. "{",
  1761. " gl_FragColor = u_emission;",
  1762. "}"
  1763. ].join("\n");
  1764. var shaderPath = {
  1765. vertex: "GLTFDefaultMaterial",
  1766. fragment: "GLTFDefaultMaterial"
  1767. };
  1768. var options = {
  1769. attributes: ["position"],
  1770. uniforms: ["worldView", "projection", "u_emission"],
  1771. samplers: [],
  1772. needAlphaBlending: false
  1773. };
  1774. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  1775. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  1776. }
  1777. return GLTFUtils._DefaultMaterial;
  1778. };
  1779. return GLTFUtils;
  1780. }());
  1781. // The GLTF default material
  1782. GLTFUtils._DefaultMaterial = null;
  1783. BABYLON.GLTFUtils = GLTFUtils;
  1784. })(BABYLON || (BABYLON = {}));
  1785. //# sourceMappingURL=babylon.glTFFileLoaderUtils.js.map
  1786. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1787. var BABYLON;
  1788. (function (BABYLON) {
  1789. var GLTFFileLoaderExtension = (function () {
  1790. function GLTFFileLoaderExtension(name) {
  1791. this._name = name;
  1792. }
  1793. Object.defineProperty(GLTFFileLoaderExtension.prototype, "name", {
  1794. get: function () {
  1795. return this._name;
  1796. },
  1797. enumerable: true,
  1798. configurable: true
  1799. });
  1800. /**
  1801. * Defines an override for loading the runtime
  1802. * Return true to stop further extensions from loading the runtime
  1803. */
  1804. GLTFFileLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1805. return false;
  1806. };
  1807. /**
  1808. * Defines an override for loading buffers
  1809. * Return true to stop further extensions from loading this buffer
  1810. */
  1811. GLTFFileLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1812. return false;
  1813. };
  1814. /**
  1815. * Defines an override for loading texture buffers
  1816. * Return true to stop further extensions from loading this texture data
  1817. */
  1818. GLTFFileLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1819. return false;
  1820. };
  1821. /**
  1822. * Defines an override for creating textures
  1823. * Return true to stop further extensions from loading this texture
  1824. */
  1825. GLTFFileLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1826. return false;
  1827. };
  1828. /**
  1829. * Defines an override for loading shader strings
  1830. * Return true to stop further extensions from loading this shader data
  1831. */
  1832. GLTFFileLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1833. return false;
  1834. };
  1835. /**
  1836. * Defines an override for loading materials
  1837. * Return true to stop further extensions from loading this material
  1838. */
  1839. GLTFFileLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1840. return false;
  1841. };
  1842. // ---------
  1843. // Utilities
  1844. // ---------
  1845. GLTFFileLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1846. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1847. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  1848. }, function () {
  1849. setTimeout(function () {
  1850. onSuccess(BABYLON.GLTFFileLoaderBase.CreateRuntime(JSON.parse(data), scene, rootUrl));
  1851. });
  1852. });
  1853. };
  1854. GLTFFileLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1855. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1856. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError);
  1857. }, function () {
  1858. BABYLON.GLTFFileLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError);
  1859. });
  1860. };
  1861. GLTFFileLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  1862. GLTFFileLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) { return GLTFFileLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError); }, onError);
  1863. };
  1864. GLTFFileLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1865. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1866. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1867. }, function () {
  1868. BABYLON.GLTFFileLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  1869. });
  1870. };
  1871. GLTFFileLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  1872. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1873. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1874. }, function () {
  1875. BABYLON.GLTFFileLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  1876. });
  1877. };
  1878. GLTFFileLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1879. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1880. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1881. }, function () {
  1882. BABYLON.GLTFFileLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  1883. });
  1884. };
  1885. GLTFFileLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  1886. GLTFFileLoaderExtension.ApplyExtensions(function (loaderExtension) {
  1887. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1888. }, function () {
  1889. BABYLON.GLTFFileLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  1890. });
  1891. };
  1892. GLTFFileLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  1893. for (var extensionName in BABYLON.GLTFFileLoader.Extensions) {
  1894. var loaderExtension = BABYLON.GLTFFileLoader.Extensions[extensionName];
  1895. if (func(loaderExtension)) {
  1896. return;
  1897. }
  1898. }
  1899. defaultFunc();
  1900. };
  1901. return GLTFFileLoaderExtension;
  1902. }());
  1903. BABYLON.GLTFFileLoaderExtension = GLTFFileLoaderExtension;
  1904. })(BABYLON || (BABYLON = {}));
  1905. //# sourceMappingURL=babylon.glTFFileLoaderExtension.js.map
  1906. /// <reference path="../../../dist/preview release/babylon.d.ts"/>
  1907. var __extends = (this && this.__extends) || function (d, b) {
  1908. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  1909. function __() { this.constructor = d; }
  1910. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1911. };
  1912. var BABYLON;
  1913. (function (BABYLON) {
  1914. var BinaryExtensionBufferName = "binary_glTF";
  1915. var EContentFormat;
  1916. (function (EContentFormat) {
  1917. EContentFormat[EContentFormat["JSON"] = 0] = "JSON";
  1918. })(EContentFormat || (EContentFormat = {}));
  1919. ;
  1920. ;
  1921. ;
  1922. ;
  1923. var GLTFBinaryExtension = (function (_super) {
  1924. __extends(GLTFBinaryExtension, _super);
  1925. function GLTFBinaryExtension() {
  1926. return _super.call(this, "KHR_binary_glTF") || this;
  1927. }
  1928. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  1929. var _this = this;
  1930. if (!(data instanceof ArrayBuffer)) {
  1931. return false;
  1932. }
  1933. setTimeout(function () {
  1934. _this._binary = _this._parseBinary(data);
  1935. if (!_this._binary) {
  1936. onError();
  1937. return true;
  1938. }
  1939. var gltfRuntime = BABYLON.GLTFFileLoaderBase.CreateRuntime(_this._binary.content, scene, rootUrl);
  1940. if (gltfRuntime.extensionsUsed.indexOf(_this.name) === -1) {
  1941. BABYLON.Tools.Warn("glTF binary file does not have " + _this.name + " specified in extensionsUsed");
  1942. gltfRuntime.extensionsUsed.push(_this.name);
  1943. }
  1944. onSuccess(gltfRuntime);
  1945. });
  1946. return true;
  1947. };
  1948. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1949. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  1950. return false;
  1951. }
  1952. if (id !== BinaryExtensionBufferName) {
  1953. return false;
  1954. }
  1955. onSuccess(this._binary.body);
  1956. return true;
  1957. };
  1958. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  1959. var texture = gltfRuntime.textures[id];
  1960. var source = gltfRuntime.images[texture.source];
  1961. if (!source.extensions || !(this.name in source.extensions)) {
  1962. return false;
  1963. }
  1964. var sourceExt = source.extensions[this.name];
  1965. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  1966. var buffer = BABYLON.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, BABYLON.EComponentType.UNSIGNED_BYTE);
  1967. onSuccess(buffer);
  1968. return true;
  1969. };
  1970. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  1971. var shader = gltfRuntime.shaders[id];
  1972. if (!shader.extensions || !(this.name in shader.extensions)) {
  1973. return false;
  1974. }
  1975. var binaryExtensionShader = shader.extensions[this.name];
  1976. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  1977. var shaderBytes = BABYLON.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, BABYLON.EComponentType.UNSIGNED_BYTE);
  1978. setTimeout(function () {
  1979. var shaderString = BABYLON.GLTFUtils.DecodeBufferToText(shaderBytes);
  1980. onSuccess(shaderString);
  1981. });
  1982. return true;
  1983. };
  1984. // Parses a glTF binary array buffer into its content and body
  1985. GLTFBinaryExtension.prototype._parseBinary = function (data) {
  1986. var binaryReader = new BinaryReader(data);
  1987. var magic = BABYLON.GLTFUtils.DecodeBufferToText(binaryReader.getUint8Array(4));
  1988. if (magic != "glTF") {
  1989. BABYLON.Tools.Error("Unexpected magic: " + magic);
  1990. return null;
  1991. }
  1992. var version = binaryReader.getUint32();
  1993. if (version != 1) {
  1994. BABYLON.Tools.Error("Unsupported version: " + version);
  1995. return null;
  1996. }
  1997. var length = binaryReader.getUint32();
  1998. if (length != data.byteLength) {
  1999. BABYLON.Tools.Error("Length in header does not match actual data length: " + length + " != " + data.byteLength);
  2000. return null;
  2001. }
  2002. var contentLength = binaryReader.getUint32();
  2003. var contentFormat = binaryReader.getUint32();
  2004. var content;
  2005. switch (contentFormat) {
  2006. case EContentFormat.JSON:
  2007. var jsonText = BABYLON.GLTFUtils.DecodeBufferToText(binaryReader.getUint8Array(contentLength));
  2008. content = JSON.parse(jsonText);
  2009. break;
  2010. default:
  2011. BABYLON.Tools.Error("Unexpected content format: " + contentFormat);
  2012. return null;
  2013. }
  2014. var body = binaryReader.getUint8Array();
  2015. return {
  2016. content: content,
  2017. body: body
  2018. };
  2019. };
  2020. ;
  2021. return GLTFBinaryExtension;
  2022. }(BABYLON.GLTFFileLoaderExtension));
  2023. BABYLON.GLTFBinaryExtension = GLTFBinaryExtension;
  2024. var BinaryReader = (function () {
  2025. function BinaryReader(arrayBuffer) {
  2026. this._arrayBuffer = arrayBuffer;
  2027. this._dataView = new DataView(arrayBuffer);
  2028. this._byteOffset = 0;
  2029. }
  2030. BinaryReader.prototype.getUint32 = function () {
  2031. var value = this._dataView.getUint32(this._byteOffset, true);
  2032. this._byteOffset += 4;
  2033. return value;
  2034. };
  2035. BinaryReader.prototype.getUint8Array = function (length) {
  2036. if (!length) {
  2037. length = this._arrayBuffer.byteLength - this._byteOffset;
  2038. }
  2039. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  2040. this._byteOffset += length;
  2041. return value;
  2042. };
  2043. return BinaryReader;
  2044. }());
  2045. BABYLON.GLTFFileLoader.RegisterExtension(new GLTFBinaryExtension());
  2046. })(BABYLON || (BABYLON = {}));
  2047. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map