babylonjs.serializers.js 188 KB

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