babylonjs.serializers.js 192 KB

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