babylonjs.serializers.js 193 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396
  1. (function universalModuleDefinition(root, factory) {
  2. var amdDependencies = [];
  3. var BABYLON = root.BABYLON || this.BABYLON;
  4. if(typeof exports === 'object' && typeof module === 'object') {
  5. BABYLON = BABYLON || require("babylonjs");
  6. module.exports = factory(BABYLON);
  7. } else if(typeof define === 'function' && define.amd) {
  8. amdDependencies.push("babylonjs");
  9. define("babylonjs-serializers", amdDependencies, factory);
  10. } else if(typeof exports === 'object') {
  11. BABYLON = BABYLON || require("babylonjs");
  12. exports["babylonjs-serializers"] = factory(BABYLON);
  13. } else {
  14. root["BABYLON"] = factory(BABYLON);
  15. }
  16. })(this, function(BABYLON) {
  17. BABYLON = BABYLON || this.BABYLON;
  18. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  19. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  20. var BABYLON;
  21. (function (BABYLON) {
  22. var OBJExport = /** @class */ (function () {
  23. function OBJExport() {
  24. }
  25. //Exports the geometrys of a Mesh array in .OBJ file format (text)
  26. OBJExport.OBJ = function (mesh, materials, matlibname, globalposition) {
  27. var output = [];
  28. var v = 1;
  29. if (materials) {
  30. if (!matlibname) {
  31. matlibname = 'mat';
  32. }
  33. output.push("mtllib " + matlibname + ".mtl");
  34. }
  35. for (var j = 0; j < mesh.length; j++) {
  36. output.push("g object" + j);
  37. output.push("o object_" + j);
  38. //Uses the position of the item in the scene, to the file (this back to normal in the end)
  39. var lastMatrix = null;
  40. if (globalposition) {
  41. var newMatrix = BABYLON.Matrix.Translation(mesh[j].position.x, mesh[j].position.y, mesh[j].position.z);
  42. lastMatrix = BABYLON.Matrix.Translation(-(mesh[j].position.x), -(mesh[j].position.y), -(mesh[j].position.z));
  43. mesh[j].bakeTransformIntoVertices(newMatrix);
  44. }
  45. //TODO: submeshes (groups)
  46. //TODO: smoothing groups (s 1, s off);
  47. if (materials) {
  48. var mat = mesh[j].material;
  49. if (mat) {
  50. output.push("usemtl " + mat.id);
  51. }
  52. }
  53. var g = mesh[j].geometry;
  54. if (!g) {
  55. continue;
  56. }
  57. var trunkVerts = g.getVerticesData('position');
  58. var trunkNormals = g.getVerticesData('normal');
  59. var trunkUV = g.getVerticesData('uv');
  60. var trunkFaces = g.getIndices();
  61. var curV = 0;
  62. if (!trunkVerts || !trunkNormals || !trunkUV || !trunkFaces) {
  63. continue;
  64. }
  65. for (var i = 0; i < trunkVerts.length; i += 3) {
  66. output.push("v " + trunkVerts[i] + " " + trunkVerts[i + 1] + " " + trunkVerts[i + 2]);
  67. curV++;
  68. }
  69. for (i = 0; i < trunkNormals.length; i += 3) {
  70. output.push("vn " + trunkNormals[i] + " " + trunkNormals[i + 1] + " " + trunkNormals[i + 2]);
  71. }
  72. for (i = 0; i < trunkUV.length; i += 2) {
  73. output.push("vt " + trunkUV[i] + " " + trunkUV[i + 1]);
  74. }
  75. for (i = 0; i < trunkFaces.length; i += 3) {
  76. output.push("f " + (trunkFaces[i + 2] + v) + "/" + (trunkFaces[i + 2] + v) + "/" + (trunkFaces[i + 2] + v) +
  77. " " + (trunkFaces[i + 1] + v) + "/" + (trunkFaces[i + 1] + v) + "/" + (trunkFaces[i + 1] + v) +
  78. " " + (trunkFaces[i] + v) + "/" + (trunkFaces[i] + v) + "/" + (trunkFaces[i] + v));
  79. }
  80. //back de previous matrix, to not change the original mesh in the scene
  81. if (globalposition && lastMatrix) {
  82. mesh[j].bakeTransformIntoVertices(lastMatrix);
  83. }
  84. v += curV;
  85. }
  86. var text = output.join("\n");
  87. return (text);
  88. };
  89. //Exports the material(s) of a mesh in .MTL file format (text)
  90. //TODO: Export the materials of mesh array
  91. OBJExport.MTL = function (mesh) {
  92. var output = [];
  93. var m = mesh.material;
  94. output.push("newmtl mat1");
  95. output.push(" Ns " + m.specularPower.toFixed(4));
  96. output.push(" Ni 1.5000");
  97. output.push(" d " + m.alpha.toFixed(4));
  98. output.push(" Tr 0.0000");
  99. output.push(" Tf 1.0000 1.0000 1.0000");
  100. output.push(" illum 2");
  101. output.push(" Ka " + m.ambientColor.r.toFixed(4) + " " + m.ambientColor.g.toFixed(4) + " " + m.ambientColor.b.toFixed(4));
  102. output.push(" Kd " + m.diffuseColor.r.toFixed(4) + " " + m.diffuseColor.g.toFixed(4) + " " + m.diffuseColor.b.toFixed(4));
  103. output.push(" Ks " + m.specularColor.r.toFixed(4) + " " + m.specularColor.g.toFixed(4) + " " + m.specularColor.b.toFixed(4));
  104. output.push(" Ke " + m.emissiveColor.r.toFixed(4) + " " + m.emissiveColor.g.toFixed(4) + " " + m.emissiveColor.b.toFixed(4));
  105. //TODO: uv scale, offset, wrap
  106. //TODO: UV mirrored in Blender? second UV channel? lightMap? reflection textures?
  107. var uvscale = "";
  108. if (m.ambientTexture) {
  109. output.push(" map_Ka " + uvscale + m.ambientTexture.name);
  110. }
  111. if (m.diffuseTexture) {
  112. output.push(" map_Kd " + uvscale + m.diffuseTexture.name);
  113. //TODO: alpha testing, opacity in diffuse texture alpha channel (diffuseTexture.hasAlpha -> map_d)
  114. }
  115. if (m.specularTexture) {
  116. output.push(" map_Ks " + uvscale + m.specularTexture.name);
  117. /* TODO: glossiness = specular highlight component is in alpha channel of specularTexture. (???)
  118. if (m.useGlossinessFromSpecularMapAlpha) {
  119. output.push(" map_Ns "+uvscale + m.specularTexture.name);
  120. }
  121. */
  122. }
  123. /* TODO: emissive texture not in .MAT format (???)
  124. if (m.emissiveTexture) {
  125. output.push(" map_d "+uvscale+m.emissiveTexture.name);
  126. }
  127. */
  128. if (m.bumpTexture) {
  129. output.push(" map_bump -imfchan z " + uvscale + m.bumpTexture.name);
  130. }
  131. if (m.opacityTexture) {
  132. output.push(" map_d " + uvscale + m.opacityTexture.name);
  133. }
  134. var text = output.join("\n");
  135. return (text);
  136. };
  137. return OBJExport;
  138. }());
  139. BABYLON.OBJExport = OBJExport;
  140. })(BABYLON || (BABYLON = {}));
  141. //# sourceMappingURL=babylon.objSerializer.js.map
  142. BABYLON.Effect.ShadersStore['setAlphaToOnePixelShader'] = "precision highp float;\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=vec4(color.rgb,1.0);\n}";
  143. var BABYLON;
  144. (function (BABYLON) {
  145. ;
  146. /**
  147. * Class for generating glTF data from a Babylon scene.
  148. */
  149. var GLTF2Export = /** @class */ (function () {
  150. function GLTF2Export() {
  151. }
  152. /**
  153. * Exports the geometry of the scene to .gltf file format asynchronously
  154. * @param scene Babylon scene with scene hierarchy information
  155. * @param filePrefix File prefix to use when generating the glTF file
  156. * @param options Exporter options
  157. * @returns Returns an object with a .gltf file and associates texture names
  158. * as keys and their data and paths as values
  159. */
  160. GLTF2Export.GLTFAsync = function (scene, filePrefix, options) {
  161. return scene.whenReadyAsync().then(function () {
  162. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  163. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  164. return gltfGenerator._generateGLTFAsync(glTFPrefix);
  165. });
  166. };
  167. /**
  168. * Exports the geometry of the scene to .glb file format asychronously
  169. * @param scene Babylon scene with scene hierarchy information
  170. * @param filePrefix File prefix to use when generating glb file
  171. * @param options Exporter options
  172. * @returns Returns an object with a .glb filename as key and data as value
  173. */
  174. GLTF2Export.GLBAsync = function (scene, filePrefix, options) {
  175. return scene.whenReadyAsync().then(function () {
  176. var glTFPrefix = filePrefix.replace(/\.[^/.]+$/, "");
  177. var gltfGenerator = new BABYLON.GLTF2._Exporter(scene, options);
  178. return gltfGenerator._generateGLBAsync(glTFPrefix);
  179. });
  180. };
  181. return GLTF2Export;
  182. }());
  183. BABYLON.GLTF2Export = GLTF2Export;
  184. })(BABYLON || (BABYLON = {}));
  185. //# sourceMappingURL=babylon.glTFSerializer.js.map
  186. /**
  187. * Module for the Babylon glTF 2.0 exporter. Should ONLY be used internally
  188. * @hidden
  189. */
  190. var BABYLON;
  191. (function (BABYLON) {
  192. var GLTF2;
  193. (function (GLTF2) {
  194. /**
  195. * Utility interface for storing vertex attribute data
  196. * @hidden
  197. */
  198. /**
  199. * Converts Babylon Scene into glTF 2.0.
  200. * @hidden
  201. */
  202. var _Exporter = /** @class */ (function () {
  203. /**
  204. * Creates a glTF Exporter instance, which can accept optional exporter options
  205. * @param babylonScene Babylon scene object
  206. * @param options Options to modify the behavior of the exporter
  207. */
  208. function _Exporter(babylonScene, options) {
  209. this.asset = { generator: "BabylonJS", version: "2.0" };
  210. this.babylonScene = babylonScene;
  211. this.bufferViews = [];
  212. this.accessors = [];
  213. this.meshes = [];
  214. this.scenes = [];
  215. this.nodes = [];
  216. this.images = [];
  217. this.materials = [];
  218. this.textures = [];
  219. this.samplers = [];
  220. this.animations = [];
  221. this.imageData = {};
  222. this.convertToRightHandedSystem = this.babylonScene.useRightHandedSystem ? false : true;
  223. var _options = options || {};
  224. this.shouldExportTransformNode = _options.shouldExportTransformNode ? _options.shouldExportTransformNode : function (babylonTransformNode) { return true; };
  225. this.animationSampleRate = _options.animationSampleRate ? _options.animationSampleRate : 1 / 60;
  226. }
  227. _Exporter.prototype.reorderIndicesBasedOnPrimitiveMode = function (submesh, primitiveMode, babylonIndices, byteOffset, binaryWriter) {
  228. switch (primitiveMode) {
  229. case BABYLON.Material.TriangleFillMode: {
  230. if (!byteOffset) {
  231. byteOffset = 0;
  232. }
  233. for (var i = submesh.indexStart, length_1 = submesh.indexStart + submesh.indexCount; i < length_1; i = i + 3) {
  234. var index = byteOffset + i * 4;
  235. // swap the second and third indices
  236. var secondIndex = binaryWriter.getUInt32(index + 4);
  237. var thirdIndex = binaryWriter.getUInt32(index + 8);
  238. binaryWriter.setUInt32(thirdIndex, index + 4);
  239. binaryWriter.setUInt32(secondIndex, index + 8);
  240. }
  241. break;
  242. }
  243. case BABYLON.Material.TriangleFanDrawMode: {
  244. for (var i = submesh.indexStart + submesh.indexCount - 1, start = submesh.indexStart; i >= start; --i) {
  245. binaryWriter.setUInt32(babylonIndices[i], byteOffset);
  246. byteOffset += 4;
  247. }
  248. break;
  249. }
  250. case BABYLON.Material.TriangleStripDrawMode: {
  251. if (submesh.indexCount >= 3) {
  252. binaryWriter.setUInt32(babylonIndices[submesh.indexStart + 2], byteOffset + 4);
  253. binaryWriter.setUInt32(babylonIndices[submesh.indexStart + 1], byteOffset + 8);
  254. }
  255. break;
  256. }
  257. }
  258. };
  259. /**
  260. * Reorders the vertex attribute data based on the primitive mode. This is necessary when indices are not available and the winding order is
  261. * clock-wise during export to glTF
  262. * @param submesh BabylonJS submesh
  263. * @param primitiveMode Primitive mode of the mesh
  264. * @param sideOrientation the winding order of the submesh
  265. * @param vertexBufferKind The type of vertex attribute
  266. * @param meshAttributeArray The vertex attribute data
  267. * @param byteOffset The offset to the binary data
  268. * @param binaryWriter The binary data for the glTF file
  269. */
  270. _Exporter.prototype.reorderVertexAttributeDataBasedOnPrimitiveMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  271. if (this.convertToRightHandedSystem && sideOrientation === BABYLON.Material.ClockWiseSideOrientation) {
  272. switch (primitiveMode) {
  273. case BABYLON.Material.TriangleFillMode: {
  274. this.reorderTriangleFillMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  275. break;
  276. }
  277. case BABYLON.Material.TriangleStripDrawMode: {
  278. this.reorderTriangleStripDrawMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  279. break;
  280. }
  281. case BABYLON.Material.TriangleFanDrawMode: {
  282. this.reorderTriangleFanMode(submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter);
  283. break;
  284. }
  285. }
  286. }
  287. };
  288. /**
  289. * Reorders the vertex attributes in the correct triangle mode order . This is necessary when indices are not available and the winding order is
  290. * clock-wise during export to glTF
  291. * @param submesh BabylonJS submesh
  292. * @param primitiveMode Primitive mode of the mesh
  293. * @param sideOrientation the winding order of the submesh
  294. * @param vertexBufferKind The type of vertex attribute
  295. * @param meshAttributeArray The vertex attribute data
  296. * @param byteOffset The offset to the binary data
  297. * @param binaryWriter The binary data for the glTF file
  298. */
  299. _Exporter.prototype.reorderTriangleFillMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  300. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  301. if (vertexBuffer) {
  302. var stride = vertexBuffer.byteStride / BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  303. if (submesh.verticesCount % 3 !== 0) {
  304. BABYLON.Tools.Error('The submesh vertices for the triangle fill mode is not divisible by 3!');
  305. }
  306. else {
  307. var vertexData = [];
  308. var index = 0;
  309. switch (vertexBufferKind) {
  310. case BABYLON.VertexBuffer.PositionKind:
  311. case BABYLON.VertexBuffer.NormalKind: {
  312. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  313. index = x * stride;
  314. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  315. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + 2 * stride));
  316. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + stride));
  317. }
  318. break;
  319. }
  320. case BABYLON.VertexBuffer.TangentKind: {
  321. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  322. index = x * stride;
  323. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  324. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + 2 * stride));
  325. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + stride));
  326. }
  327. break;
  328. }
  329. case BABYLON.VertexBuffer.ColorKind: {
  330. var size = vertexBuffer.getSize();
  331. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + size) {
  332. index = x * stride;
  333. if (size === 4) {
  334. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  335. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + 2 * stride));
  336. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index + stride));
  337. }
  338. else {
  339. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  340. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + 2 * stride));
  341. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + stride));
  342. }
  343. }
  344. break;
  345. }
  346. case BABYLON.VertexBuffer.UVKind:
  347. case BABYLON.VertexBuffer.UV2Kind: {
  348. for (var x = submesh.verticesStart; x < submesh.verticesStart + submesh.verticesCount; x = x + 3) {
  349. index = x * stride;
  350. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index));
  351. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index + 2 * stride));
  352. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index + stride));
  353. }
  354. break;
  355. }
  356. default: {
  357. BABYLON.Tools.Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  358. }
  359. }
  360. this.writeVertexAttributeData(vertexData, byteOffset, vertexBufferKind, meshAttributeArray, binaryWriter);
  361. }
  362. }
  363. else {
  364. BABYLON.Tools.Warn("reorderTriangleFillMode: Vertex Buffer Kind " + vertexBufferKind + " not present!");
  365. }
  366. };
  367. /**
  368. * Reorders the vertex attributes in the correct triangle strip order. This is necessary when indices are not available and the winding order is
  369. * clock-wise during export to glTF
  370. * @param submesh BabylonJS submesh
  371. * @param primitiveMode Primitive mode of the mesh
  372. * @param sideOrientation the winding order of the submesh
  373. * @param vertexBufferKind The type of vertex attribute
  374. * @param meshAttributeArray The vertex attribute data
  375. * @param byteOffset The offset to the binary data
  376. * @param binaryWriter The binary data for the glTF file
  377. */
  378. _Exporter.prototype.reorderTriangleStripDrawMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  379. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  380. if (vertexBuffer) {
  381. var stride = vertexBuffer.byteStride / BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  382. var vertexData = [];
  383. var index = 0;
  384. switch (vertexBufferKind) {
  385. case BABYLON.VertexBuffer.PositionKind:
  386. case BABYLON.VertexBuffer.NormalKind: {
  387. index = submesh.verticesStart;
  388. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + 2 * stride));
  389. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index + stride));
  390. break;
  391. }
  392. case BABYLON.VertexBuffer.TangentKind: {
  393. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  394. index = x * stride;
  395. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  396. }
  397. break;
  398. }
  399. case BABYLON.VertexBuffer.ColorKind: {
  400. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  401. index = x * stride;
  402. vertexBuffer.getSize() === 4 ? vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index)) : vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  403. }
  404. break;
  405. }
  406. case BABYLON.VertexBuffer.UVKind:
  407. case BABYLON.VertexBuffer.UV2Kind: {
  408. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  409. index = x * stride;
  410. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index));
  411. }
  412. break;
  413. }
  414. default: {
  415. BABYLON.Tools.Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  416. }
  417. }
  418. this.writeVertexAttributeData(vertexData, byteOffset + 12, vertexBufferKind, meshAttributeArray, binaryWriter);
  419. }
  420. else {
  421. BABYLON.Tools.Warn("reorderTriangleStripDrawMode: Vertex buffer kind " + vertexBufferKind + " not present!");
  422. }
  423. };
  424. /**
  425. * Reorders the vertex attributes in the correct triangle fan order. This is necessary when indices are not available and the winding order is
  426. * clock-wise during export to glTF
  427. * @param submesh BabylonJS submesh
  428. * @param primitiveMode Primitive mode of the mesh
  429. * @param sideOrientation the winding order of the submesh
  430. * @param vertexBufferKind The type of vertex attribute
  431. * @param meshAttributeArray The vertex attribute data
  432. * @param byteOffset The offset to the binary data
  433. * @param binaryWriter The binary data for the glTF file
  434. */
  435. _Exporter.prototype.reorderTriangleFanMode = function (submesh, primitiveMode, sideOrientation, vertexBufferKind, meshAttributeArray, byteOffset, binaryWriter) {
  436. var vertexBuffer = this.getVertexBufferFromMesh(vertexBufferKind, submesh.getMesh());
  437. if (vertexBuffer) {
  438. var stride = vertexBuffer.byteStride / BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  439. var vertexData = [];
  440. var index = 0;
  441. switch (vertexBufferKind) {
  442. case BABYLON.VertexBuffer.PositionKind:
  443. case BABYLON.VertexBuffer.NormalKind: {
  444. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  445. index = x * stride;
  446. vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  447. }
  448. break;
  449. }
  450. case BABYLON.VertexBuffer.TangentKind: {
  451. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  452. index = x * stride;
  453. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  454. }
  455. break;
  456. }
  457. case BABYLON.VertexBuffer.ColorKind: {
  458. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  459. index = x * stride;
  460. vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index));
  461. vertexBuffer.getSize() === 4 ? vertexData.push(BABYLON.Vector4.FromArray(meshAttributeArray, index)) : vertexData.push(BABYLON.Vector3.FromArray(meshAttributeArray, index));
  462. }
  463. break;
  464. }
  465. case BABYLON.VertexBuffer.UVKind:
  466. case BABYLON.VertexBuffer.UV2Kind: {
  467. for (var x = submesh.verticesStart + submesh.verticesCount - 1; x >= submesh.verticesStart; --x) {
  468. index = x * stride;
  469. vertexData.push(BABYLON.Vector2.FromArray(meshAttributeArray, index));
  470. }
  471. break;
  472. }
  473. default: {
  474. BABYLON.Tools.Error("Unsupported Vertex Buffer type: " + vertexBufferKind);
  475. }
  476. }
  477. this.writeVertexAttributeData(vertexData, byteOffset, vertexBufferKind, meshAttributeArray, binaryWriter);
  478. }
  479. else {
  480. BABYLON.Tools.Warn("reorderTriangleFanMode: Vertex buffer kind " + vertexBufferKind + " not present!");
  481. }
  482. };
  483. /**
  484. * Writes the vertex attribute data to binary
  485. * @param vertices The vertices to write to the binary writer
  486. * @param byteOffset The offset into the binary writer to overwrite binary data
  487. * @param vertexAttributeKind The vertex attribute type
  488. * @param meshAttributeArray The vertex attribute data
  489. * @param binaryWriter The writer containing the binary data
  490. */
  491. _Exporter.prototype.writeVertexAttributeData = function (vertices, byteOffset, vertexAttributeKind, meshAttributeArray, binaryWriter) {
  492. for (var _i = 0, vertices_1 = vertices; _i < vertices_1.length; _i++) {
  493. var vertex = vertices_1[_i];
  494. if (this.convertToRightHandedSystem && !(vertexAttributeKind === BABYLON.VertexBuffer.ColorKind) && !(vertex instanceof BABYLON.Vector2)) {
  495. if (vertex instanceof BABYLON.Vector3) {
  496. (vertexAttributeKind === BABYLON.VertexBuffer.PositionKind) ? GLTF2._GLTFUtilities.GetRightHandedPositionVector3FromRef(vertex) : GLTF2._GLTFUtilities.GetRightHandedNormalVector3FromRef(vertex);
  497. }
  498. else {
  499. GLTF2._GLTFUtilities.GetRightHandedVector4FromRef(vertex);
  500. }
  501. }
  502. for (var _a = 0, _b = vertex.asArray(); _a < _b.length; _a++) {
  503. var component = _b[_a];
  504. binaryWriter.setFloat32(component, byteOffset);
  505. byteOffset += 4;
  506. }
  507. }
  508. };
  509. /**
  510. * Writes mesh attribute data to a data buffer
  511. * Returns the bytelength of the data
  512. * @param vertexBufferKind Indicates what kind of vertex data is being passed in
  513. * @param meshAttributeArray Array containing the attribute data
  514. * @param binaryWriter The buffer to write the binary data to
  515. * @param indices Used to specify the order of the vertex data
  516. */
  517. _Exporter.prototype.writeAttributeData = function (vertexBufferKind, meshAttributeArray, byteStride, binaryWriter) {
  518. var stride = byteStride / 4;
  519. var vertexAttributes = [];
  520. var index;
  521. switch (vertexBufferKind) {
  522. case BABYLON.VertexBuffer.PositionKind: {
  523. for (var k = 0, length_2 = meshAttributeArray.length / stride; k < length_2; ++k) {
  524. index = k * stride;
  525. var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
  526. if (this.convertToRightHandedSystem) {
  527. GLTF2._GLTFUtilities.GetRightHandedPositionVector3FromRef(vertexData);
  528. }
  529. vertexAttributes.push(vertexData.asArray());
  530. }
  531. break;
  532. }
  533. case BABYLON.VertexBuffer.NormalKind: {
  534. for (var k = 0, length_3 = meshAttributeArray.length / stride; k < length_3; ++k) {
  535. index = k * stride;
  536. var vertexData = BABYLON.Vector3.FromArray(meshAttributeArray, index);
  537. if (this.convertToRightHandedSystem) {
  538. GLTF2._GLTFUtilities.GetRightHandedNormalVector3FromRef(vertexData);
  539. }
  540. vertexAttributes.push(vertexData.asArray());
  541. }
  542. break;
  543. }
  544. case BABYLON.VertexBuffer.TangentKind: {
  545. for (var k = 0, length_4 = meshAttributeArray.length / stride; k < length_4; ++k) {
  546. index = k * stride;
  547. var vertexData = BABYLON.Vector4.FromArray(meshAttributeArray, index);
  548. if (this.convertToRightHandedSystem) {
  549. GLTF2._GLTFUtilities.GetRightHandedVector4FromRef(vertexData);
  550. }
  551. vertexAttributes.push(vertexData.asArray());
  552. }
  553. break;
  554. }
  555. case BABYLON.VertexBuffer.ColorKind: {
  556. for (var k = 0, length_5 = meshAttributeArray.length / stride; k < length_5; ++k) {
  557. index = k * stride;
  558. var vertexData = stride === 3 ? BABYLON.Vector3.FromArray(meshAttributeArray, index) : BABYLON.Vector4.FromArray(meshAttributeArray, index);
  559. vertexAttributes.push(vertexData.asArray());
  560. }
  561. break;
  562. }
  563. case BABYLON.VertexBuffer.UVKind:
  564. case BABYLON.VertexBuffer.UV2Kind: {
  565. for (var k = 0, length_6 = meshAttributeArray.length / stride; k < length_6; ++k) {
  566. index = k * stride;
  567. vertexAttributes.push(this.convertToRightHandedSystem ? [meshAttributeArray[index], meshAttributeArray[index + 1]] : [meshAttributeArray[index], meshAttributeArray[index + 1]]);
  568. }
  569. break;
  570. }
  571. default: {
  572. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + vertexBufferKind);
  573. vertexAttributes = [];
  574. }
  575. }
  576. for (var _i = 0, vertexAttributes_1 = vertexAttributes; _i < vertexAttributes_1.length; _i++) {
  577. var vertexAttribute = vertexAttributes_1[_i];
  578. for (var _a = 0, vertexAttribute_1 = vertexAttribute; _a < vertexAttribute_1.length; _a++) {
  579. var component = vertexAttribute_1[_a];
  580. binaryWriter.setFloat32(component);
  581. }
  582. }
  583. };
  584. /**
  585. * Generates glTF json data
  586. * @param shouldUseGlb Indicates whether the json should be written for a glb file
  587. * @param glTFPrefix Text to use when prefixing a glTF file
  588. * @param prettyPrint Indicates whether the json file should be pretty printed (true) or not (false)
  589. * @returns json data as string
  590. */
  591. _Exporter.prototype.generateJSON = function (shouldUseGlb, glTFPrefix, prettyPrint) {
  592. var _this = this;
  593. var buffer = { byteLength: this.totalByteLength };
  594. var imageName;
  595. var imageData;
  596. var bufferView;
  597. var byteOffset = this.totalByteLength;
  598. var glTF = {
  599. asset: this.asset
  600. };
  601. if (buffer.byteLength) {
  602. glTF.buffers = [buffer];
  603. }
  604. if (this.nodes && this.nodes.length) {
  605. glTF.nodes = this.nodes;
  606. }
  607. if (this.meshes && this.meshes.length) {
  608. glTF.meshes = this.meshes;
  609. }
  610. if (this.scenes && this.scenes.length) {
  611. glTF.scenes = this.scenes;
  612. glTF.scene = 0;
  613. }
  614. if (this.bufferViews && this.bufferViews.length) {
  615. glTF.bufferViews = this.bufferViews;
  616. }
  617. if (this.accessors && this.accessors.length) {
  618. glTF.accessors = this.accessors;
  619. }
  620. if (this.animations && this.animations.length) {
  621. glTF.animations = this.animations;
  622. }
  623. if (this.materials && this.materials.length) {
  624. glTF.materials = this.materials;
  625. }
  626. if (this.textures && this.textures.length) {
  627. glTF.textures = this.textures;
  628. }
  629. if (this.samplers && this.samplers.length) {
  630. glTF.samplers = this.samplers;
  631. }
  632. if (this.images && this.images.length) {
  633. if (!shouldUseGlb) {
  634. glTF.images = this.images;
  635. }
  636. else {
  637. glTF.images = [];
  638. this.images.forEach(function (image) {
  639. if (image.uri) {
  640. imageData = _this.imageData[image.uri];
  641. imageName = image.uri.split('.')[0] + " image";
  642. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, byteOffset, imageData.data.length, undefined, imageName);
  643. byteOffset += imageData.data.buffer.byteLength;
  644. _this.bufferViews.push(bufferView);
  645. image.bufferView = _this.bufferViews.length - 1;
  646. image.name = imageName;
  647. image.mimeType = imageData.mimeType;
  648. image.uri = undefined;
  649. if (!glTF.images) {
  650. glTF.images = [];
  651. }
  652. glTF.images.push(image);
  653. }
  654. });
  655. // Replace uri with bufferview and mime type for glb
  656. buffer.byteLength = byteOffset;
  657. }
  658. }
  659. if (!shouldUseGlb) {
  660. buffer.uri = glTFPrefix + ".bin";
  661. }
  662. var jsonText = prettyPrint ? JSON.stringify(glTF, null, 2) : JSON.stringify(glTF);
  663. return jsonText;
  664. };
  665. /**
  666. * Generates data for .gltf and .bin files based on the glTF prefix string
  667. * @param glTFPrefix Text to use when prefixing a glTF file
  668. * @returns GLTFData with glTF file data
  669. */
  670. _Exporter.prototype._generateGLTFAsync = function (glTFPrefix) {
  671. var _this = this;
  672. return this._generateBinaryAsync().then(function (binaryBuffer) {
  673. var jsonText = _this.generateJSON(false, glTFPrefix, true);
  674. var bin = new Blob([binaryBuffer], { type: 'application/octet-stream' });
  675. var glTFFileName = glTFPrefix + '.gltf';
  676. var glTFBinFile = glTFPrefix + '.bin';
  677. var container = new BABYLON.GLTFData();
  678. container.glTFFiles[glTFFileName] = jsonText;
  679. container.glTFFiles[glTFBinFile] = bin;
  680. if (_this.imageData) {
  681. for (var image in _this.imageData) {
  682. container.glTFFiles[image] = new Blob([_this.imageData[image].data], { type: _this.imageData[image].mimeType });
  683. }
  684. }
  685. return container;
  686. });
  687. };
  688. /**
  689. * Creates a binary buffer for glTF
  690. * @returns array buffer for binary data
  691. */
  692. _Exporter.prototype._generateBinaryAsync = function () {
  693. var binaryWriter = new _BinaryWriter(4);
  694. return this.createSceneAsync(this.babylonScene, binaryWriter).then(function () {
  695. return binaryWriter.getArrayBuffer();
  696. });
  697. };
  698. /**
  699. * Pads the number to a multiple of 4
  700. * @param num number to pad
  701. * @returns padded number
  702. */
  703. _Exporter.prototype._getPadding = function (num) {
  704. var remainder = num % 4;
  705. var padding = remainder === 0 ? remainder : 4 - remainder;
  706. return padding;
  707. };
  708. /**
  709. * Generates a glb file from the json and binary data
  710. * Returns an object with the glb file name as the key and data as the value
  711. * @param glTFPrefix
  712. * @returns object with glb filename as key and data as value
  713. */
  714. _Exporter.prototype._generateGLBAsync = function (glTFPrefix) {
  715. var _this = this;
  716. return this._generateBinaryAsync().then(function (binaryBuffer) {
  717. var jsonText = _this.generateJSON(true);
  718. var glbFileName = glTFPrefix + '.glb';
  719. var headerLength = 12;
  720. var chunkLengthPrefix = 8;
  721. var jsonLength = jsonText.length;
  722. var imageByteLength = 0;
  723. for (var key in _this.imageData) {
  724. imageByteLength += _this.imageData[key].data.byteLength;
  725. }
  726. var jsonPadding = _this._getPadding(jsonLength);
  727. var binPadding = _this._getPadding(binaryBuffer.byteLength);
  728. var imagePadding = _this._getPadding(imageByteLength);
  729. var byteLength = headerLength + (2 * chunkLengthPrefix) + jsonLength + jsonPadding + binaryBuffer.byteLength + binPadding + imageByteLength + imagePadding;
  730. //header
  731. var headerBuffer = new ArrayBuffer(headerLength);
  732. var headerBufferView = new DataView(headerBuffer);
  733. headerBufferView.setUint32(0, 0x46546C67, true); //glTF
  734. headerBufferView.setUint32(4, 2, true); // version
  735. headerBufferView.setUint32(8, byteLength, true); // total bytes in file
  736. //json chunk
  737. var jsonChunkBuffer = new ArrayBuffer(chunkLengthPrefix + jsonLength + jsonPadding);
  738. var jsonChunkBufferView = new DataView(jsonChunkBuffer);
  739. jsonChunkBufferView.setUint32(0, jsonLength + jsonPadding, true);
  740. jsonChunkBufferView.setUint32(4, 0x4E4F534A, true);
  741. //json chunk bytes
  742. var jsonData = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix);
  743. for (var i = 0; i < jsonLength; ++i) {
  744. jsonData[i] = jsonText.charCodeAt(i);
  745. }
  746. //json padding
  747. var jsonPaddingView = new Uint8Array(jsonChunkBuffer, chunkLengthPrefix + jsonLength);
  748. for (var i = 0; i < jsonPadding; ++i) {
  749. jsonPaddingView[i] = 0x20;
  750. }
  751. //binary chunk
  752. var binaryChunkBuffer = new ArrayBuffer(chunkLengthPrefix);
  753. var binaryChunkBufferView = new DataView(binaryChunkBuffer);
  754. binaryChunkBufferView.setUint32(0, binaryBuffer.byteLength + imageByteLength + imagePadding, true);
  755. binaryChunkBufferView.setUint32(4, 0x004E4942, true);
  756. // binary padding
  757. var binPaddingBuffer = new ArrayBuffer(binPadding);
  758. var binPaddingView = new Uint8Array(binPaddingBuffer);
  759. for (var i = 0; i < binPadding; ++i) {
  760. binPaddingView[i] = 0;
  761. }
  762. var imagePaddingBuffer = new ArrayBuffer(imagePadding);
  763. var imagePaddingView = new Uint8Array(imagePaddingBuffer);
  764. for (var i = 0; i < imagePadding; ++i) {
  765. imagePaddingView[i] = 0;
  766. }
  767. var glbData = [headerBuffer, jsonChunkBuffer, binaryChunkBuffer, binaryBuffer];
  768. // binary data
  769. for (var key in _this.imageData) {
  770. glbData.push(_this.imageData[key].data.buffer);
  771. }
  772. glbData.push(binPaddingBuffer);
  773. glbData.push(imagePaddingBuffer);
  774. var glbFile = new Blob(glbData, { type: 'application/octet-stream' });
  775. var container = new BABYLON.GLTFData();
  776. container.glTFFiles[glbFileName] = glbFile;
  777. return container;
  778. });
  779. };
  780. /**
  781. * Sets the TRS for each node
  782. * @param node glTF Node for storing the transformation data
  783. * @param babylonTransformNode Babylon mesh used as the source for the transformation data
  784. */
  785. _Exporter.prototype.setNodeTransformation = function (node, babylonTransformNode) {
  786. if (!babylonTransformNode.position.equalsToFloats(0, 0, 0)) {
  787. node.translation = this.convertToRightHandedSystem ? GLTF2._GLTFUtilities.GetRightHandedPositionVector3(babylonTransformNode.position).asArray() : babylonTransformNode.position.asArray();
  788. }
  789. if (!babylonTransformNode.scaling.equalsToFloats(1, 1, 1)) {
  790. node.scale = babylonTransformNode.scaling.asArray();
  791. }
  792. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(babylonTransformNode.rotation.y, babylonTransformNode.rotation.x, babylonTransformNode.rotation.z);
  793. if (babylonTransformNode.rotationQuaternion) {
  794. rotationQuaternion.multiplyInPlace(babylonTransformNode.rotationQuaternion);
  795. }
  796. if (!(rotationQuaternion.x === 0 && rotationQuaternion.y === 0 && rotationQuaternion.z === 0 && rotationQuaternion.w === 1)) {
  797. if (this.convertToRightHandedSystem) {
  798. GLTF2._GLTFUtilities.GetRightHandedQuaternionFromRef(rotationQuaternion);
  799. }
  800. node.rotation = rotationQuaternion.normalize().asArray();
  801. }
  802. };
  803. _Exporter.prototype.getVertexBufferFromMesh = function (attributeKind, bufferMesh) {
  804. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  805. var vertexBuffer = bufferMesh.getVertexBuffer(attributeKind);
  806. if (vertexBuffer) {
  807. return vertexBuffer;
  808. }
  809. }
  810. return null;
  811. };
  812. /**
  813. * Creates a bufferview based on the vertices type for the Babylon mesh
  814. * @param kind Indicates the type of vertices data
  815. * @param babylonTransformNode The Babylon mesh to get the vertices data from
  816. * @param binaryWriter The buffer to write the bufferview data to
  817. */
  818. _Exporter.prototype.createBufferViewKind = function (kind, babylonTransformNode, binaryWriter, byteStride) {
  819. var bufferMesh = babylonTransformNode instanceof BABYLON.Mesh ?
  820. babylonTransformNode : babylonTransformNode instanceof BABYLON.InstancedMesh ?
  821. babylonTransformNode.sourceMesh : null;
  822. if (bufferMesh) {
  823. var vertexData = bufferMesh.getVerticesData(kind);
  824. if (vertexData) {
  825. var byteLength = vertexData.length * 4;
  826. var bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, byteStride, kind + " - " + bufferMesh.name);
  827. this.bufferViews.push(bufferView);
  828. this.writeAttributeData(kind, vertexData, byteStride, binaryWriter);
  829. }
  830. }
  831. };
  832. /**
  833. * The primitive mode of the Babylon mesh
  834. * @param babylonMesh The BabylonJS mesh
  835. */
  836. _Exporter.prototype.getMeshPrimitiveMode = function (babylonMesh) {
  837. if (babylonMesh instanceof BABYLON.LinesMesh) {
  838. return BABYLON.Material.LineListDrawMode;
  839. }
  840. return babylonMesh.material ? babylonMesh.material.fillMode : BABYLON.Material.TriangleFillMode;
  841. };
  842. /**
  843. * Sets the primitive mode of the glTF mesh primitive
  844. * @param meshPrimitive glTF mesh primitive
  845. * @param primitiveMode The primitive mode
  846. */
  847. _Exporter.prototype.setPrimitiveMode = function (meshPrimitive, primitiveMode) {
  848. switch (primitiveMode) {
  849. case BABYLON.Material.TriangleFillMode: {
  850. // glTF defaults to using Triangle Mode
  851. break;
  852. }
  853. case BABYLON.Material.TriangleStripDrawMode: {
  854. meshPrimitive.mode = 5 /* TRIANGLE_STRIP */;
  855. break;
  856. }
  857. case BABYLON.Material.TriangleFanDrawMode: {
  858. meshPrimitive.mode = 6 /* TRIANGLE_FAN */;
  859. break;
  860. }
  861. case BABYLON.Material.PointListDrawMode: {
  862. meshPrimitive.mode = 0 /* POINTS */;
  863. }
  864. case BABYLON.Material.PointFillMode: {
  865. meshPrimitive.mode = 0 /* POINTS */;
  866. break;
  867. }
  868. case BABYLON.Material.LineLoopDrawMode: {
  869. meshPrimitive.mode = 2 /* LINE_LOOP */;
  870. break;
  871. }
  872. case BABYLON.Material.LineListDrawMode: {
  873. meshPrimitive.mode = 1 /* LINES */;
  874. break;
  875. }
  876. case BABYLON.Material.LineStripDrawMode: {
  877. meshPrimitive.mode = 3 /* LINE_STRIP */;
  878. break;
  879. }
  880. }
  881. };
  882. /**
  883. * Sets the vertex attribute accessor based of the glTF mesh primitive
  884. * @param meshPrimitive glTF mesh primitive
  885. * @param attributeKind vertex attribute
  886. * @returns boolean specifying if uv coordinates are present
  887. */
  888. _Exporter.prototype.setAttributeKind = function (meshPrimitive, attributeKind) {
  889. switch (attributeKind) {
  890. case BABYLON.VertexBuffer.PositionKind: {
  891. meshPrimitive.attributes.POSITION = this.accessors.length - 1;
  892. break;
  893. }
  894. case BABYLON.VertexBuffer.NormalKind: {
  895. meshPrimitive.attributes.NORMAL = this.accessors.length - 1;
  896. break;
  897. }
  898. case BABYLON.VertexBuffer.ColorKind: {
  899. meshPrimitive.attributes.COLOR_0 = this.accessors.length - 1;
  900. break;
  901. }
  902. case BABYLON.VertexBuffer.TangentKind: {
  903. meshPrimitive.attributes.TANGENT = this.accessors.length - 1;
  904. break;
  905. }
  906. case BABYLON.VertexBuffer.UVKind: {
  907. meshPrimitive.attributes.TEXCOORD_0 = this.accessors.length - 1;
  908. break;
  909. }
  910. case BABYLON.VertexBuffer.UV2Kind: {
  911. meshPrimitive.attributes.TEXCOORD_1 = this.accessors.length - 1;
  912. break;
  913. }
  914. default: {
  915. BABYLON.Tools.Warn("Unsupported Vertex Buffer Type: " + attributeKind);
  916. }
  917. }
  918. };
  919. /**
  920. * Sets data for the primitive attributes of each submesh
  921. * @param mesh glTF Mesh object to store the primitive attribute information
  922. * @param babylonTransformNode Babylon mesh to get the primitive attribute data from
  923. * @param binaryWriter Buffer to write the attribute data to
  924. */
  925. _Exporter.prototype.setPrimitiveAttributes = function (mesh, babylonTransformNode, binaryWriter) {
  926. var bufferMesh = null;
  927. var bufferView;
  928. var uvCoordsPresent;
  929. var minMax;
  930. if (babylonTransformNode instanceof BABYLON.Mesh) {
  931. bufferMesh = babylonTransformNode;
  932. }
  933. else if (babylonTransformNode instanceof BABYLON.InstancedMesh) {
  934. bufferMesh = babylonTransformNode.sourceMesh;
  935. }
  936. var attributeData = [
  937. { kind: BABYLON.VertexBuffer.PositionKind, accessorType: "VEC3" /* VEC3 */, byteStride: 12 },
  938. { kind: BABYLON.VertexBuffer.NormalKind, accessorType: "VEC3" /* VEC3 */, byteStride: 12 },
  939. { kind: BABYLON.VertexBuffer.ColorKind, accessorType: "VEC4" /* VEC4 */, byteStride: 16 },
  940. { kind: BABYLON.VertexBuffer.TangentKind, accessorType: "VEC4" /* VEC4 */, byteStride: 16 },
  941. { kind: BABYLON.VertexBuffer.UVKind, accessorType: "VEC2" /* VEC2 */, byteStride: 8 },
  942. { kind: BABYLON.VertexBuffer.UV2Kind, accessorType: "VEC2" /* VEC2 */, byteStride: 8 },
  943. ];
  944. if (bufferMesh) {
  945. var indexBufferViewIndex = null;
  946. var primitiveMode = this.getMeshPrimitiveMode(bufferMesh);
  947. var vertexAttributeBufferViews = {};
  948. // For each BabylonMesh, create bufferviews for each 'kind'
  949. for (var _i = 0, attributeData_1 = attributeData; _i < attributeData_1.length; _i++) {
  950. var attribute = attributeData_1[_i];
  951. var attributeKind = attribute.kind;
  952. if (bufferMesh.isVerticesDataPresent(attributeKind)) {
  953. var vertexBuffer = this.getVertexBufferFromMesh(attributeKind, bufferMesh);
  954. attribute.byteStride = vertexBuffer ? vertexBuffer.getSize() * 4 : BABYLON.VertexBuffer.DeduceStride(attributeKind) * 4;
  955. if (attribute.byteStride === 12) {
  956. attribute.accessorType = "VEC3" /* VEC3 */;
  957. }
  958. this.createBufferViewKind(attributeKind, babylonTransformNode, binaryWriter, attribute.byteStride);
  959. attribute.bufferViewIndex = this.bufferViews.length - 1;
  960. vertexAttributeBufferViews[attributeKind] = attribute.bufferViewIndex;
  961. }
  962. }
  963. if (bufferMesh.getTotalIndices()) {
  964. var indices = bufferMesh.getIndices();
  965. if (indices) {
  966. var byteLength = indices.length * 4;
  967. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, "Indices - " + bufferMesh.name);
  968. this.bufferViews.push(bufferView);
  969. indexBufferViewIndex = this.bufferViews.length - 1;
  970. for (var k = 0, length_7 = indices.length; k < length_7; ++k) {
  971. binaryWriter.setUInt32(indices[k]);
  972. }
  973. }
  974. }
  975. if (bufferMesh.subMeshes) {
  976. // go through all mesh primitives (submeshes)
  977. for (var _a = 0, _b = bufferMesh.subMeshes; _a < _b.length; _a++) {
  978. var submesh = _b[_a];
  979. uvCoordsPresent = false;
  980. var babylonMaterial = submesh.getMaterial();
  981. var materialIndex = null;
  982. if (babylonMaterial) {
  983. if (bufferMesh instanceof BABYLON.LinesMesh) {
  984. // get the color from the lines mesh and set it in the material
  985. var material = {
  986. name: bufferMesh.name + ' material'
  987. };
  988. if (!bufferMesh.color.equals(BABYLON.Color3.White()) || bufferMesh.alpha < 1) {
  989. material.pbrMetallicRoughness = {
  990. baseColorFactor: bufferMesh.color.asArray().concat([bufferMesh.alpha])
  991. };
  992. }
  993. this.materials.push(material);
  994. materialIndex = this.materials.length - 1;
  995. }
  996. else if (babylonMaterial instanceof BABYLON.MultiMaterial) {
  997. babylonMaterial = babylonMaterial.subMaterials[submesh.materialIndex];
  998. if (babylonMaterial) {
  999. materialIndex = this.babylonScene.materials.indexOf(babylonMaterial);
  1000. }
  1001. }
  1002. else {
  1003. materialIndex = this.babylonScene.materials.indexOf(babylonMaterial);
  1004. }
  1005. }
  1006. var glTFMaterial = materialIndex != null ? this.materials[materialIndex] : null;
  1007. var meshPrimitive = { attributes: {} };
  1008. this.setPrimitiveMode(meshPrimitive, primitiveMode);
  1009. for (var _c = 0, attributeData_2 = attributeData; _c < attributeData_2.length; _c++) {
  1010. var attribute = attributeData_2[_c];
  1011. var attributeKind = attribute.kind;
  1012. if (attributeKind === BABYLON.VertexBuffer.UVKind || attributeKind === BABYLON.VertexBuffer.UV2Kind) {
  1013. if (glTFMaterial && !GLTF2._GLTFMaterial._HasTexturesPresent(glTFMaterial)) {
  1014. continue;
  1015. }
  1016. }
  1017. var vertexData = bufferMesh.getVerticesData(attributeKind);
  1018. if (vertexData) {
  1019. var vertexBuffer = this.getVertexBufferFromMesh(attributeKind, bufferMesh);
  1020. if (vertexBuffer) {
  1021. var stride = vertexBuffer.getSize();
  1022. var bufferViewIndex = attribute.bufferViewIndex;
  1023. if (bufferViewIndex != undefined) { // check to see if bufferviewindex has a numeric value assigned.
  1024. minMax = { min: null, max: null };
  1025. if (attributeKind == BABYLON.VertexBuffer.PositionKind) {
  1026. minMax = GLTF2._GLTFUtilities.CalculateMinMaxPositions(vertexData, 0, vertexData.length / stride, this.convertToRightHandedSystem);
  1027. }
  1028. var accessor = GLTF2._GLTFUtilities.CreateAccessor(bufferViewIndex, attributeKind + " - " + babylonTransformNode.name, attribute.accessorType, 5126 /* FLOAT */, vertexData.length / stride, 0, minMax.min, minMax.max);
  1029. this.accessors.push(accessor);
  1030. this.setAttributeKind(meshPrimitive, attributeKind);
  1031. if (meshPrimitive.attributes.TEXCOORD_0 != null || meshPrimitive.attributes.TEXCOORD_1 != null) {
  1032. uvCoordsPresent = true;
  1033. }
  1034. }
  1035. }
  1036. }
  1037. }
  1038. if (indexBufferViewIndex) {
  1039. // Create accessor
  1040. var accessor = GLTF2._GLTFUtilities.CreateAccessor(indexBufferViewIndex, "indices - " + babylonTransformNode.name, "SCALAR" /* SCALAR */, 5125 /* UNSIGNED_INT */, submesh.indexCount, submesh.indexStart * 4, null, null);
  1041. this.accessors.push(accessor);
  1042. meshPrimitive.indices = this.accessors.length - 1;
  1043. }
  1044. if (babylonMaterial) {
  1045. if (materialIndex != null && Object.keys(meshPrimitive.attributes).length > 0) {
  1046. var sideOrientation = this.babylonScene.materials[materialIndex].sideOrientation;
  1047. if (this.convertToRightHandedSystem && sideOrientation === BABYLON.Material.ClockWiseSideOrientation) {
  1048. //Overwrite the indices to be counter-clockwise
  1049. var byteOffset = indexBufferViewIndex != null ? this.bufferViews[indexBufferViewIndex].byteOffset : null;
  1050. if (byteOffset == null) {
  1051. byteOffset = 0;
  1052. }
  1053. var babylonIndices = null;
  1054. if (indexBufferViewIndex != null) {
  1055. babylonIndices = bufferMesh.getIndices();
  1056. }
  1057. if (babylonIndices) {
  1058. this.reorderIndicesBasedOnPrimitiveMode(submesh, primitiveMode, babylonIndices, byteOffset, binaryWriter);
  1059. }
  1060. else {
  1061. for (var _d = 0, attributeData_3 = attributeData; _d < attributeData_3.length; _d++) {
  1062. var attribute = attributeData_3[_d];
  1063. var vertexData = bufferMesh.getVerticesData(attribute.kind);
  1064. if (vertexData) {
  1065. var byteOffset_1 = this.bufferViews[vertexAttributeBufferViews[attribute.kind]].byteOffset;
  1066. if (!byteOffset_1) {
  1067. byteOffset_1 = 0;
  1068. }
  1069. this.reorderVertexAttributeDataBasedOnPrimitiveMode(submesh, primitiveMode, sideOrientation, attribute.kind, vertexData, byteOffset_1, binaryWriter);
  1070. }
  1071. }
  1072. }
  1073. }
  1074. if (!uvCoordsPresent && GLTF2._GLTFMaterial._HasTexturesPresent(this.materials[materialIndex])) {
  1075. var newMat = GLTF2._GLTFMaterial._StripTexturesFromMaterial(this.materials[materialIndex]);
  1076. this.materials.push(newMat);
  1077. materialIndex = this.materials.length - 1;
  1078. }
  1079. meshPrimitive.material = materialIndex;
  1080. }
  1081. }
  1082. mesh.primitives.push(meshPrimitive);
  1083. }
  1084. }
  1085. }
  1086. };
  1087. /**
  1088. * Creates a glTF scene based on the array of meshes
  1089. * Returns the the total byte offset
  1090. * @param babylonScene Babylon scene to get the mesh data from
  1091. * @param binaryWriter Buffer to write binary data to
  1092. */
  1093. _Exporter.prototype.createSceneAsync = function (babylonScene, binaryWriter) {
  1094. var _this = this;
  1095. var scene = { nodes: [] };
  1096. var glTFNodeIndex;
  1097. var glTFNode;
  1098. var directDescendents;
  1099. var nodes = babylonScene.transformNodes.concat(babylonScene.meshes);
  1100. return GLTF2._GLTFMaterial._ConvertMaterialsToGLTFAsync(babylonScene.materials, "image/png" /* PNG */, this.images, this.textures, this.samplers, this.materials, this.imageData, true).then(function () {
  1101. _this.nodeMap = _this.createNodeMapAndAnimations(babylonScene, nodes, _this.shouldExportTransformNode, binaryWriter);
  1102. _this.totalByteLength = binaryWriter.getByteOffset();
  1103. // Build Hierarchy with the node map.
  1104. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  1105. var babylonTransformNode = nodes_1[_i];
  1106. glTFNodeIndex = _this.nodeMap[babylonTransformNode.uniqueId];
  1107. if (glTFNodeIndex != null) {
  1108. glTFNode = _this.nodes[glTFNodeIndex];
  1109. if (!babylonTransformNode.parent) {
  1110. if (!_this.shouldExportTransformNode(babylonTransformNode)) {
  1111. BABYLON.Tools.Log("Omitting " + babylonTransformNode.name + " from scene.");
  1112. }
  1113. else {
  1114. if (_this.convertToRightHandedSystem) {
  1115. if (glTFNode.translation) {
  1116. glTFNode.translation[2] *= -1;
  1117. glTFNode.translation[0] *= -1;
  1118. }
  1119. glTFNode.rotation = glTFNode.rotation ? BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(glTFNode.rotation)).asArray() : (BABYLON.Quaternion.FromArray([0, 1, 0, 0])).asArray();
  1120. }
  1121. scene.nodes.push(glTFNodeIndex);
  1122. }
  1123. }
  1124. directDescendents = babylonTransformNode.getDescendants(true);
  1125. if (!glTFNode.children && directDescendents && directDescendents.length) {
  1126. glTFNode.children = [];
  1127. for (var _a = 0, directDescendents_1 = directDescendents; _a < directDescendents_1.length; _a++) {
  1128. var descendent = directDescendents_1[_a];
  1129. if (_this.nodeMap[descendent.uniqueId] != null) {
  1130. glTFNode.children.push(_this.nodeMap[descendent.uniqueId]);
  1131. }
  1132. }
  1133. }
  1134. }
  1135. }
  1136. ;
  1137. if (scene.nodes.length) {
  1138. _this.scenes.push(scene);
  1139. }
  1140. });
  1141. };
  1142. /**
  1143. * Creates a mapping of Node unique id to node index and handles animations
  1144. * @param babylonScene Babylon Scene
  1145. * @param nodes Babylon transform nodes
  1146. * @param shouldExportTransformNode Callback specifying if a transform node should be exported
  1147. * @param binaryWriter Buffer to write binary data to
  1148. * @returns Node mapping of unique id to index
  1149. */
  1150. _Exporter.prototype.createNodeMapAndAnimations = function (babylonScene, nodes, shouldExportTransformNode, binaryWriter) {
  1151. var _this = this;
  1152. var nodeMap = {};
  1153. var nodeIndex;
  1154. var runtimeGLTFAnimation = {
  1155. name: 'runtime animations',
  1156. channels: [],
  1157. samplers: []
  1158. };
  1159. var idleGLTFAnimations = [];
  1160. var node;
  1161. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  1162. var babylonTransformNode = nodes_2[_i];
  1163. if (shouldExportTransformNode(babylonTransformNode)) {
  1164. node = this.createNode(babylonTransformNode, binaryWriter);
  1165. this.nodes.push(node);
  1166. nodeIndex = this.nodes.length - 1;
  1167. nodeMap[babylonTransformNode.uniqueId] = nodeIndex;
  1168. if (!babylonScene.animationGroups.length && babylonTransformNode.animations.length) {
  1169. GLTF2._GLTFAnimation._CreateNodeAnimationFromTransformNodeAnimations(babylonTransformNode, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, this.nodes, binaryWriter, this.bufferViews, this.accessors, this.convertToRightHandedSystem, this.animationSampleRate);
  1170. }
  1171. }
  1172. else {
  1173. "Excluding mesh " + babylonTransformNode.name;
  1174. }
  1175. }
  1176. ;
  1177. if (runtimeGLTFAnimation.channels.length && runtimeGLTFAnimation.samplers.length) {
  1178. this.animations.push(runtimeGLTFAnimation);
  1179. }
  1180. idleGLTFAnimations.forEach(function (idleGLTFAnimation) {
  1181. if (idleGLTFAnimation.channels.length && idleGLTFAnimation.samplers.length) {
  1182. _this.animations.push(idleGLTFAnimation);
  1183. }
  1184. });
  1185. if (babylonScene.animationGroups.length) {
  1186. GLTF2._GLTFAnimation._CreateNodeAnimationFromAnimationGroups(babylonScene, this.animations, nodeMap, this.nodes, binaryWriter, this.bufferViews, this.accessors, this.convertToRightHandedSystem, this.animationSampleRate);
  1187. }
  1188. return nodeMap;
  1189. };
  1190. /**
  1191. * Creates a glTF node from a Babylon mesh
  1192. * @param babylonMesh Source Babylon mesh
  1193. * @param binaryWriter Buffer for storing geometry data
  1194. * @returns glTF node
  1195. */
  1196. _Exporter.prototype.createNode = function (babylonTransformNode, binaryWriter) {
  1197. // create node to hold translation/rotation/scale and the mesh
  1198. var node = {};
  1199. // create mesh
  1200. var mesh = { primitives: [] };
  1201. if (babylonTransformNode.name) {
  1202. node.name = babylonTransformNode.name;
  1203. }
  1204. // Set transformation
  1205. this.setNodeTransformation(node, babylonTransformNode);
  1206. this.setPrimitiveAttributes(mesh, babylonTransformNode, binaryWriter);
  1207. if (mesh.primitives.length) {
  1208. this.meshes.push(mesh);
  1209. node.mesh = this.meshes.length - 1;
  1210. }
  1211. return node;
  1212. };
  1213. return _Exporter;
  1214. }());
  1215. GLTF2._Exporter = _Exporter;
  1216. /**
  1217. * @hidden
  1218. *
  1219. * Stores glTF binary data. If the array buffer byte length is exceeded, it doubles in size dynamically
  1220. */
  1221. var _BinaryWriter = /** @class */ (function () {
  1222. /**
  1223. * Initialize binary writer with an initial byte length
  1224. * @param byteLength Initial byte length of the array buffer
  1225. */
  1226. function _BinaryWriter(byteLength) {
  1227. this._arrayBuffer = new ArrayBuffer(byteLength);
  1228. this._dataView = new DataView(this._arrayBuffer);
  1229. this._byteOffset = 0;
  1230. }
  1231. /**
  1232. * Resize the array buffer to the specified byte length
  1233. * @param byteLength
  1234. */
  1235. _BinaryWriter.prototype.resizeBuffer = function (byteLength) {
  1236. var newBuffer = new ArrayBuffer(byteLength);
  1237. var oldUint8Array = new Uint8Array(this._arrayBuffer);
  1238. var newUint8Array = new Uint8Array(newBuffer);
  1239. for (var i = 0, length_8 = newUint8Array.byteLength; i < length_8; ++i) {
  1240. newUint8Array[i] = oldUint8Array[i];
  1241. }
  1242. this._arrayBuffer = newBuffer;
  1243. this._dataView = new DataView(this._arrayBuffer);
  1244. };
  1245. /**
  1246. * Get an array buffer with the length of the byte offset
  1247. * @returns ArrayBuffer resized to the byte offset
  1248. */
  1249. _BinaryWriter.prototype.getArrayBuffer = function () {
  1250. this.resizeBuffer(this.getByteOffset());
  1251. return this._arrayBuffer;
  1252. };
  1253. /**
  1254. * Get the byte offset of the array buffer
  1255. * @returns byte offset
  1256. */
  1257. _BinaryWriter.prototype.getByteOffset = function () {
  1258. return this._byteOffset;
  1259. };
  1260. /**
  1261. * Stores an UInt8 in the array buffer
  1262. * @param entry
  1263. * @param byteOffset If defined, specifies where to set the value as an offset.
  1264. */
  1265. _BinaryWriter.prototype.setUInt8 = function (entry, byteOffset) {
  1266. if (byteOffset != null) {
  1267. if (byteOffset < this._byteOffset) {
  1268. this._dataView.setUint8(byteOffset, entry);
  1269. }
  1270. else {
  1271. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1272. }
  1273. }
  1274. else {
  1275. if (this._byteOffset + 1 > this._arrayBuffer.byteLength) {
  1276. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  1277. }
  1278. this._dataView.setUint8(this._byteOffset++, entry);
  1279. }
  1280. };
  1281. /**
  1282. * Gets an UInt32 in the array buffer
  1283. * @param entry
  1284. * @param byteOffset If defined, specifies where to set the value as an offset.
  1285. */
  1286. _BinaryWriter.prototype.getUInt32 = function (byteOffset) {
  1287. if (byteOffset < this._byteOffset) {
  1288. return this._dataView.getUint32(byteOffset, true);
  1289. }
  1290. else {
  1291. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1292. throw new Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1293. }
  1294. };
  1295. _BinaryWriter.prototype.getVector3Float32FromRef = function (vector3, byteOffset) {
  1296. if (byteOffset + 8 > this._byteOffset) {
  1297. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1298. }
  1299. else {
  1300. vector3.x = this._dataView.getFloat32(byteOffset, true);
  1301. vector3.y = this._dataView.getFloat32(byteOffset + 4, true);
  1302. vector3.z = this._dataView.getFloat32(byteOffset + 8, true);
  1303. }
  1304. };
  1305. _BinaryWriter.prototype.setVector3Float32FromRef = function (vector3, byteOffset) {
  1306. if (byteOffset + 8 > this._byteOffset) {
  1307. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1308. }
  1309. else {
  1310. this._dataView.setFloat32(byteOffset, vector3.x, true);
  1311. this._dataView.setFloat32(byteOffset + 4, vector3.y, true);
  1312. this._dataView.setFloat32(byteOffset + 8, vector3.z, true);
  1313. }
  1314. };
  1315. _BinaryWriter.prototype.getVector4Float32FromRef = function (vector4, byteOffset) {
  1316. if (byteOffset + 12 > this._byteOffset) {
  1317. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1318. }
  1319. else {
  1320. vector4.x = this._dataView.getFloat32(byteOffset, true);
  1321. vector4.y = this._dataView.getFloat32(byteOffset + 4, true);
  1322. vector4.z = this._dataView.getFloat32(byteOffset + 8, true);
  1323. vector4.w = this._dataView.getFloat32(byteOffset + 12, true);
  1324. }
  1325. };
  1326. _BinaryWriter.prototype.setVector4Float32FromRef = function (vector4, byteOffset) {
  1327. if (byteOffset + 12 > this._byteOffset) {
  1328. BABYLON.Tools.Error("BinaryWriter: byteoffset is greater than the current binary buffer length!");
  1329. }
  1330. else {
  1331. this._dataView.setFloat32(byteOffset, vector4.x, true);
  1332. this._dataView.setFloat32(byteOffset + 4, vector4.y, true);
  1333. this._dataView.setFloat32(byteOffset + 8, vector4.z, true);
  1334. this._dataView.setFloat32(byteOffset + 12, vector4.w, true);
  1335. }
  1336. };
  1337. /**
  1338. * Stores a Float32 in the array buffer
  1339. * @param entry
  1340. */
  1341. _BinaryWriter.prototype.setFloat32 = function (entry, byteOffset) {
  1342. if (isNaN(entry)) {
  1343. BABYLON.Tools.Error('Invalid data being written!');
  1344. }
  1345. if (byteOffset != null) {
  1346. if (byteOffset < this._byteOffset) {
  1347. this._dataView.setFloat32(byteOffset, entry, true);
  1348. }
  1349. else {
  1350. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary length!');
  1351. }
  1352. }
  1353. if (this._byteOffset + 4 > this._arrayBuffer.byteLength) {
  1354. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  1355. }
  1356. this._dataView.setFloat32(this._byteOffset, entry, true);
  1357. this._byteOffset += 4;
  1358. };
  1359. /**
  1360. * Stores an UInt32 in the array buffer
  1361. * @param entry
  1362. * @param byteOffset If defined, specifies where to set the value as an offset.
  1363. */
  1364. _BinaryWriter.prototype.setUInt32 = function (entry, byteOffset) {
  1365. if (byteOffset != null) {
  1366. if (byteOffset < this._byteOffset) {
  1367. this._dataView.setUint32(byteOffset, entry, true);
  1368. }
  1369. else {
  1370. BABYLON.Tools.Error('BinaryWriter: byteoffset is greater than the current binary buffer length!');
  1371. }
  1372. }
  1373. else {
  1374. if (this._byteOffset + 4 > this._arrayBuffer.byteLength) {
  1375. this.resizeBuffer(this._arrayBuffer.byteLength * 2);
  1376. }
  1377. this._dataView.setUint32(this._byteOffset, entry, true);
  1378. this._byteOffset += 4;
  1379. }
  1380. };
  1381. return _BinaryWriter;
  1382. }());
  1383. GLTF2._BinaryWriter = _BinaryWriter;
  1384. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  1385. })(BABYLON || (BABYLON = {}));
  1386. //# sourceMappingURL=babylon.glTFExporter.js.map
  1387. var BABYLON;
  1388. (function (BABYLON) {
  1389. /**
  1390. * Class for holding and downloading glTF file data
  1391. */
  1392. var GLTFData = /** @class */ (function () {
  1393. /**
  1394. * Initializes the glTF file object
  1395. */
  1396. function GLTFData() {
  1397. this.glTFFiles = {};
  1398. }
  1399. /**
  1400. * Downloads the glTF data as files based on their names and data
  1401. */
  1402. GLTFData.prototype.downloadFiles = function () {
  1403. /**
  1404. * Checks for a matching suffix at the end of a string (for ES5 and lower)
  1405. * @param str Source string
  1406. * @param suffix Suffix to search for in the source string
  1407. * @returns Boolean indicating whether the suffix was found (true) or not (false)
  1408. */
  1409. function endsWith(str, suffix) {
  1410. return str.indexOf(suffix, str.length - suffix.length) !== -1;
  1411. }
  1412. for (var key in this.glTFFiles) {
  1413. var link = document.createElement('a');
  1414. document.body.appendChild(link);
  1415. link.setAttribute("type", "hidden");
  1416. link.download = key;
  1417. var blob = this.glTFFiles[key];
  1418. var mimeType = void 0;
  1419. if (endsWith(key, ".glb")) {
  1420. mimeType = { type: "model/gltf-binary" };
  1421. }
  1422. else if (endsWith(key, ".bin")) {
  1423. mimeType = { type: "application/octet-stream" };
  1424. }
  1425. else if (endsWith(key, ".gltf")) {
  1426. mimeType = { type: "model/gltf+json" };
  1427. }
  1428. else if (endsWith(key, ".jpeg" || ".jpg")) {
  1429. mimeType = { type: "image/jpeg" /* JPEG */ };
  1430. }
  1431. else if (endsWith(key, ".png")) {
  1432. mimeType = { type: "image/png" /* PNG */ };
  1433. }
  1434. link.href = window.URL.createObjectURL(new Blob([blob], mimeType));
  1435. link.click();
  1436. }
  1437. };
  1438. return GLTFData;
  1439. }());
  1440. BABYLON.GLTFData = GLTFData;
  1441. })(BABYLON || (BABYLON = {}));
  1442. //# sourceMappingURL=babylon.glTFData.js.map
  1443. var BABYLON;
  1444. (function (BABYLON) {
  1445. var GLTF2;
  1446. (function (GLTF2) {
  1447. /**
  1448. * Utility methods for working with glTF material conversion properties. This class should only be used internally
  1449. * @hidden
  1450. */
  1451. var _GLTFMaterial = /** @class */ (function () {
  1452. function _GLTFMaterial() {
  1453. }
  1454. /**
  1455. * Specifies if two colors are approximately equal in value
  1456. * @param color1 first color to compare to
  1457. * @param color2 second color to compare to
  1458. * @param epsilon threshold value
  1459. */
  1460. _GLTFMaterial.FuzzyEquals = function (color1, color2, epsilon) {
  1461. return BABYLON.Scalar.WithinEpsilon(color1.r, color2.r, epsilon) &&
  1462. BABYLON.Scalar.WithinEpsilon(color1.g, color2.g, epsilon) &&
  1463. BABYLON.Scalar.WithinEpsilon(color1.b, color2.b, epsilon);
  1464. };
  1465. /**
  1466. * Gets the materials from a Babylon scene and converts them to glTF materials
  1467. * @param scene babylonjs scene
  1468. * @param mimeType texture mime type
  1469. * @param images array of images
  1470. * @param textures array of textures
  1471. * @param materials array of materials
  1472. * @param imageData mapping of texture names to base64 textures
  1473. * @param hasTextureCoords specifies if texture coordinates are present on the material
  1474. */
  1475. _GLTFMaterial._ConvertMaterialsToGLTFAsync = function (babylonMaterials, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords) {
  1476. var promises = [];
  1477. for (var _i = 0, babylonMaterials_1 = babylonMaterials; _i < babylonMaterials_1.length; _i++) {
  1478. var babylonMaterial = babylonMaterials_1[_i];
  1479. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1480. promises.push(_GLTFMaterial._ConvertStandardMaterialAsync(babylonMaterial, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords));
  1481. }
  1482. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1483. promises.push(_GLTFMaterial._ConvertPBRMetallicRoughnessMaterialAsync(babylonMaterial, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords));
  1484. }
  1485. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  1486. promises.push(_GLTFMaterial._ConvertPBRMaterialAsync(babylonMaterial, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords));
  1487. }
  1488. else {
  1489. BABYLON.Tools.Warn("Unsupported material type: " + babylonMaterial.name);
  1490. }
  1491. }
  1492. return Promise.all(promises).then(function () { });
  1493. };
  1494. /**
  1495. * Makes a copy of the glTF material without the texture parameters
  1496. * @param originalMaterial original glTF material
  1497. * @returns glTF material without texture parameters
  1498. */
  1499. _GLTFMaterial._StripTexturesFromMaterial = function (originalMaterial) {
  1500. var newMaterial = {};
  1501. if (originalMaterial) {
  1502. newMaterial.name = originalMaterial.name;
  1503. newMaterial.doubleSided = originalMaterial.doubleSided;
  1504. newMaterial.alphaMode = originalMaterial.alphaMode;
  1505. newMaterial.alphaCutoff = originalMaterial.alphaCutoff;
  1506. newMaterial.emissiveFactor = originalMaterial.emissiveFactor;
  1507. var originalPBRMetallicRoughness = originalMaterial.pbrMetallicRoughness;
  1508. if (originalPBRMetallicRoughness) {
  1509. newMaterial.pbrMetallicRoughness = {};
  1510. newMaterial.pbrMetallicRoughness.baseColorFactor = originalPBRMetallicRoughness.baseColorFactor;
  1511. newMaterial.pbrMetallicRoughness.metallicFactor = originalPBRMetallicRoughness.metallicFactor;
  1512. newMaterial.pbrMetallicRoughness.roughnessFactor = originalPBRMetallicRoughness.roughnessFactor;
  1513. }
  1514. }
  1515. return newMaterial;
  1516. };
  1517. /**
  1518. * Specifies if the material has any texture parameters present
  1519. * @param material glTF Material
  1520. * @returns boolean specifying if texture parameters are present
  1521. */
  1522. _GLTFMaterial._HasTexturesPresent = function (material) {
  1523. if (material.emissiveTexture || material.normalTexture || material.occlusionTexture) {
  1524. return true;
  1525. }
  1526. var pbrMat = material.pbrMetallicRoughness;
  1527. if (pbrMat) {
  1528. if (pbrMat.baseColorTexture || pbrMat.metallicRoughnessTexture) {
  1529. return true;
  1530. }
  1531. }
  1532. return false;
  1533. };
  1534. /**
  1535. * Converts a Babylon StandardMaterial to a glTF Metallic Roughness Material
  1536. * @param babylonStandardMaterial
  1537. * @returns glTF Metallic Roughness Material representation
  1538. */
  1539. _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness = function (babylonStandardMaterial) {
  1540. var P0 = new BABYLON.Vector2(0, 1);
  1541. var P1 = new BABYLON.Vector2(0, 0.1);
  1542. var P2 = new BABYLON.Vector2(0, 0.1);
  1543. var P3 = new BABYLON.Vector2(1300, 0.1);
  1544. /**
  1545. * Given the control points, solve for x based on a given t for a cubic bezier curve
  1546. * @param t a value between 0 and 1
  1547. * @param p0 first control point
  1548. * @param p1 second control point
  1549. * @param p2 third control point
  1550. * @param p3 fourth control point
  1551. * @returns number result of cubic bezier curve at the specified t
  1552. */
  1553. function _cubicBezierCurve(t, p0, p1, p2, p3) {
  1554. return ((1 - t) * (1 - t) * (1 - t) * p0 +
  1555. 3 * (1 - t) * (1 - t) * t * p1 +
  1556. 3 * (1 - t) * t * t * p2 +
  1557. t * t * t * p3);
  1558. }
  1559. /**
  1560. * Evaluates a specified specular power value to determine the appropriate roughness value,
  1561. * based on a pre-defined cubic bezier curve with specular on the abscissa axis (x-axis)
  1562. * and roughness on the ordinant axis (y-axis)
  1563. * @param specularPower specular power of standard material
  1564. * @returns Number representing the roughness value
  1565. */
  1566. function _solveForRoughness(specularPower) {
  1567. var t = Math.pow(specularPower / P3.x, 0.333333);
  1568. return _cubicBezierCurve(t, P0.y, P1.y, P2.y, P3.y);
  1569. }
  1570. var diffuse = babylonStandardMaterial.diffuseColor.toLinearSpace().scale(0.5);
  1571. var opacity = babylonStandardMaterial.alpha;
  1572. var specularPower = BABYLON.Scalar.Clamp(babylonStandardMaterial.specularPower, 0, this._maxSpecularPower);
  1573. var roughness = _solveForRoughness(specularPower);
  1574. var glTFPbrMetallicRoughness = {
  1575. baseColorFactor: [
  1576. diffuse.r,
  1577. diffuse.g,
  1578. diffuse.b,
  1579. opacity
  1580. ],
  1581. metallicFactor: 0,
  1582. roughnessFactor: roughness,
  1583. };
  1584. return glTFPbrMetallicRoughness;
  1585. };
  1586. /**
  1587. * Computes the metallic factor
  1588. * @param diffuse diffused value
  1589. * @param specular specular value
  1590. * @param oneMinusSpecularStrength one minus the specular strength
  1591. * @returns metallic value
  1592. */
  1593. _GLTFMaterial._SolveMetallic = function (diffuse, specular, oneMinusSpecularStrength) {
  1594. if (specular < _GLTFMaterial._dielectricSpecular.r) {
  1595. _GLTFMaterial._dielectricSpecular;
  1596. return 0;
  1597. }
  1598. var a = _GLTFMaterial._dielectricSpecular.r;
  1599. var b = diffuse * oneMinusSpecularStrength / (1.0 - _GLTFMaterial._dielectricSpecular.r) + specular - 2.0 * _GLTFMaterial._dielectricSpecular.r;
  1600. var c = _GLTFMaterial._dielectricSpecular.r - specular;
  1601. var D = b * b - 4.0 * a * c;
  1602. return BABYLON.Scalar.Clamp((-b + Math.sqrt(D)) / (2.0 * a), 0, 1);
  1603. };
  1604. /**
  1605. * Gets the glTF alpha mode from the Babylon Material
  1606. * @param babylonMaterial Babylon Material
  1607. * @returns The Babylon alpha mode value
  1608. */
  1609. _GLTFMaterial._GetAlphaMode = function (babylonMaterial) {
  1610. if (babylonMaterial instanceof BABYLON.StandardMaterial) {
  1611. var babylonStandardMaterial = babylonMaterial;
  1612. if ((babylonStandardMaterial.alpha !== 1.0) ||
  1613. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  1614. (babylonStandardMaterial.opacityTexture != null)) {
  1615. return "BLEND" /* BLEND */;
  1616. }
  1617. else {
  1618. return "OPAQUE" /* OPAQUE */;
  1619. }
  1620. }
  1621. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1622. var babylonPBRMetallicRoughness = babylonMaterial;
  1623. switch (babylonPBRMetallicRoughness.transparencyMode) {
  1624. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1625. return "OPAQUE" /* OPAQUE */;
  1626. }
  1627. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1628. return "BLEND" /* BLEND */;
  1629. }
  1630. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1631. return "MASK" /* MASK */;
  1632. }
  1633. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1634. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1635. return "BLEND" /* BLEND */;
  1636. }
  1637. default: {
  1638. BABYLON.Tools.Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  1639. return null;
  1640. }
  1641. }
  1642. }
  1643. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  1644. var babylonPBRMaterial = babylonMaterial;
  1645. switch (babylonPBRMaterial.transparencyMode) {
  1646. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1647. return "OPAQUE" /* OPAQUE */;
  1648. }
  1649. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1650. return "BLEND" /* BLEND */;
  1651. }
  1652. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1653. return "MASK" /* MASK */;
  1654. }
  1655. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1656. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1657. return "BLEND" /* BLEND */;
  1658. }
  1659. default: {
  1660. BABYLON.Tools.Error("Unsupported alpha mode " + babylonPBRMaterial.transparencyMode);
  1661. return null;
  1662. }
  1663. }
  1664. }
  1665. else {
  1666. BABYLON.Tools.Error("Unsupported Babylon material type");
  1667. return null;
  1668. }
  1669. };
  1670. /**
  1671. * Converts a Babylon Standard Material to a glTF Material
  1672. * @param babylonStandardMaterial BJS Standard Material
  1673. * @param mimeType mime type to use for the textures
  1674. * @param images array of glTF image interfaces
  1675. * @param textures array of glTF texture interfaces
  1676. * @param materials array of glTF material interfaces
  1677. * @param imageData map of image file name to data
  1678. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1679. */
  1680. _GLTFMaterial._ConvertStandardMaterialAsync = function (babylonStandardMaterial, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords) {
  1681. var alphaMode = this._GetAlphaMode(babylonStandardMaterial);
  1682. var useAlpha = alphaMode !== "OPAQUE" /* OPAQUE */ ? true : false;
  1683. var promises = [];
  1684. var glTFPbrMetallicRoughness = _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1685. var glTFMaterial = { name: babylonStandardMaterial.name };
  1686. if (babylonStandardMaterial.backFaceCulling != null && !babylonStandardMaterial.backFaceCulling) {
  1687. if (!babylonStandardMaterial.twoSidedLighting) {
  1688. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1689. }
  1690. glTFMaterial.doubleSided = true;
  1691. }
  1692. if (hasTextureCoords) {
  1693. if (babylonStandardMaterial.diffuseTexture) {
  1694. var promise = _GLTFMaterial._ExportTextureAsync(babylonStandardMaterial.diffuseTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1695. if (glTFTexture) {
  1696. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1697. }
  1698. });
  1699. promises.push(promise);
  1700. }
  1701. if (babylonStandardMaterial.bumpTexture) {
  1702. var promise = _GLTFMaterial._ExportTextureAsync(babylonStandardMaterial.bumpTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1703. if (glTFTexture) {
  1704. glTFMaterial.normalTexture = glTFTexture;
  1705. if (babylonStandardMaterial.bumpTexture != null && babylonStandardMaterial.bumpTexture.level !== 1) {
  1706. glTFMaterial.normalTexture.scale = babylonStandardMaterial.bumpTexture.level;
  1707. }
  1708. }
  1709. });
  1710. promises.push(promise);
  1711. }
  1712. if (babylonStandardMaterial.emissiveTexture) {
  1713. var promise = _GLTFMaterial._ExportTextureAsync(babylonStandardMaterial.emissiveTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFEmissiveTexture) {
  1714. if (glTFEmissiveTexture) {
  1715. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1716. }
  1717. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1718. });
  1719. promises.push(promise);
  1720. }
  1721. if (babylonStandardMaterial.ambientTexture) {
  1722. var promise = _GLTFMaterial._ExportTextureAsync(babylonStandardMaterial.ambientTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1723. if (glTFTexture) {
  1724. var occlusionTexture = {
  1725. index: glTFTexture.index
  1726. };
  1727. glTFMaterial.occlusionTexture = occlusionTexture;
  1728. occlusionTexture.strength = 1.0;
  1729. }
  1730. });
  1731. promises.push(promise);
  1732. }
  1733. }
  1734. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1735. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1736. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1737. }
  1738. else {
  1739. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1740. }
  1741. }
  1742. if (babylonStandardMaterial.emissiveColor && !this.FuzzyEquals(babylonStandardMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1743. glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
  1744. }
  1745. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1746. materials.push(glTFMaterial);
  1747. return Promise.all(promises).then(function () { });
  1748. };
  1749. /**
  1750. *
  1751. * @param texture Texture with alpha to overwrite to one
  1752. * @param useAlpha Specifies if alpha should be preserved or not
  1753. * @returns Promise with texture
  1754. */
  1755. _GLTFMaterial._SetAlphaToOneAsync = function (texture, useAlpha) {
  1756. return new Promise(function (resolve, reject) {
  1757. if (useAlpha) {
  1758. resolve(texture);
  1759. }
  1760. else {
  1761. var scene = texture.getScene();
  1762. if (scene) {
  1763. var proceduralTexture_1 = new BABYLON.ProceduralTexture('texture', texture.getSize(), 'setAlphaToOne', scene);
  1764. if (proceduralTexture_1) {
  1765. proceduralTexture_1.setTexture('textureSampler', texture);
  1766. proceduralTexture_1.onLoadObservable.add(function () { resolve(proceduralTexture_1); });
  1767. }
  1768. else {
  1769. reject("Cannot create procedural texture for " + texture.name + "!");
  1770. }
  1771. }
  1772. else {
  1773. reject("Scene not available for texture " + texture.name);
  1774. }
  1775. }
  1776. });
  1777. };
  1778. /**
  1779. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  1780. * @param babylonPBRMetalRoughMaterial BJS PBR Metallic Roughness Material
  1781. * @param mimeType mime type to use for the textures
  1782. * @param images array of glTF image interfaces
  1783. * @param textures array of glTF texture interfaces
  1784. * @param materials array of glTF material interfaces
  1785. * @param imageData map of image file name to data
  1786. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1787. */
  1788. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterialAsync = function (babylonPBRMetalRoughMaterial, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords) {
  1789. var promises = [];
  1790. var glTFPbrMetallicRoughness = {};
  1791. if (babylonPBRMetalRoughMaterial.baseColor) {
  1792. glTFPbrMetallicRoughness.baseColorFactor = [
  1793. babylonPBRMetalRoughMaterial.baseColor.r,
  1794. babylonPBRMetalRoughMaterial.baseColor.g,
  1795. babylonPBRMetalRoughMaterial.baseColor.b,
  1796. babylonPBRMetalRoughMaterial.alpha
  1797. ];
  1798. }
  1799. if (babylonPBRMetalRoughMaterial.metallic != null && babylonPBRMetalRoughMaterial.metallic !== 1) {
  1800. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1801. }
  1802. if (babylonPBRMetalRoughMaterial.roughness != null && babylonPBRMetalRoughMaterial.roughness !== 1) {
  1803. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1804. }
  1805. var glTFMaterial = {
  1806. name: babylonPBRMetalRoughMaterial.name
  1807. };
  1808. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1809. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1810. }
  1811. var alphaMode = null;
  1812. var useAlpha = false;
  1813. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1814. alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMetalRoughMaterial);
  1815. if (alphaMode) {
  1816. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  1817. glTFMaterial.alphaMode = alphaMode;
  1818. if (alphaMode === "MASK" /* MASK */) {
  1819. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1820. }
  1821. }
  1822. }
  1823. }
  1824. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  1825. useAlpha = true;
  1826. }
  1827. if (hasTextureCoords) {
  1828. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1829. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMetalRoughMaterial.baseTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1830. if (glTFTexture) {
  1831. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1832. }
  1833. });
  1834. promises.push(promise);
  1835. }
  1836. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1837. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMetalRoughMaterial.normalTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1838. if (glTFTexture) {
  1839. glTFMaterial.normalTexture = glTFTexture;
  1840. if (babylonPBRMetalRoughMaterial.normalTexture.level !== 1) {
  1841. glTFMaterial.normalTexture.scale = babylonPBRMetalRoughMaterial.normalTexture.level;
  1842. }
  1843. }
  1844. });
  1845. promises.push(promise);
  1846. }
  1847. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1848. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1849. if (glTFTexture) {
  1850. glTFMaterial.occlusionTexture = glTFTexture;
  1851. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1852. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1853. }
  1854. }
  1855. });
  1856. promises.push(promise);
  1857. }
  1858. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1859. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1860. if (glTFTexture) {
  1861. glTFMaterial.emissiveTexture = glTFTexture;
  1862. }
  1863. });
  1864. promises.push(promise);
  1865. }
  1866. }
  1867. if (this.FuzzyEquals(babylonPBRMetalRoughMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1868. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1869. }
  1870. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1871. materials.push(glTFMaterial);
  1872. return Promise.all(promises).then(function () { });
  1873. };
  1874. /**
  1875. * Converts an image typed array buffer to a base64 image
  1876. * @param buffer typed array buffer
  1877. * @param width width of the image
  1878. * @param height height of the image
  1879. * @param mimeType mimetype of the image
  1880. * @returns base64 image string
  1881. */
  1882. _GLTFMaterial._CreateBase64FromCanvas = function (buffer, width, height, mimeType) {
  1883. var imageCanvas = document.createElement('canvas');
  1884. imageCanvas.width = width;
  1885. imageCanvas.height = height;
  1886. imageCanvas.id = "WriteCanvas";
  1887. var ctx = imageCanvas.getContext('2d');
  1888. var imgData = ctx.createImageData(width, height);
  1889. imgData.data.set(buffer);
  1890. ctx.putImageData(imgData, 0, 0);
  1891. return imageCanvas.toDataURL(mimeType);
  1892. };
  1893. /**
  1894. * Generates a white texture based on the specified width and height
  1895. * @param width width of the texture in pixels
  1896. * @param height height of the texture in pixels
  1897. * @param scene babylonjs scene
  1898. * @returns white texture
  1899. */
  1900. _GLTFMaterial._CreateWhiteTexture = function (width, height, scene) {
  1901. var data = new Uint8Array(width * height * 4);
  1902. for (var i = 0; i < data.length; i = i + 4) {
  1903. data[i] = data[i + 1] = data[i + 2] = data[i + 3] = 0xFF;
  1904. }
  1905. var rawTexture = BABYLON.RawTexture.CreateRGBATexture(data, width, height, scene);
  1906. return rawTexture;
  1907. };
  1908. /**
  1909. * Resizes the two source textures to the same dimensions. If a texture is null, a default white texture is generated. If both textures are null, returns null
  1910. * @param texture1 first texture to resize
  1911. * @param texture2 second texture to resize
  1912. * @param scene babylonjs scene
  1913. * @returns resized textures or null
  1914. */
  1915. _GLTFMaterial._ResizeTexturesToSameDimensions = function (texture1, texture2, scene) {
  1916. var texture1Size = texture1 ? texture1.getSize() : { width: 0, height: 0 };
  1917. var texture2Size = texture2 ? texture2.getSize() : { width: 0, height: 0 };
  1918. var resizedTexture1;
  1919. var resizedTexture2;
  1920. if (texture1Size.width < texture2Size.width) {
  1921. if (texture1) {
  1922. resizedTexture1 = BABYLON.TextureTools.CreateResizedCopy(texture1, texture2Size.width, texture2Size.height, true);
  1923. }
  1924. else {
  1925. resizedTexture1 = this._CreateWhiteTexture(texture2Size.width, texture2Size.height, scene);
  1926. }
  1927. resizedTexture2 = texture2;
  1928. }
  1929. else if (texture1Size.width > texture2Size.width) {
  1930. if (texture2) {
  1931. resizedTexture2 = BABYLON.TextureTools.CreateResizedCopy(texture2, texture1Size.width, texture1Size.height, true);
  1932. }
  1933. else {
  1934. resizedTexture2 = this._CreateWhiteTexture(texture1Size.width, texture1Size.height, scene);
  1935. }
  1936. resizedTexture1 = texture1;
  1937. }
  1938. else {
  1939. resizedTexture1 = texture1;
  1940. resizedTexture2 = texture2;
  1941. }
  1942. return {
  1943. "texture1": resizedTexture1,
  1944. "texture2": resizedTexture2
  1945. };
  1946. };
  1947. /**
  1948. * Convert Specular Glossiness Textures to Metallic Roughness
  1949. * See link below for info on the material conversions from PBR Metallic/Roughness and Specular/Glossiness
  1950. * @link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows-bjs/js/babylon.pbrUtilities.js
  1951. * @param diffuseTexture texture used to store diffuse information
  1952. * @param specularGlossinessTexture texture used to store specular and glossiness information
  1953. * @param factors specular glossiness material factors
  1954. * @param mimeType the mime type to use for the texture
  1955. * @returns pbr metallic roughness interface or null
  1956. */
  1957. _GLTFMaterial._ConvertSpecularGlossinessTexturesToMetallicRoughness = function (diffuseTexture, specularGlossinessTexture, factors, mimeType) {
  1958. if (!(diffuseTexture || specularGlossinessTexture)) {
  1959. BABYLON.Tools.Warn('_ConvertSpecularGlosinessTexturesToMetallicRoughness: diffuse and specular glossiness textures are not defined!');
  1960. return null;
  1961. }
  1962. var scene = diffuseTexture ? diffuseTexture.getScene() : specularGlossinessTexture ? specularGlossinessTexture.getScene() : null;
  1963. if (scene) {
  1964. var resizedTextures = this._ResizeTexturesToSameDimensions(diffuseTexture, specularGlossinessTexture, scene);
  1965. var diffuseSize = resizedTextures.texture1.getSize();
  1966. var diffuseBuffer = void 0;
  1967. var specularGlossinessBuffer = void 0;
  1968. var width = diffuseSize.width;
  1969. var height = diffuseSize.height;
  1970. var pixels = (resizedTextures.texture1.readPixels());
  1971. if (pixels instanceof Uint8Array) {
  1972. diffuseBuffer = (resizedTextures.texture1.readPixels());
  1973. pixels = resizedTextures.texture2.readPixels();
  1974. if (pixels instanceof Uint8Array) {
  1975. specularGlossinessBuffer = (resizedTextures.texture2.readPixels());
  1976. var byteLength = specularGlossinessBuffer.byteLength;
  1977. var metallicRoughnessBuffer = new Uint8Array(byteLength);
  1978. var baseColorBuffer = new Uint8Array(byteLength);
  1979. var strideSize = 4;
  1980. var maxBaseColor = BABYLON.Color3.Black();
  1981. var maxMetallic = 0;
  1982. var maxRoughness = 0;
  1983. for (var h = 0; h < height; ++h) {
  1984. for (var w = 0; w < width; ++w) {
  1985. var offset = (width * h + w) * strideSize;
  1986. var diffuseColor = BABYLON.Color3.FromInts(diffuseBuffer[offset], diffuseBuffer[offset + 1], diffuseBuffer[offset + 2]).toLinearSpace().multiply(factors.diffuseColor);
  1987. var specularColor = BABYLON.Color3.FromInts(specularGlossinessBuffer[offset], specularGlossinessBuffer[offset + 1], specularGlossinessBuffer[offset + 2]).toLinearSpace().multiply(factors.specularColor);
  1988. var glossiness = (specularGlossinessBuffer[offset + 3] / 255) * factors.glossiness;
  1989. var specularGlossiness = {
  1990. diffuseColor: diffuseColor,
  1991. specularColor: specularColor,
  1992. glossiness: glossiness
  1993. };
  1994. var metallicRoughness = this._ConvertSpecularGlossinessToMetallicRoughness(specularGlossiness);
  1995. maxBaseColor.r = Math.max(maxBaseColor.r, metallicRoughness.baseColor.r);
  1996. maxBaseColor.g = Math.max(maxBaseColor.g, metallicRoughness.baseColor.g);
  1997. maxBaseColor.b = Math.max(maxBaseColor.b, metallicRoughness.baseColor.b);
  1998. maxMetallic = Math.max(maxMetallic, metallicRoughness.metallic);
  1999. maxRoughness = Math.max(maxRoughness, metallicRoughness.roughness);
  2000. baseColorBuffer[offset] = metallicRoughness.baseColor.r * 255;
  2001. baseColorBuffer[offset + 1] = metallicRoughness.baseColor.g * 255;
  2002. baseColorBuffer[offset + 2] = metallicRoughness.baseColor.b * 255;
  2003. baseColorBuffer[offset + 3] = resizedTextures.texture1.hasAlpha ? diffuseBuffer[offset + 3] : 255;
  2004. metallicRoughnessBuffer[offset] = 0;
  2005. metallicRoughnessBuffer[offset + 1] = metallicRoughness.roughness * 255;
  2006. metallicRoughnessBuffer[offset + 2] = metallicRoughness.metallic * 255;
  2007. metallicRoughnessBuffer[offset + 3] = 255;
  2008. }
  2009. }
  2010. // Retrieves the metallic roughness factors from the maximum texture values.
  2011. var metallicRoughnessFactors = {
  2012. baseColor: maxBaseColor,
  2013. metallic: maxMetallic,
  2014. roughness: maxRoughness
  2015. };
  2016. var writeOutMetallicRoughnessTexture = false;
  2017. var writeOutBaseColorTexture = false;
  2018. for (var h = 0; h < height; ++h) {
  2019. for (var w = 0; w < width; ++w) {
  2020. var destinationOffset = (width * h + w) * strideSize;
  2021. baseColorBuffer[destinationOffset] /= metallicRoughnessFactors.baseColor.r > this._epsilon ? metallicRoughnessFactors.baseColor.r : 1;
  2022. baseColorBuffer[destinationOffset + 1] /= metallicRoughnessFactors.baseColor.g > this._epsilon ? metallicRoughnessFactors.baseColor.g : 1;
  2023. baseColorBuffer[destinationOffset + 2] /= metallicRoughnessFactors.baseColor.b > this._epsilon ? metallicRoughnessFactors.baseColor.b : 1;
  2024. var linearBaseColorPixel = BABYLON.Color3.FromInts(baseColorBuffer[destinationOffset], baseColorBuffer[destinationOffset + 1], baseColorBuffer[destinationOffset + 2]);
  2025. var sRGBBaseColorPixel = linearBaseColorPixel.toGammaSpace();
  2026. baseColorBuffer[destinationOffset] = sRGBBaseColorPixel.r * 255;
  2027. baseColorBuffer[destinationOffset + 1] = sRGBBaseColorPixel.g * 255;
  2028. baseColorBuffer[destinationOffset + 2] = sRGBBaseColorPixel.b * 255;
  2029. if (!this.FuzzyEquals(sRGBBaseColorPixel, BABYLON.Color3.White(), this._epsilon)) {
  2030. writeOutBaseColorTexture = true;
  2031. }
  2032. metallicRoughnessBuffer[destinationOffset + 1] /= metallicRoughnessFactors.roughness > this._epsilon ? metallicRoughnessFactors.roughness : 1;
  2033. metallicRoughnessBuffer[destinationOffset + 2] /= metallicRoughnessFactors.metallic > this._epsilon ? metallicRoughnessFactors.metallic : 1;
  2034. var metallicRoughnessPixel = BABYLON.Color3.FromInts(255, metallicRoughnessBuffer[destinationOffset + 1], metallicRoughnessBuffer[destinationOffset + 2]);
  2035. if (!this.FuzzyEquals(metallicRoughnessPixel, BABYLON.Color3.White(), this._epsilon)) {
  2036. writeOutMetallicRoughnessTexture = true;
  2037. }
  2038. }
  2039. }
  2040. if (writeOutMetallicRoughnessTexture) {
  2041. var metallicRoughnessBase64 = this._CreateBase64FromCanvas(metallicRoughnessBuffer, width, height, mimeType);
  2042. metallicRoughnessFactors.metallicRoughnessTextureBase64 = metallicRoughnessBase64;
  2043. }
  2044. if (writeOutBaseColorTexture) {
  2045. var baseColorBase64 = this._CreateBase64FromCanvas(baseColorBuffer, width, height, mimeType);
  2046. metallicRoughnessFactors.baseColorTextureBase64 = baseColorBase64;
  2047. }
  2048. return metallicRoughnessFactors;
  2049. }
  2050. else {
  2051. BABYLON.Tools.Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture2.name);
  2052. }
  2053. }
  2054. else {
  2055. BABYLON.Tools.Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture1.name);
  2056. }
  2057. }
  2058. else {
  2059. BABYLON.Tools.Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!");
  2060. }
  2061. return null;
  2062. };
  2063. /**
  2064. * Converts specular glossiness material properties to metallic roughness
  2065. * @param specularGlossiness interface with specular glossiness material properties
  2066. * @returns interface with metallic roughness material properties
  2067. */
  2068. _GLTFMaterial._ConvertSpecularGlossinessToMetallicRoughness = function (specularGlossiness) {
  2069. var diffusePerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.diffuseColor);
  2070. var specularPerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.specularColor);
  2071. var oneMinusSpecularStrength = 1 - _GLTFMaterial._GetMaxComponent(specularGlossiness.specularColor);
  2072. var metallic = _GLTFMaterial._SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  2073. var baseColorFromDiffuse = specularGlossiness.diffuseColor.scale(oneMinusSpecularStrength / (1.0 - this._dielectricSpecular.r) / Math.max(1 - metallic, this._epsilon));
  2074. var baseColorFromSpecular = specularGlossiness.specularColor.subtract(this._dielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, this._epsilon));
  2075. var baseColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  2076. baseColor = baseColor.clampToRef(0, 1, baseColor);
  2077. var metallicRoughness = {
  2078. baseColor: baseColor,
  2079. metallic: metallic,
  2080. roughness: 1 - specularGlossiness.glossiness
  2081. };
  2082. return metallicRoughness;
  2083. };
  2084. /**
  2085. * Calculates the surface reflectance, independent of lighting conditions
  2086. * @param color Color source to calculate brightness from
  2087. * @returns number representing the perceived brightness, or zero if color is undefined
  2088. */
  2089. _GLTFMaterial._GetPerceivedBrightness = function (color) {
  2090. if (color) {
  2091. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  2092. }
  2093. return 0;
  2094. };
  2095. /**
  2096. * Returns the maximum color component value
  2097. * @param color
  2098. * @returns maximum color component value, or zero if color is null or undefined
  2099. */
  2100. _GLTFMaterial._GetMaxComponent = function (color) {
  2101. if (color) {
  2102. return Math.max(color.r, Math.max(color.g, color.b));
  2103. }
  2104. return 0;
  2105. };
  2106. /**
  2107. * Convert a PBRMaterial (Metallic/Roughness) to Metallic Roughness factors
  2108. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  2109. * @param mimeType mime type to use for the textures
  2110. * @param images array of glTF image interfaces
  2111. * @param textures array of glTF texture interfaces
  2112. * @param glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  2113. * @param imageData map of image file name to data
  2114. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2115. * @returns glTF PBR Metallic Roughness factors
  2116. */
  2117. _GLTFMaterial._ConvertMetalRoughFactorsToMetallicRoughnessAsync = function (babylonPBRMaterial, mimeType, images, textures, samplers, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  2118. var alphaMode = this._GetAlphaMode(babylonPBRMaterial);
  2119. var useAlpha = alphaMode !== "OPAQUE" /* OPAQUE */ ? true : false;
  2120. var promises = [];
  2121. var metallicRoughness = {
  2122. baseColor: babylonPBRMaterial.albedoColor,
  2123. metallic: babylonPBRMaterial.metallic,
  2124. roughness: babylonPBRMaterial.roughness
  2125. };
  2126. if (hasTextureCoords) {
  2127. if (babylonPBRMaterial.albedoTexture) {
  2128. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMaterial.albedoTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  2129. if (glTFTexture) {
  2130. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  2131. }
  2132. });
  2133. promises.push(promise);
  2134. }
  2135. if (babylonPBRMaterial.metallicTexture) {
  2136. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMaterial.metallicTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  2137. if (glTFTexture) {
  2138. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFTexture;
  2139. }
  2140. });
  2141. promises.push(promise);
  2142. }
  2143. }
  2144. return Promise.all(promises).then(function () {
  2145. return metallicRoughness;
  2146. });
  2147. };
  2148. _GLTFMaterial._GetGLTFTextureSampler = function (texture) {
  2149. var sampler = _GLTFMaterial._GetGLTFTextureWrapModesSampler(texture);
  2150. var samplingMode = texture instanceof BABYLON.Texture ? texture.samplingMode : null;
  2151. if (samplingMode != null) {
  2152. switch (samplingMode) {
  2153. case BABYLON.Texture.LINEAR_LINEAR: {
  2154. sampler.magFilter = 9729 /* LINEAR */;
  2155. sampler.minFilter = 9729 /* LINEAR */;
  2156. break;
  2157. }
  2158. case BABYLON.Texture.LINEAR_NEAREST: {
  2159. sampler.magFilter = 9729 /* LINEAR */;
  2160. sampler.minFilter = 9728 /* NEAREST */;
  2161. break;
  2162. }
  2163. case BABYLON.Texture.NEAREST_LINEAR: {
  2164. sampler.magFilter = 9728 /* NEAREST */;
  2165. sampler.minFilter = 9729 /* LINEAR */;
  2166. break;
  2167. }
  2168. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR: {
  2169. sampler.magFilter = 9728 /* NEAREST */;
  2170. sampler.minFilter = 9987 /* LINEAR_MIPMAP_LINEAR */;
  2171. break;
  2172. }
  2173. case BABYLON.Texture.NEAREST_NEAREST: {
  2174. sampler.magFilter = 9728 /* NEAREST */;
  2175. sampler.minFilter = 9728 /* NEAREST */;
  2176. break;
  2177. }
  2178. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST: {
  2179. sampler.magFilter = 9728 /* NEAREST */;
  2180. sampler.minFilter = 9985 /* LINEAR_MIPMAP_NEAREST */;
  2181. break;
  2182. }
  2183. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST: {
  2184. sampler.magFilter = 9729 /* LINEAR */;
  2185. sampler.minFilter = 9984 /* NEAREST_MIPMAP_NEAREST */;
  2186. break;
  2187. }
  2188. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR: {
  2189. sampler.magFilter = 9729 /* LINEAR */;
  2190. sampler.minFilter = 9986 /* NEAREST_MIPMAP_LINEAR */;
  2191. break;
  2192. }
  2193. case BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR: {
  2194. sampler.magFilter = 9728 /* NEAREST */;
  2195. sampler.minFilter = 9986 /* NEAREST_MIPMAP_LINEAR */;
  2196. break;
  2197. }
  2198. case BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR: {
  2199. sampler.magFilter = 9729 /* LINEAR */;
  2200. sampler.minFilter = 9987 /* LINEAR_MIPMAP_LINEAR */;
  2201. break;
  2202. }
  2203. case BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST: {
  2204. sampler.magFilter = 9729 /* LINEAR */;
  2205. sampler.minFilter = 9985 /* LINEAR_MIPMAP_NEAREST */;
  2206. break;
  2207. }
  2208. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST: {
  2209. sampler.magFilter = 9728 /* NEAREST */;
  2210. sampler.minFilter = 9984 /* NEAREST_MIPMAP_NEAREST */;
  2211. break;
  2212. }
  2213. }
  2214. }
  2215. return sampler;
  2216. };
  2217. _GLTFMaterial._GetGLTFTextureWrapMode = function (wrapMode) {
  2218. switch (wrapMode) {
  2219. case BABYLON.Texture.WRAP_ADDRESSMODE: {
  2220. return 10497 /* REPEAT */;
  2221. }
  2222. case BABYLON.Texture.CLAMP_ADDRESSMODE: {
  2223. return 33071 /* CLAMP_TO_EDGE */;
  2224. }
  2225. case BABYLON.Texture.MIRROR_ADDRESSMODE: {
  2226. return 33648 /* MIRRORED_REPEAT */;
  2227. }
  2228. default: {
  2229. BABYLON.Tools.Error("Unsupported Texture Wrap Mode " + wrapMode + "!");
  2230. return 10497 /* REPEAT */;
  2231. }
  2232. }
  2233. };
  2234. _GLTFMaterial._GetGLTFTextureWrapModesSampler = function (texture) {
  2235. var wrapS = _GLTFMaterial._GetGLTFTextureWrapMode(texture instanceof BABYLON.Texture ? texture.wrapU : BABYLON.Texture.WRAP_ADDRESSMODE);
  2236. var wrapT = _GLTFMaterial._GetGLTFTextureWrapMode(texture instanceof BABYLON.Texture ? texture.wrapV : BABYLON.Texture.WRAP_ADDRESSMODE);
  2237. if (wrapS === 10497 /* REPEAT */ && wrapT === 10497 /* REPEAT */) { // default wrapping mode in glTF, so omitting
  2238. return {};
  2239. }
  2240. return { wrapS: wrapS, wrapT: wrapT };
  2241. };
  2242. /**
  2243. * Convert a PBRMaterial (Specular/Glossiness) to Metallic Roughness factors
  2244. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  2245. * @param mimeType mime type to use for the textures
  2246. * @param images array of glTF image interfaces
  2247. * @param textures array of glTF texture interfaces
  2248. * @param glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  2249. * @param imageData map of image file name to data
  2250. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2251. * @returns glTF PBR Metallic Roughness factors
  2252. */
  2253. _GLTFMaterial._ConvertSpecGlossFactorsToMetallicRoughness = function (babylonPBRMaterial, mimeType, images, textures, samplers, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  2254. var specGloss = {
  2255. diffuseColor: babylonPBRMaterial.albedoColor || BABYLON.Color3.White(),
  2256. specularColor: babylonPBRMaterial.reflectivityColor || BABYLON.Color3.White(),
  2257. glossiness: babylonPBRMaterial.microSurface || 1,
  2258. };
  2259. var samplerIndex = null;
  2260. var sampler = this._GetGLTFTextureSampler(babylonPBRMaterial.albedoTexture);
  2261. if (sampler.magFilter != null && sampler.minFilter != null && sampler.wrapS != null && sampler.wrapT != null) {
  2262. samplers.push(sampler);
  2263. samplerIndex = samplers.length - 1;
  2264. }
  2265. if (babylonPBRMaterial.reflectivityTexture && !babylonPBRMaterial.useMicroSurfaceFromReflectivityMapAlpha) {
  2266. BABYLON.Tools.Error("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture are currently not supported");
  2267. return null;
  2268. }
  2269. var metallicRoughnessFactors = this._ConvertSpecularGlossinessTexturesToMetallicRoughness(babylonPBRMaterial.albedoTexture, babylonPBRMaterial.reflectivityTexture, specGloss, mimeType);
  2270. if (metallicRoughnessFactors) {
  2271. if (hasTextureCoords) {
  2272. if (metallicRoughnessFactors.baseColorTextureBase64) {
  2273. var glTFBaseColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.baseColorTextureBase64, "bjsBaseColorTexture_" + (textures.length) + ".png", mimeType, images, textures, babylonPBRMaterial.albedoTexture ? babylonPBRMaterial.albedoTexture.coordinatesIndex : null, samplerIndex, imageData);
  2274. if (glTFBaseColorTexture != null) {
  2275. glTFPbrMetallicRoughness.baseColorTexture = glTFBaseColorTexture;
  2276. }
  2277. }
  2278. if (metallicRoughnessFactors.metallicRoughnessTextureBase64) {
  2279. var glTFMRColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.metallicRoughnessTextureBase64, "bjsMetallicRoughnessTexture_" + (textures.length) + ".png", mimeType, images, textures, babylonPBRMaterial.reflectivityTexture ? babylonPBRMaterial.reflectivityTexture.coordinatesIndex : null, samplerIndex, imageData);
  2280. if (glTFMRColorTexture != null) {
  2281. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFMRColorTexture;
  2282. }
  2283. }
  2284. return metallicRoughnessFactors;
  2285. }
  2286. }
  2287. return this._ConvertSpecularGlossinessToMetallicRoughness(specGloss);
  2288. };
  2289. /**
  2290. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  2291. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  2292. * @param mimeType mime type to use for the textures
  2293. * @param images array of glTF image interfaces
  2294. * @param textures array of glTF texture interfaces
  2295. * @param materials array of glTF material interfaces
  2296. * @param imageData map of image file name to data
  2297. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2298. */
  2299. _GLTFMaterial._ConvertPBRMaterialAsync = function (babylonPBRMaterial, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords) {
  2300. var glTFPbrMetallicRoughness = {};
  2301. // let metallicRoughness: Nullable<_IPBRMetallicRoughness>;
  2302. var glTFMaterial = {
  2303. name: babylonPBRMaterial.name
  2304. };
  2305. var useMetallicRoughness = babylonPBRMaterial.isMetallicWorkflow();
  2306. if (useMetallicRoughness) {
  2307. if (babylonPBRMaterial.albedoColor) {
  2308. glTFPbrMetallicRoughness.baseColorFactor = [
  2309. babylonPBRMaterial.albedoColor.r,
  2310. babylonPBRMaterial.albedoColor.g,
  2311. babylonPBRMaterial.albedoColor.b,
  2312. babylonPBRMaterial.alpha
  2313. ];
  2314. }
  2315. return this._ConvertMetalRoughFactorsToMetallicRoughnessAsync(babylonPBRMaterial, mimeType, images, textures, samplers, glTFPbrMetallicRoughness, imageData, hasTextureCoords).then(function (metallicRoughness) {
  2316. return _GLTFMaterial.SetMetallicRoughnessPbrMaterial(metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords);
  2317. });
  2318. }
  2319. else {
  2320. var metallicRoughness = this._ConvertSpecGlossFactorsToMetallicRoughness(babylonPBRMaterial, mimeType, images, textures, samplers, glTFPbrMetallicRoughness, imageData, hasTextureCoords);
  2321. return _GLTFMaterial.SetMetallicRoughnessPbrMaterial(metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords);
  2322. }
  2323. };
  2324. _GLTFMaterial.SetMetallicRoughnessPbrMaterial = function (metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, images, textures, samplers, materials, imageData, hasTextureCoords) {
  2325. var promises = [];
  2326. if (metallicRoughness) {
  2327. var alphaMode = null;
  2328. var useAlpha = false;
  2329. if (babylonPBRMaterial.transparencyMode != null) {
  2330. alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMaterial);
  2331. if (alphaMode) {
  2332. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  2333. useAlpha = true;
  2334. glTFMaterial.alphaMode = alphaMode;
  2335. if (alphaMode === "MASK" /* MASK */) {
  2336. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  2337. }
  2338. }
  2339. }
  2340. }
  2341. if (!(this.FuzzyEquals(metallicRoughness.baseColor, BABYLON.Color3.White(), this._epsilon) && babylonPBRMaterial.alpha >= this._epsilon)) {
  2342. glTFPbrMetallicRoughness.baseColorFactor = [
  2343. metallicRoughness.baseColor.r,
  2344. metallicRoughness.baseColor.g,
  2345. metallicRoughness.baseColor.b,
  2346. babylonPBRMaterial.alpha
  2347. ];
  2348. }
  2349. if (metallicRoughness.metallic != null && metallicRoughness.metallic !== 1) {
  2350. glTFPbrMetallicRoughness.metallicFactor = metallicRoughness.metallic;
  2351. }
  2352. if (metallicRoughness.roughness != null && metallicRoughness.roughness !== 1) {
  2353. glTFPbrMetallicRoughness.roughnessFactor = metallicRoughness.roughness;
  2354. }
  2355. if (babylonPBRMaterial.backFaceCulling != null && !babylonPBRMaterial.backFaceCulling) {
  2356. if (!babylonPBRMaterial.twoSidedLighting) {
  2357. BABYLON.Tools.Warn(babylonPBRMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  2358. }
  2359. glTFMaterial.doubleSided = true;
  2360. }
  2361. if (hasTextureCoords) {
  2362. if (babylonPBRMaterial.bumpTexture) {
  2363. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMaterial.bumpTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  2364. if (glTFTexture) {
  2365. glTFMaterial.normalTexture = glTFTexture;
  2366. if (babylonPBRMaterial.bumpTexture.level !== 1) {
  2367. glTFMaterial.normalTexture.scale = babylonPBRMaterial.bumpTexture.level;
  2368. }
  2369. }
  2370. });
  2371. promises.push(promise);
  2372. }
  2373. if (babylonPBRMaterial.ambientTexture) {
  2374. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMaterial.ambientTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  2375. if (glTFTexture) {
  2376. var occlusionTexture = {
  2377. index: glTFTexture.index
  2378. };
  2379. glTFMaterial.occlusionTexture = occlusionTexture;
  2380. if (babylonPBRMaterial.ambientTextureStrength) {
  2381. occlusionTexture.strength = babylonPBRMaterial.ambientTextureStrength;
  2382. }
  2383. }
  2384. });
  2385. promises.push(promise);
  2386. }
  2387. if (babylonPBRMaterial.emissiveTexture) {
  2388. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMaterial.emissiveTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  2389. if (glTFTexture) {
  2390. glTFMaterial.emissiveTexture = glTFTexture;
  2391. }
  2392. });
  2393. promises.push(promise);
  2394. }
  2395. }
  2396. if (!this.FuzzyEquals(babylonPBRMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  2397. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  2398. }
  2399. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  2400. materials.push(glTFMaterial);
  2401. }
  2402. return Promise.all(promises).then(function (result) { });
  2403. };
  2404. _GLTFMaterial.GetPixelsFromTexture = function (babylonTexture) {
  2405. var pixels = babylonTexture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT ? babylonTexture.readPixels() : babylonTexture.readPixels();
  2406. return pixels;
  2407. };
  2408. /**
  2409. * Extracts a texture from a Babylon texture into file data and glTF data
  2410. * @param babylonTexture Babylon texture to extract
  2411. * @param mimeType Mime Type of the babylonTexture
  2412. * @param images Array of glTF images
  2413. * @param textures Array of glTF textures
  2414. * @param imageData map of image file name and data
  2415. * @return glTF texture info, or null if the texture format is not supported
  2416. */
  2417. _GLTFMaterial._ExportTextureAsync = function (babylonTexture, mimeType, images, textures, samplers, imageData, useAlpha) {
  2418. var _this = this;
  2419. var sampler = _GLTFMaterial._GetGLTFTextureSampler(babylonTexture);
  2420. var samplerIndex = null;
  2421. // if a pre-existing sampler with identical parameters exists, then reuse the previous sampler
  2422. var foundSamplerIndex = null;
  2423. for (var i = 0; i < samplers.length; ++i) {
  2424. var s = samplers[i];
  2425. if (s.minFilter === sampler.minFilter && s.magFilter === sampler.magFilter &&
  2426. s.wrapS === sampler.wrapS && s.wrapT === sampler.wrapT) {
  2427. foundSamplerIndex = i;
  2428. break;
  2429. }
  2430. }
  2431. if (foundSamplerIndex == null) {
  2432. samplers.push(sampler);
  2433. samplerIndex = samplers.length - 1;
  2434. }
  2435. else {
  2436. samplerIndex = foundSamplerIndex;
  2437. }
  2438. var textureName = "texture_" + (textures.length - 1).toString();
  2439. var textureData = babylonTexture.getInternalTexture();
  2440. if (textureData != null) {
  2441. textureName = textureData.url || textureName;
  2442. }
  2443. textureName = BABYLON.Tools.GetFilename(textureName);
  2444. var baseFile = textureName.split('.')[0];
  2445. var extension = "";
  2446. if (mimeType === "image/jpeg" /* JPEG */) {
  2447. extension = ".jpg";
  2448. }
  2449. else if (mimeType === "image/png" /* PNG */) {
  2450. extension = ".png";
  2451. }
  2452. else {
  2453. return Promise.reject("Unsupported mime type " + mimeType);
  2454. }
  2455. textureName = baseFile + extension;
  2456. return this._SetAlphaToOneAsync(babylonTexture, useAlpha).then(function (texture) {
  2457. var pixels = _GLTFMaterial.GetPixelsFromTexture(texture);
  2458. var size = babylonTexture.getSize();
  2459. var base64Data = _this._CreateBase64FromCanvas(pixels, size.width, size.height, mimeType);
  2460. var textureInfo = _this._GetTextureInfoFromBase64(base64Data, textureName, mimeType, images, textures, babylonTexture.coordinatesIndex, samplerIndex, imageData);
  2461. return textureInfo;
  2462. });
  2463. };
  2464. /**
  2465. * Builds a texture from base64 string
  2466. * @param base64Texture base64 texture string
  2467. * @param textureName Name to use for the texture
  2468. * @param mimeType image mime type for the texture
  2469. * @param images array of images
  2470. * @param textures array of textures
  2471. * @param imageData map of image data
  2472. * @returns glTF texture info, or null if the texture format is not supported
  2473. */
  2474. _GLTFMaterial._GetTextureInfoFromBase64 = function (base64Texture, textureName, mimeType, images, textures, texCoordIndex, samplerIndex, imageData) {
  2475. var textureInfo = null;
  2476. var glTFTexture = {
  2477. source: images.length,
  2478. name: textureName
  2479. };
  2480. if (samplerIndex != null) {
  2481. glTFTexture.sampler = samplerIndex;
  2482. }
  2483. var binStr = atob(base64Texture.split(',')[1]);
  2484. var arrBuff = new ArrayBuffer(binStr.length);
  2485. var arr = new Uint8Array(arrBuff);
  2486. for (var i = 0, length_1 = binStr.length; i < length_1; ++i) {
  2487. arr[i] = binStr.charCodeAt(i);
  2488. }
  2489. var imageValues = { data: arr, mimeType: mimeType };
  2490. imageData[textureName] = imageValues;
  2491. if (mimeType === "image/jpeg" /* JPEG */ || mimeType === "image/png" /* PNG */) {
  2492. var glTFImage = {
  2493. uri: textureName
  2494. };
  2495. var foundIndex = null;
  2496. for (var i = 0; i < images.length; ++i) {
  2497. if (images[i].uri === textureName) {
  2498. foundIndex = i;
  2499. break;
  2500. }
  2501. }
  2502. if (foundIndex == null) {
  2503. images.push(glTFImage);
  2504. glTFTexture.source = images.length - 1;
  2505. }
  2506. else {
  2507. glTFTexture.source = foundIndex;
  2508. }
  2509. textures.push(glTFTexture);
  2510. textureInfo = {
  2511. index: textures.length - 1
  2512. };
  2513. if (texCoordIndex != null) {
  2514. textureInfo.texCoord = texCoordIndex;
  2515. }
  2516. }
  2517. return textureInfo;
  2518. };
  2519. /**
  2520. * Represents the dielectric specular values for R, G and B
  2521. */
  2522. _GLTFMaterial._dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  2523. /**
  2524. * Allows the maximum specular power to be defined for material calculations
  2525. */
  2526. _GLTFMaterial._maxSpecularPower = 1024;
  2527. /**
  2528. * Numeric tolerance value
  2529. */
  2530. _GLTFMaterial._epsilon = 1e-6;
  2531. return _GLTFMaterial;
  2532. }());
  2533. GLTF2._GLTFMaterial = _GLTFMaterial;
  2534. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2535. })(BABYLON || (BABYLON = {}));
  2536. //# sourceMappingURL=babylon.glTFMaterial.js.map
  2537. var BABYLON;
  2538. (function (BABYLON) {
  2539. var GLTF2;
  2540. (function (GLTF2) {
  2541. /**
  2542. * @hidden
  2543. * Enum for handling in tangent and out tangent.
  2544. */
  2545. var _TangentType;
  2546. (function (_TangentType) {
  2547. /**
  2548. * Specifies that input tangents are used.
  2549. */
  2550. _TangentType[_TangentType["INTANGENT"] = 0] = "INTANGENT";
  2551. /**
  2552. * Specifies that output tangents are used.
  2553. */
  2554. _TangentType[_TangentType["OUTTANGENT"] = 1] = "OUTTANGENT";
  2555. })(_TangentType || (_TangentType = {}));
  2556. /**
  2557. * @hidden
  2558. * Utility class for generating glTF animation data from BabylonJS.
  2559. */
  2560. var _GLTFAnimation = /** @class */ (function () {
  2561. function _GLTFAnimation() {
  2562. }
  2563. /**
  2564. * @ignore
  2565. *
  2566. * Creates glTF channel animation from BabylonJS animation.
  2567. * @param babylonTransformNode - BabylonJS mesh.
  2568. * @param animation - animation.
  2569. * @param animationChannelTargetPath - The target animation channel.
  2570. * @param convertToRightHandedSystem - Specifies if the values should be converted to right-handed.
  2571. * @param useQuaternion - Specifies if quaternions are used.
  2572. * @returns nullable IAnimationData
  2573. */
  2574. _GLTFAnimation._CreateNodeAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  2575. var inputs = [];
  2576. var outputs = [];
  2577. var keyFrames = animation.getKeys();
  2578. var minMaxKeyFrames = _GLTFAnimation.calculateMinMaxKeyFrames(keyFrames);
  2579. var interpolationOrBake = _GLTFAnimation._DeduceInterpolation(keyFrames, animationChannelTargetPath, useQuaternion);
  2580. var frameDelta = minMaxKeyFrames.max - minMaxKeyFrames.min;
  2581. var interpolation = interpolationOrBake.interpolationType;
  2582. var shouldBakeAnimation = interpolationOrBake.shouldBakeAnimation;
  2583. if (shouldBakeAnimation) {
  2584. _GLTFAnimation._CreateBakedAnimation(babylonTransformNode, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  2585. }
  2586. else {
  2587. if (interpolation === "LINEAR" /* LINEAR */ || interpolation === "STEP" /* STEP */) {
  2588. _GLTFAnimation._CreateLinearOrStepAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2589. }
  2590. else if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  2591. _GLTFAnimation._CreateCubicSplineAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2592. }
  2593. else {
  2594. _GLTFAnimation._CreateBakedAnimation(babylonTransformNode, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  2595. }
  2596. }
  2597. if (inputs.length && outputs.length) {
  2598. var result = {
  2599. inputs: inputs,
  2600. outputs: outputs,
  2601. samplerInterpolation: interpolation,
  2602. inputsMin: shouldBakeAnimation ? minMaxKeyFrames.min : BABYLON.Tools.FloatRound(minMaxKeyFrames.min / animation.framePerSecond),
  2603. inputsMax: shouldBakeAnimation ? minMaxKeyFrames.max : BABYLON.Tools.FloatRound(minMaxKeyFrames.max / animation.framePerSecond)
  2604. };
  2605. return result;
  2606. }
  2607. return null;
  2608. };
  2609. _GLTFAnimation._DeduceAnimationInfo = function (animation) {
  2610. var animationChannelTargetPath = null;
  2611. var dataAccessorType = "VEC3" /* VEC3 */;
  2612. var useQuaternion = false;
  2613. var property = animation.targetProperty.split('.');
  2614. switch (property[0]) {
  2615. case 'scaling': {
  2616. animationChannelTargetPath = "scale" /* SCALE */;
  2617. break;
  2618. }
  2619. case 'position': {
  2620. animationChannelTargetPath = "translation" /* TRANSLATION */;
  2621. break;
  2622. }
  2623. case 'rotation': {
  2624. dataAccessorType = "VEC4" /* VEC4 */;
  2625. animationChannelTargetPath = "rotation" /* ROTATION */;
  2626. break;
  2627. }
  2628. case 'rotationQuaternion': {
  2629. dataAccessorType = "VEC4" /* VEC4 */;
  2630. useQuaternion = true;
  2631. animationChannelTargetPath = "rotation" /* ROTATION */;
  2632. break;
  2633. }
  2634. default: {
  2635. BABYLON.Tools.Error("Unsupported animatable property " + property[0]);
  2636. }
  2637. }
  2638. if (animationChannelTargetPath) {
  2639. return { animationChannelTargetPath: animationChannelTargetPath, dataAccessorType: dataAccessorType, useQuaternion: useQuaternion };
  2640. }
  2641. else {
  2642. BABYLON.Tools.Error('animation channel target path and data accessor type could be deduced');
  2643. }
  2644. return null;
  2645. };
  2646. /**
  2647. * @ignore
  2648. * Create node animations from the transform node animations
  2649. * @param babylonTransformNode
  2650. * @param runtimeGLTFAnimation
  2651. * @param idleGLTFAnimations
  2652. * @param nodeMap
  2653. * @param nodes
  2654. * @param binaryWriter
  2655. * @param bufferViews
  2656. * @param accessors
  2657. * @param convertToRightHandedSystem
  2658. */
  2659. _GLTFAnimation._CreateNodeAnimationFromTransformNodeAnimations = function (babylonTransformNode, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  2660. var glTFAnimation;
  2661. if (babylonTransformNode.animations) {
  2662. for (var _i = 0, _a = babylonTransformNode.animations; _i < _a.length; _i++) {
  2663. var animation = _a[_i];
  2664. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(animation);
  2665. if (animationInfo) {
  2666. glTFAnimation = {
  2667. name: animation.name,
  2668. samplers: [],
  2669. channels: []
  2670. };
  2671. _GLTFAnimation.AddAnimation("" + animation.name, animation.hasRunningRuntimeAnimations ? runtimeGLTFAnimation : glTFAnimation, babylonTransformNode, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  2672. if (glTFAnimation.samplers.length && glTFAnimation.channels.length) {
  2673. idleGLTFAnimations.push(glTFAnimation);
  2674. }
  2675. }
  2676. }
  2677. ;
  2678. }
  2679. };
  2680. /**
  2681. * @ignore
  2682. * Create node animations from the animation groups
  2683. * @param babylonScene
  2684. * @param glTFAnimations
  2685. * @param nodeMap
  2686. * @param nodes
  2687. * @param binaryWriter
  2688. * @param bufferViews
  2689. * @param accessors
  2690. * @param convertToRightHandedSystem
  2691. */
  2692. _GLTFAnimation._CreateNodeAnimationFromAnimationGroups = function (babylonScene, glTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  2693. var glTFAnimation;
  2694. if (babylonScene.animationGroups) {
  2695. var animationGroups = babylonScene.animationGroups;
  2696. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  2697. var animationGroup = animationGroups_1[_i];
  2698. glTFAnimation = {
  2699. name: animationGroup.name,
  2700. channels: [],
  2701. samplers: []
  2702. };
  2703. for (var _a = 0, _b = animationGroup.targetedAnimations; _a < _b.length; _a++) {
  2704. var targetAnimation = _b[_a];
  2705. var target = targetAnimation.target;
  2706. var animation = targetAnimation.animation;
  2707. if (target instanceof BABYLON.Mesh || target.length === 1 && target[0] instanceof BABYLON.Mesh) { // TODO: Update to support bones
  2708. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(targetAnimation.animation);
  2709. if (animationInfo) {
  2710. var babylonMesh = target instanceof BABYLON.Mesh ? target : target[0];
  2711. _GLTFAnimation.AddAnimation("" + animation.name, glTFAnimation, babylonMesh, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  2712. }
  2713. }
  2714. }
  2715. ;
  2716. if (glTFAnimation.channels.length && glTFAnimation.samplers.length) {
  2717. glTFAnimations.push(glTFAnimation);
  2718. }
  2719. }
  2720. ;
  2721. }
  2722. };
  2723. _GLTFAnimation.AddAnimation = function (name, glTFAnimation, babylonTransformNode, animation, dataAccessorType, animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  2724. var animationData = _GLTFAnimation._CreateNodeAnimation(babylonTransformNode, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate);
  2725. var bufferView;
  2726. var accessor;
  2727. var keyframeAccessorIndex;
  2728. var dataAccessorIndex;
  2729. var outputLength;
  2730. var animationSampler;
  2731. var animationChannel;
  2732. if (animationData) {
  2733. var nodeIndex = nodeMap[babylonTransformNode.uniqueId];
  2734. // Creates buffer view and accessor for key frames.
  2735. var byteLength = animationData.inputs.length * 4;
  2736. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " keyframe data view");
  2737. bufferViews.push(bufferView);
  2738. animationData.inputs.forEach(function (input) {
  2739. binaryWriter.setFloat32(input);
  2740. });
  2741. accessor = GLTF2._GLTFUtilities.CreateAccessor(bufferViews.length - 1, name + " keyframes", "SCALAR" /* SCALAR */, 5126 /* FLOAT */, animationData.inputs.length, null, [animationData.inputsMin], [animationData.inputsMax]);
  2742. accessors.push(accessor);
  2743. keyframeAccessorIndex = accessors.length - 1;
  2744. // create bufferview and accessor for keyed values.
  2745. outputLength = animationData.outputs.length;
  2746. byteLength = dataAccessorType === "VEC3" /* VEC3 */ ? animationData.outputs.length * 12 : animationData.outputs.length * 16;
  2747. // check for in and out tangents
  2748. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " data view");
  2749. bufferViews.push(bufferView);
  2750. animationData.outputs.forEach(function (output) {
  2751. output.forEach(function (entry) {
  2752. binaryWriter.setFloat32(entry);
  2753. });
  2754. });
  2755. accessor = GLTF2._GLTFUtilities.CreateAccessor(bufferViews.length - 1, name + " data", dataAccessorType, 5126 /* FLOAT */, outputLength, null, null, null);
  2756. accessors.push(accessor);
  2757. dataAccessorIndex = accessors.length - 1;
  2758. // create sampler
  2759. animationSampler = {
  2760. interpolation: animationData.samplerInterpolation,
  2761. input: keyframeAccessorIndex,
  2762. output: dataAccessorIndex
  2763. };
  2764. glTFAnimation.samplers.push(animationSampler);
  2765. // create channel
  2766. animationChannel = {
  2767. sampler: glTFAnimation.samplers.length - 1,
  2768. target: {
  2769. node: nodeIndex,
  2770. path: animationChannelTargetPath
  2771. }
  2772. };
  2773. glTFAnimation.channels.push(animationChannel);
  2774. }
  2775. };
  2776. /**
  2777. * Create a baked animation
  2778. * @param babylonTransformNode BabylonJS mesh
  2779. * @param animation BabylonJS animation corresponding to the BabylonJS mesh
  2780. * @param animationChannelTargetPath animation target channel
  2781. * @param minFrame minimum animation frame
  2782. * @param maxFrame maximum animation frame
  2783. * @param fps frames per second of the animation
  2784. * @param inputs input key frames of the animation
  2785. * @param outputs output key frame data of the animation
  2786. * @param convertToRightHandedSystem converts the values to right-handed
  2787. * @param useQuaternion specifies if quaternions should be used
  2788. */
  2789. _GLTFAnimation._CreateBakedAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, minFrame, maxFrame, fps, sampleRate, inputs, outputs, minMaxFrames, convertToRightHandedSystem, useQuaternion) {
  2790. var value;
  2791. var quaternionCache = BABYLON.Quaternion.Identity();
  2792. var previousTime = null;
  2793. var time;
  2794. var maxUsedFrame = null;
  2795. var currKeyFrame = null;
  2796. var nextKeyFrame = null;
  2797. var prevKeyFrame = null;
  2798. var endFrame = null;
  2799. minMaxFrames.min = BABYLON.Tools.FloatRound(minFrame / fps);
  2800. var keyFrames = animation.getKeys();
  2801. for (var i = 0, length_1 = keyFrames.length; i < length_1; ++i) {
  2802. endFrame = null;
  2803. currKeyFrame = keyFrames[i];
  2804. if (i + 1 < length_1) {
  2805. nextKeyFrame = keyFrames[i + 1];
  2806. if (currKeyFrame.value.equals(nextKeyFrame.value)) {
  2807. if (i === 0) { // set the first frame to itself
  2808. endFrame = currKeyFrame.frame;
  2809. }
  2810. else {
  2811. continue;
  2812. }
  2813. }
  2814. else {
  2815. endFrame = nextKeyFrame.frame;
  2816. }
  2817. }
  2818. else {
  2819. // at the last key frame
  2820. prevKeyFrame = keyFrames[i - 1];
  2821. if (currKeyFrame.value.equals(prevKeyFrame.value)) {
  2822. continue;
  2823. }
  2824. else {
  2825. endFrame = maxFrame;
  2826. }
  2827. }
  2828. if (endFrame) {
  2829. for (var f = currKeyFrame.frame; f <= endFrame; f += sampleRate) {
  2830. time = BABYLON.Tools.FloatRound(f / fps);
  2831. if (time === previousTime) {
  2832. continue;
  2833. }
  2834. previousTime = time;
  2835. maxUsedFrame = time;
  2836. value = animation._interpolate(f, 0, undefined, animation.loopMode);
  2837. _GLTFAnimation._SetInterpolatedValue(babylonTransformNode, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2838. }
  2839. }
  2840. }
  2841. if (maxUsedFrame) {
  2842. minMaxFrames.max = maxUsedFrame;
  2843. }
  2844. };
  2845. _GLTFAnimation._ConvertFactorToVector3OrQuaternion = function (factor, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  2846. var property;
  2847. var componentName;
  2848. var value = null;
  2849. var basePositionRotationOrScale = _GLTFAnimation._GetBasePositionRotationOrScale(babylonTransformNode, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  2850. if (animationType === BABYLON.Animation.ANIMATIONTYPE_FLOAT) { // handles single component x, y, z or w component animation by using a base property and animating over a component.
  2851. property = animation.targetProperty.split('.');
  2852. componentName = property ? property[1] : ''; // x, y, or z component
  2853. value = useQuaternion ? BABYLON.Quaternion.FromArray(basePositionRotationOrScale).normalize() : BABYLON.Vector3.FromArray(basePositionRotationOrScale);
  2854. switch (componentName) {
  2855. case 'x': {
  2856. value[componentName] = (convertToRightHandedSystem && useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2857. break;
  2858. }
  2859. case 'y': {
  2860. value[componentName] = (convertToRightHandedSystem && useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2861. break;
  2862. }
  2863. case 'z': {
  2864. value[componentName] = (convertToRightHandedSystem && !useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2865. break;
  2866. }
  2867. case 'w': {
  2868. value.w = factor;
  2869. break;
  2870. }
  2871. default: {
  2872. BABYLON.Tools.Error("glTFAnimation: Unsupported component type \"" + componentName + "\" for scale animation!");
  2873. }
  2874. }
  2875. }
  2876. return value;
  2877. };
  2878. _GLTFAnimation._SetInterpolatedValue = function (babylonTransformNode, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2879. var animationType = animation.dataType;
  2880. var cacheValue;
  2881. inputs.push(time);
  2882. if (typeof value === "number") {
  2883. value = this._ConvertFactorToVector3OrQuaternion(value, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  2884. }
  2885. if (value) {
  2886. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2887. if (useQuaternion) {
  2888. quaternionCache = value;
  2889. }
  2890. else {
  2891. cacheValue = value;
  2892. BABYLON.Quaternion.RotationYawPitchRollToRef(cacheValue.y, cacheValue.x, cacheValue.z, quaternionCache);
  2893. }
  2894. if (convertToRightHandedSystem) {
  2895. GLTF2._GLTFUtilities.GetRightHandedQuaternionFromRef(quaternionCache);
  2896. if (!babylonTransformNode.parent) {
  2897. quaternionCache = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(quaternionCache);
  2898. }
  2899. }
  2900. outputs.push(quaternionCache.asArray());
  2901. }
  2902. else {
  2903. cacheValue = value;
  2904. if (convertToRightHandedSystem && (animationChannelTargetPath !== "scale" /* SCALE */)) {
  2905. GLTF2._GLTFUtilities.GetRightHandedPositionVector3FromRef(cacheValue);
  2906. if (!babylonTransformNode.parent) {
  2907. cacheValue.x *= -1;
  2908. cacheValue.z *= -1;
  2909. }
  2910. }
  2911. outputs.push(cacheValue.asArray());
  2912. }
  2913. }
  2914. };
  2915. /**
  2916. * Creates linear animation from the animation key frames
  2917. * @param babylonTransformNode BabylonJS mesh
  2918. * @param animation BabylonJS animation
  2919. * @param animationChannelTargetPath The target animation channel
  2920. * @param frameDelta The difference between the last and first frame of the animation
  2921. * @param inputs Array to store the key frame times
  2922. * @param outputs Array to store the key frame data
  2923. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  2924. * @param useQuaternion Specifies if quaternions are used in the animation
  2925. */
  2926. _GLTFAnimation._CreateLinearOrStepAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2927. for (var _i = 0, _a = animation.getKeys(); _i < _a.length; _i++) {
  2928. var keyFrame = _a[_i];
  2929. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  2930. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion);
  2931. }
  2932. ;
  2933. };
  2934. /**
  2935. * Creates cubic spline animation from the animation key frames
  2936. * @param babylonTransformNode BabylonJS mesh
  2937. * @param animation BabylonJS animation
  2938. * @param animationChannelTargetPath The target animation channel
  2939. * @param frameDelta The difference between the last and first frame of the animation
  2940. * @param inputs Array to store the key frame times
  2941. * @param outputs Array to store the key frame data
  2942. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  2943. * @param useQuaternion Specifies if quaternions are used in the animation
  2944. */
  2945. _GLTFAnimation._CreateCubicSplineAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2946. animation.getKeys().forEach(function (keyFrame) {
  2947. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  2948. _GLTFAnimation.AddSplineTangent(babylonTransformNode, _TangentType.INTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  2949. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion);
  2950. _GLTFAnimation.AddSplineTangent(babylonTransformNode, _TangentType.OUTTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  2951. });
  2952. };
  2953. _GLTFAnimation._GetBasePositionRotationOrScale = function (babylonTransformNode, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  2954. var basePositionRotationOrScale;
  2955. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2956. if (useQuaternion) {
  2957. if (babylonTransformNode.rotationQuaternion) {
  2958. basePositionRotationOrScale = babylonTransformNode.rotationQuaternion.asArray();
  2959. if (convertToRightHandedSystem) {
  2960. GLTF2._GLTFUtilities.GetRightHandedQuaternionArrayFromRef(basePositionRotationOrScale);
  2961. if (!babylonTransformNode.parent) {
  2962. basePositionRotationOrScale = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(basePositionRotationOrScale)).asArray();
  2963. }
  2964. }
  2965. }
  2966. else {
  2967. basePositionRotationOrScale = BABYLON.Quaternion.Identity().asArray();
  2968. }
  2969. }
  2970. else {
  2971. basePositionRotationOrScale = babylonTransformNode.rotation.asArray();
  2972. GLTF2._GLTFUtilities.GetRightHandedNormalArray3FromRef(basePositionRotationOrScale);
  2973. }
  2974. }
  2975. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  2976. basePositionRotationOrScale = babylonTransformNode.position.asArray();
  2977. if (convertToRightHandedSystem) {
  2978. GLTF2._GLTFUtilities.GetRightHandedPositionArray3FromRef(basePositionRotationOrScale);
  2979. }
  2980. }
  2981. else { // scale
  2982. basePositionRotationOrScale = babylonTransformNode.scaling.asArray();
  2983. }
  2984. return basePositionRotationOrScale;
  2985. };
  2986. /**
  2987. * Adds a key frame value
  2988. * @param keyFrame
  2989. * @param animation
  2990. * @param outputs
  2991. * @param animationChannelTargetPath
  2992. * @param basePositionRotationOrScale
  2993. * @param convertToRightHandedSystem
  2994. * @param useQuaternion
  2995. */
  2996. _GLTFAnimation._AddKeyframeValue = function (keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion) {
  2997. var value;
  2998. var newPositionRotationOrScale;
  2999. var animationType = animation.dataType;
  3000. if (animationType === BABYLON.Animation.ANIMATIONTYPE_VECTOR3) {
  3001. value = keyFrame.value.asArray();
  3002. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  3003. var array = BABYLON.Vector3.FromArray(value);
  3004. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(array.y, array.x, array.z);
  3005. if (convertToRightHandedSystem) {
  3006. GLTF2._GLTFUtilities.GetRightHandedQuaternionFromRef(rotationQuaternion);
  3007. if (!babylonTransformNode.parent) {
  3008. rotationQuaternion = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(rotationQuaternion);
  3009. }
  3010. }
  3011. value = rotationQuaternion.asArray();
  3012. }
  3013. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  3014. if (convertToRightHandedSystem) {
  3015. GLTF2._GLTFUtilities.GetRightHandedNormalArray3FromRef(value);
  3016. if (!babylonTransformNode.parent) {
  3017. value[0] *= -1;
  3018. value[2] *= -1;
  3019. }
  3020. }
  3021. }
  3022. outputs.push(value); // scale vector.
  3023. }
  3024. else if (animationType === BABYLON.Animation.ANIMATIONTYPE_FLOAT) { // handles single component x, y, z or w component animation by using a base property and animating over a component.
  3025. newPositionRotationOrScale = this._ConvertFactorToVector3OrQuaternion(keyFrame.value, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  3026. if (newPositionRotationOrScale) {
  3027. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  3028. var posRotScale = useQuaternion ? newPositionRotationOrScale : BABYLON.Quaternion.RotationYawPitchRoll(newPositionRotationOrScale.y, newPositionRotationOrScale.x, newPositionRotationOrScale.z).normalize();
  3029. if (convertToRightHandedSystem) {
  3030. GLTF2._GLTFUtilities.GetRightHandedQuaternionFromRef(posRotScale);
  3031. if (!babylonTransformNode.parent) {
  3032. posRotScale = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(posRotScale);
  3033. }
  3034. }
  3035. outputs.push(posRotScale.asArray());
  3036. }
  3037. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  3038. if (convertToRightHandedSystem) {
  3039. GLTF2._GLTFUtilities.GetRightHandedNormalVector3FromRef(newPositionRotationOrScale);
  3040. if (!babylonTransformNode.parent) {
  3041. newPositionRotationOrScale.x *= -1;
  3042. newPositionRotationOrScale.z *= -1;
  3043. }
  3044. }
  3045. }
  3046. outputs.push(newPositionRotationOrScale.asArray());
  3047. }
  3048. }
  3049. else if (animationType === BABYLON.Animation.ANIMATIONTYPE_QUATERNION) {
  3050. value = keyFrame.value.normalize().asArray();
  3051. if (convertToRightHandedSystem) {
  3052. GLTF2._GLTFUtilities.GetRightHandedQuaternionArrayFromRef(value);
  3053. if (!babylonTransformNode.parent) {
  3054. value = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(value)).asArray();
  3055. }
  3056. }
  3057. outputs.push(value);
  3058. }
  3059. else {
  3060. BABYLON.Tools.Error('glTFAnimation: Unsupported key frame values for animation!');
  3061. }
  3062. };
  3063. /**
  3064. * Determine the interpolation based on the key frames
  3065. * @param keyFrames
  3066. * @param animationChannelTargetPath
  3067. * @param useQuaternion
  3068. */
  3069. _GLTFAnimation._DeduceInterpolation = function (keyFrames, animationChannelTargetPath, useQuaternion) {
  3070. var interpolationType;
  3071. var shouldBakeAnimation = false;
  3072. var key;
  3073. if (animationChannelTargetPath === "rotation" /* ROTATION */ && !useQuaternion) {
  3074. return { interpolationType: "LINEAR" /* LINEAR */, shouldBakeAnimation: true };
  3075. }
  3076. for (var i = 0, length_2 = keyFrames.length; i < length_2; ++i) {
  3077. key = keyFrames[i];
  3078. if (key.inTangent || key.outTangent) {
  3079. if (interpolationType) {
  3080. if (interpolationType !== "CUBICSPLINE" /* CUBICSPLINE */) {
  3081. interpolationType = "LINEAR" /* LINEAR */;
  3082. shouldBakeAnimation = true;
  3083. break;
  3084. }
  3085. }
  3086. else {
  3087. interpolationType = "CUBICSPLINE" /* CUBICSPLINE */;
  3088. }
  3089. }
  3090. else {
  3091. if (interpolationType) {
  3092. if (interpolationType === "CUBICSPLINE" /* CUBICSPLINE */ ||
  3093. (key.interpolation && (key.interpolation === BABYLON.AnimationKeyInterpolation.STEP) && interpolationType !== "STEP" /* STEP */)) {
  3094. interpolationType = "LINEAR" /* LINEAR */;
  3095. shouldBakeAnimation = true;
  3096. break;
  3097. }
  3098. }
  3099. else {
  3100. if (key.interpolation && (key.interpolation === BABYLON.AnimationKeyInterpolation.STEP)) {
  3101. interpolationType = "STEP" /* STEP */;
  3102. }
  3103. else {
  3104. interpolationType = "LINEAR" /* LINEAR */;
  3105. }
  3106. }
  3107. }
  3108. }
  3109. if (!interpolationType) {
  3110. interpolationType = "LINEAR" /* LINEAR */;
  3111. }
  3112. return { interpolationType: interpolationType, shouldBakeAnimation: shouldBakeAnimation };
  3113. };
  3114. /**
  3115. * Adds an input tangent or output tangent to the output data
  3116. * If an input tangent or output tangent is missing, it uses the zero vector or zero quaternion
  3117. * @param tangentType Specifies which type of tangent to handle (inTangent or outTangent)
  3118. * @param outputs The animation data by keyframe
  3119. * @param animationChannelTargetPath The target animation channel
  3120. * @param interpolation The interpolation type
  3121. * @param keyFrame The key frame with the animation data
  3122. * @param frameDelta Time difference between two frames used to scale the tangent by the frame delta
  3123. * @param useQuaternion Specifies if quaternions are used
  3124. * @param convertToRightHandedSystem Specifies if the values should be converted to right-handed
  3125. */
  3126. _GLTFAnimation.AddSplineTangent = function (babylonTransformNode, tangentType, outputs, animationChannelTargetPath, interpolation, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem) {
  3127. var tangent;
  3128. var tangentValue = tangentType === _TangentType.INTANGENT ? keyFrame.inTangent : keyFrame.outTangent;
  3129. if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  3130. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  3131. if (tangentValue) {
  3132. if (useQuaternion) {
  3133. tangent = tangentValue.scale(frameDelta).asArray();
  3134. }
  3135. else {
  3136. var array = tangentValue.scale(frameDelta);
  3137. tangent = BABYLON.Quaternion.RotationYawPitchRoll(array.y, array.x, array.z).asArray();
  3138. }
  3139. if (convertToRightHandedSystem) {
  3140. GLTF2._GLTFUtilities.GetRightHandedQuaternionArrayFromRef(tangent);
  3141. if (!babylonTransformNode.parent) {
  3142. tangent = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(tangent)).asArray();
  3143. }
  3144. }
  3145. }
  3146. else {
  3147. tangent = [0, 0, 0, 0];
  3148. }
  3149. }
  3150. else {
  3151. if (tangentValue) {
  3152. tangent = tangentValue.scale(frameDelta).asArray();
  3153. if (convertToRightHandedSystem) {
  3154. if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  3155. GLTF2._GLTFUtilities.GetRightHandedPositionArray3FromRef(tangent);
  3156. if (!babylonTransformNode.parent) {
  3157. tangent[0] *= -1; // x
  3158. tangent[2] *= -1; // z
  3159. }
  3160. }
  3161. }
  3162. }
  3163. else {
  3164. tangent = [0, 0, 0];
  3165. }
  3166. }
  3167. outputs.push(tangent);
  3168. }
  3169. };
  3170. /**
  3171. * Get the minimum and maximum key frames' frame values
  3172. * @param keyFrames animation key frames
  3173. * @returns the minimum and maximum key frame value
  3174. */
  3175. _GLTFAnimation.calculateMinMaxKeyFrames = function (keyFrames) {
  3176. var min = Infinity;
  3177. var max = -Infinity;
  3178. keyFrames.forEach(function (keyFrame) {
  3179. min = Math.min(min, keyFrame.frame);
  3180. max = Math.max(max, keyFrame.frame);
  3181. });
  3182. return { min: min, max: max };
  3183. };
  3184. return _GLTFAnimation;
  3185. }());
  3186. GLTF2._GLTFAnimation = _GLTFAnimation;
  3187. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3188. })(BABYLON || (BABYLON = {}));
  3189. //# sourceMappingURL=babylon.glTFAnimation.js.map
  3190. var BABYLON;
  3191. (function (BABYLON) {
  3192. var GLTF2;
  3193. (function (GLTF2) {
  3194. /**
  3195. * @hidden
  3196. */
  3197. var _GLTFUtilities = /** @class */ (function () {
  3198. function _GLTFUtilities() {
  3199. }
  3200. /**
  3201. * Creates a buffer view based on the supplied arguments
  3202. * @param bufferIndex index value of the specified buffer
  3203. * @param byteOffset byte offset value
  3204. * @param byteLength byte length of the bufferView
  3205. * @param byteStride byte distance between conequential elements
  3206. * @param name name of the buffer view
  3207. * @returns bufferView for glTF
  3208. */
  3209. _GLTFUtilities.CreateBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  3210. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  3211. if (byteOffset) {
  3212. bufferview.byteOffset = byteOffset;
  3213. }
  3214. if (name) {
  3215. bufferview.name = name;
  3216. }
  3217. if (byteStride) {
  3218. bufferview.byteStride = byteStride;
  3219. }
  3220. return bufferview;
  3221. };
  3222. /**
  3223. * Creates an accessor based on the supplied arguments
  3224. * @param bufferviewIndex The index of the bufferview referenced by this accessor
  3225. * @param name The name of the accessor
  3226. * @param type The type of the accessor
  3227. * @param componentType The datatype of components in the attribute
  3228. * @param count The number of attributes referenced by this accessor
  3229. * @param byteOffset The offset relative to the start of the bufferView in bytes
  3230. * @param min Minimum value of each component in this attribute
  3231. * @param max Maximum value of each component in this attribute
  3232. * @returns accessor for glTF
  3233. */
  3234. _GLTFUtilities.CreateAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  3235. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  3236. if (min != null) {
  3237. accessor.min = min;
  3238. }
  3239. if (max != null) {
  3240. accessor.max = max;
  3241. }
  3242. if (byteOffset != null) {
  3243. accessor.byteOffset = byteOffset;
  3244. }
  3245. return accessor;
  3246. };
  3247. /**
  3248. * Calculates the minimum and maximum values of an array of position floats
  3249. * @param positions Positions array of a mesh
  3250. * @param vertexStart Starting vertex offset to calculate min and max values
  3251. * @param vertexCount Number of vertices to check for min and max values
  3252. * @returns min number array and max number array
  3253. */
  3254. _GLTFUtilities.CalculateMinMaxPositions = function (positions, vertexStart, vertexCount, convertToRightHandedSystem) {
  3255. var min = [Infinity, Infinity, Infinity];
  3256. var max = [-Infinity, -Infinity, -Infinity];
  3257. var positionStrideSize = 3;
  3258. var indexOffset;
  3259. var position;
  3260. var vector;
  3261. if (vertexCount) {
  3262. for (var i = vertexStart, length_1 = vertexStart + vertexCount; i < length_1; ++i) {
  3263. indexOffset = positionStrideSize * i;
  3264. position = BABYLON.Vector3.FromArray(positions, indexOffset);
  3265. if (convertToRightHandedSystem) {
  3266. _GLTFUtilities.GetRightHandedPositionVector3FromRef(position);
  3267. }
  3268. vector = position.asArray();
  3269. for (var j = 0; j < positionStrideSize; ++j) {
  3270. var num = vector[j];
  3271. if (num < min[j]) {
  3272. min[j] = num;
  3273. }
  3274. if (num > max[j]) {
  3275. max[j] = num;
  3276. }
  3277. ++indexOffset;
  3278. }
  3279. }
  3280. }
  3281. return { min: min, max: max };
  3282. };
  3283. /**
  3284. * Converts a new right-handed Vector3
  3285. * @param vector vector3 array
  3286. * @returns right-handed Vector3
  3287. */
  3288. _GLTFUtilities.GetRightHandedPositionVector3 = function (vector) {
  3289. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  3290. };
  3291. /**
  3292. * Converts a Vector3 to right-handed
  3293. * @param vector Vector3 to convert to right-handed
  3294. */
  3295. _GLTFUtilities.GetRightHandedPositionVector3FromRef = function (vector) {
  3296. vector.z *= -1;
  3297. };
  3298. /**
  3299. * Converts a three element number array to right-handed
  3300. * @param vector number array to convert to right-handed
  3301. */
  3302. _GLTFUtilities.GetRightHandedPositionArray3FromRef = function (vector) {
  3303. vector[2] *= -1;
  3304. };
  3305. /**
  3306. * Converts a new right-handed Vector3
  3307. * @param vector vector3 array
  3308. * @returns right-handed Vector3
  3309. */
  3310. _GLTFUtilities.GetRightHandedNormalVector3 = function (vector) {
  3311. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  3312. };
  3313. /**
  3314. * Converts a Vector3 to right-handed
  3315. * @param vector Vector3 to convert to right-handed
  3316. */
  3317. _GLTFUtilities.GetRightHandedNormalVector3FromRef = function (vector) {
  3318. vector.z *= -1;
  3319. };
  3320. /**
  3321. * Converts a three element number array to right-handed
  3322. * @param vector number array to convert to right-handed
  3323. */
  3324. _GLTFUtilities.GetRightHandedNormalArray3FromRef = function (vector) {
  3325. vector[2] *= -1;
  3326. };
  3327. /**
  3328. * Converts a Vector4 to right-handed
  3329. * @param vector Vector4 to convert to right-handed
  3330. */
  3331. _GLTFUtilities.GetRightHandedVector4FromRef = function (vector) {
  3332. vector.z *= -1;
  3333. vector.w *= -1;
  3334. };
  3335. /**
  3336. * Converts a Vector4 to right-handed
  3337. * @param vector Vector4 to convert to right-handed
  3338. */
  3339. _GLTFUtilities.GetRightHandedArray4FromRef = function (vector) {
  3340. vector[2] *= -1;
  3341. vector[3] *= -1;
  3342. };
  3343. /**
  3344. * Converts a Quaternion to right-handed
  3345. * @param quaternion Source quaternion to convert to right-handed
  3346. */
  3347. _GLTFUtilities.GetRightHandedQuaternionFromRef = function (quaternion) {
  3348. quaternion.x *= -1;
  3349. quaternion.y *= -1;
  3350. };
  3351. /**
  3352. * Converts a Quaternion to right-handed
  3353. * @param quaternion Source quaternion to convert to right-handed
  3354. */
  3355. _GLTFUtilities.GetRightHandedQuaternionArrayFromRef = function (quaternion) {
  3356. quaternion[0] *= -1;
  3357. quaternion[1] *= -1;
  3358. };
  3359. return _GLTFUtilities;
  3360. }());
  3361. GLTF2._GLTFUtilities = _GLTFUtilities;
  3362. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3363. })(BABYLON || (BABYLON = {}));
  3364. //# sourceMappingURL=babylon.glTFUtilities.js.map
  3365. return BABYLON;
  3366. });