babylon.glTF2Serializer.js 215 KB

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