babylon.glTF2Serializer.js 215 KB

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