babylon.glTF2Serializer.js 184 KB

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