babylonjs.serializers.js 196 KB

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