babylon.glTF2Serializer.js 187 KB

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