babylon.glTF2Serializer.js 187 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254
  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 instanceof BABYLON.StandardMaterial) {
  1469. var babylonStandardMaterial = babylonMaterial;
  1470. if ((babylonStandardMaterial.alpha !== 1.0) ||
  1471. (babylonStandardMaterial.diffuseTexture != null && babylonStandardMaterial.diffuseTexture.hasAlpha) ||
  1472. (babylonStandardMaterial.opacityTexture != null)) {
  1473. return "BLEND" /* BLEND */;
  1474. }
  1475. else {
  1476. return "OPAQUE" /* OPAQUE */;
  1477. }
  1478. }
  1479. else if (babylonMaterial instanceof BABYLON.PBRMetallicRoughnessMaterial) {
  1480. var babylonPBRMetallicRoughness = babylonMaterial;
  1481. switch (babylonPBRMetallicRoughness.transparencyMode) {
  1482. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1483. return "OPAQUE" /* OPAQUE */;
  1484. }
  1485. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1486. return "BLEND" /* BLEND */;
  1487. }
  1488. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1489. return "MASK" /* MASK */;
  1490. }
  1491. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1492. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1493. return "BLEND" /* BLEND */;
  1494. }
  1495. default: {
  1496. BABYLON.Tools.Error("Unsupported alpha mode " + babylonPBRMetallicRoughness.transparencyMode);
  1497. return null;
  1498. }
  1499. }
  1500. }
  1501. else if (babylonMaterial instanceof BABYLON.PBRMaterial) {
  1502. var babylonPBRMaterial = babylonMaterial;
  1503. switch (babylonPBRMaterial.transparencyMode) {
  1504. case BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE: {
  1505. return "OPAQUE" /* OPAQUE */;
  1506. }
  1507. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND: {
  1508. return "BLEND" /* BLEND */;
  1509. }
  1510. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST: {
  1511. return "MASK" /* MASK */;
  1512. }
  1513. case BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND: {
  1514. BABYLON.Tools.Warn(babylonMaterial.name + ": GLTF Exporter | Alpha test and blend mode not supported in glTF. Alpha blend used instead.");
  1515. return "BLEND" /* BLEND */;
  1516. }
  1517. default: {
  1518. BABYLON.Tools.Error("Unsupported alpha mode " + babylonPBRMaterial.transparencyMode);
  1519. return null;
  1520. }
  1521. }
  1522. }
  1523. else {
  1524. BABYLON.Tools.Error("Unsupported Babylon material type");
  1525. return null;
  1526. }
  1527. };
  1528. /**
  1529. * Converts a Babylon Standard Material to a glTF Material
  1530. * @param babylonStandardMaterial BJS Standard Material
  1531. * @param mimeType mime type to use for the textures
  1532. * @param images array of glTF image interfaces
  1533. * @param textures array of glTF texture interfaces
  1534. * @param materials array of glTF material interfaces
  1535. * @param imageData map of image file name to data
  1536. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1537. */
  1538. _GLTFMaterial._ConvertStandardMaterialAsync = function (babylonStandardMaterial, mimeType, images, textures, samplers, materials, materialMap, imageData, hasTextureCoords) {
  1539. var alphaMode = this._GetAlphaMode(babylonStandardMaterial);
  1540. var useAlpha = alphaMode !== "OPAQUE" /* OPAQUE */ ? true : false;
  1541. var promises = [];
  1542. var glTFPbrMetallicRoughness = _GLTFMaterial._ConvertToGLTFPBRMetallicRoughness(babylonStandardMaterial);
  1543. var glTFMaterial = { name: babylonStandardMaterial.name };
  1544. if (babylonStandardMaterial.backFaceCulling != null && !babylonStandardMaterial.backFaceCulling) {
  1545. if (!babylonStandardMaterial.twoSidedLighting) {
  1546. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  1547. }
  1548. glTFMaterial.doubleSided = true;
  1549. }
  1550. if (hasTextureCoords) {
  1551. if (babylonStandardMaterial.diffuseTexture) {
  1552. var promise = _GLTFMaterial._ExportTextureAsync(babylonStandardMaterial.diffuseTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1553. if (glTFTexture) {
  1554. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1555. }
  1556. });
  1557. promises.push(promise);
  1558. }
  1559. if (babylonStandardMaterial.bumpTexture) {
  1560. var promise = _GLTFMaterial._ExportTextureAsync(babylonStandardMaterial.bumpTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1561. if (glTFTexture) {
  1562. glTFMaterial.normalTexture = glTFTexture;
  1563. if (babylonStandardMaterial.bumpTexture != null && babylonStandardMaterial.bumpTexture.level !== 1) {
  1564. glTFMaterial.normalTexture.scale = babylonStandardMaterial.bumpTexture.level;
  1565. }
  1566. }
  1567. });
  1568. promises.push(promise);
  1569. }
  1570. if (babylonStandardMaterial.emissiveTexture) {
  1571. var promise = _GLTFMaterial._ExportTextureAsync(babylonStandardMaterial.emissiveTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFEmissiveTexture) {
  1572. if (glTFEmissiveTexture) {
  1573. glTFMaterial.emissiveTexture = glTFEmissiveTexture;
  1574. }
  1575. glTFMaterial.emissiveFactor = [1.0, 1.0, 1.0];
  1576. });
  1577. promises.push(promise);
  1578. }
  1579. if (babylonStandardMaterial.ambientTexture) {
  1580. var promise = _GLTFMaterial._ExportTextureAsync(babylonStandardMaterial.ambientTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1581. if (glTFTexture) {
  1582. var occlusionTexture = {
  1583. index: glTFTexture.index
  1584. };
  1585. glTFMaterial.occlusionTexture = occlusionTexture;
  1586. occlusionTexture.strength = 1.0;
  1587. }
  1588. });
  1589. promises.push(promise);
  1590. }
  1591. }
  1592. if (babylonStandardMaterial.alpha < 1.0 || babylonStandardMaterial.opacityTexture) {
  1593. if (babylonStandardMaterial.alphaMode === BABYLON.Engine.ALPHA_COMBINE) {
  1594. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1595. }
  1596. else {
  1597. BABYLON.Tools.Warn(babylonStandardMaterial.name + ": glTF 2.0 does not support alpha mode: " + babylonStandardMaterial.alphaMode.toString());
  1598. }
  1599. }
  1600. if (babylonStandardMaterial.emissiveColor && !this.FuzzyEquals(babylonStandardMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1601. glTFMaterial.emissiveFactor = babylonStandardMaterial.emissiveColor.asArray();
  1602. }
  1603. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1604. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  1605. switch (alphaMode) {
  1606. case "BLEND" /* BLEND */: {
  1607. glTFMaterial.alphaMode = "BLEND" /* BLEND */;
  1608. break;
  1609. }
  1610. case "MASK" /* MASK */: {
  1611. glTFMaterial.alphaMode = "MASK" /* MASK */;
  1612. glTFMaterial.alphaCutoff = babylonStandardMaterial.alphaCutOff;
  1613. break;
  1614. }
  1615. default: {
  1616. BABYLON.Tools.Warn("Unsupported alpha mode " + alphaMode);
  1617. }
  1618. }
  1619. }
  1620. materials.push(glTFMaterial);
  1621. materialMap[babylonStandardMaterial.uniqueId] = materials.length - 1;
  1622. return Promise.all(promises).then(function () { });
  1623. };
  1624. /**
  1625. *
  1626. * @param texture Texture with alpha to overwrite to one
  1627. * @param useAlpha Specifies if alpha should be preserved or not
  1628. * @returns Promise with texture
  1629. */
  1630. _GLTFMaterial._SetAlphaToOneAsync = function (texture, useAlpha) {
  1631. return new Promise(function (resolve, reject) {
  1632. if (useAlpha) {
  1633. resolve(texture);
  1634. }
  1635. else {
  1636. var scene = texture.getScene();
  1637. if (scene) {
  1638. var proceduralTexture_1 = new BABYLON.ProceduralTexture('texture', texture.getSize(), 'setAlphaToOne', scene);
  1639. if (proceduralTexture_1) {
  1640. proceduralTexture_1.setTexture('textureSampler', texture);
  1641. proceduralTexture_1.onLoadObservable.add(function () { resolve(proceduralTexture_1); });
  1642. }
  1643. else {
  1644. reject("Cannot create procedural texture for " + texture.name + "!");
  1645. }
  1646. }
  1647. else {
  1648. reject("Scene not available for texture " + texture.name);
  1649. }
  1650. }
  1651. });
  1652. };
  1653. /**
  1654. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  1655. * @param babylonPBRMetalRoughMaterial BJS PBR Metallic Roughness Material
  1656. * @param mimeType mime type to use for the textures
  1657. * @param images array of glTF image interfaces
  1658. * @param textures array of glTF texture interfaces
  1659. * @param materials array of glTF material interfaces
  1660. * @param imageData map of image file name to data
  1661. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1662. */
  1663. _GLTFMaterial._ConvertPBRMetallicRoughnessMaterialAsync = function (babylonPBRMetalRoughMaterial, mimeType, images, textures, samplers, materials, materialMap, imageData, hasTextureCoords) {
  1664. var promises = [];
  1665. var glTFPbrMetallicRoughness = {};
  1666. if (babylonPBRMetalRoughMaterial.baseColor) {
  1667. glTFPbrMetallicRoughness.baseColorFactor = [
  1668. babylonPBRMetalRoughMaterial.baseColor.r,
  1669. babylonPBRMetalRoughMaterial.baseColor.g,
  1670. babylonPBRMetalRoughMaterial.baseColor.b,
  1671. babylonPBRMetalRoughMaterial.alpha
  1672. ];
  1673. }
  1674. if (babylonPBRMetalRoughMaterial.metallic != null && babylonPBRMetalRoughMaterial.metallic !== 1) {
  1675. glTFPbrMetallicRoughness.metallicFactor = babylonPBRMetalRoughMaterial.metallic;
  1676. }
  1677. if (babylonPBRMetalRoughMaterial.roughness != null && babylonPBRMetalRoughMaterial.roughness !== 1) {
  1678. glTFPbrMetallicRoughness.roughnessFactor = babylonPBRMetalRoughMaterial.roughness;
  1679. }
  1680. var glTFMaterial = {
  1681. name: babylonPBRMetalRoughMaterial.name
  1682. };
  1683. if (babylonPBRMetalRoughMaterial.doubleSided) {
  1684. glTFMaterial.doubleSided = babylonPBRMetalRoughMaterial.doubleSided;
  1685. }
  1686. var alphaMode = null;
  1687. var useAlpha = false;
  1688. if (babylonPBRMetalRoughMaterial.transparencyMode != null) {
  1689. alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMetalRoughMaterial);
  1690. if (alphaMode) {
  1691. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  1692. glTFMaterial.alphaMode = alphaMode;
  1693. if (alphaMode === "MASK" /* MASK */) {
  1694. glTFMaterial.alphaCutoff = babylonPBRMetalRoughMaterial.alphaCutOff;
  1695. }
  1696. }
  1697. }
  1698. }
  1699. if (alphaMode !== "OPAQUE" /* OPAQUE */) {
  1700. useAlpha = true;
  1701. }
  1702. if (hasTextureCoords) {
  1703. if (babylonPBRMetalRoughMaterial.baseTexture != null) {
  1704. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMetalRoughMaterial.baseTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1705. if (glTFTexture) {
  1706. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  1707. }
  1708. });
  1709. promises.push(promise);
  1710. }
  1711. if (babylonPBRMetalRoughMaterial.normalTexture) {
  1712. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMetalRoughMaterial.normalTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1713. if (glTFTexture) {
  1714. glTFMaterial.normalTexture = glTFTexture;
  1715. if (babylonPBRMetalRoughMaterial.normalTexture.level !== 1) {
  1716. glTFMaterial.normalTexture.scale = babylonPBRMetalRoughMaterial.normalTexture.level;
  1717. }
  1718. }
  1719. });
  1720. promises.push(promise);
  1721. }
  1722. if (babylonPBRMetalRoughMaterial.occlusionTexture) {
  1723. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMetalRoughMaterial.occlusionTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1724. if (glTFTexture) {
  1725. glTFMaterial.occlusionTexture = glTFTexture;
  1726. if (babylonPBRMetalRoughMaterial.occlusionStrength != null) {
  1727. glTFMaterial.occlusionTexture.strength = babylonPBRMetalRoughMaterial.occlusionStrength;
  1728. }
  1729. }
  1730. });
  1731. promises.push(promise);
  1732. }
  1733. if (babylonPBRMetalRoughMaterial.emissiveTexture) {
  1734. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMetalRoughMaterial.emissiveTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  1735. if (glTFTexture) {
  1736. glTFMaterial.emissiveTexture = glTFTexture;
  1737. }
  1738. });
  1739. promises.push(promise);
  1740. }
  1741. }
  1742. if (this.FuzzyEquals(babylonPBRMetalRoughMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  1743. glTFMaterial.emissiveFactor = babylonPBRMetalRoughMaterial.emissiveColor.asArray();
  1744. }
  1745. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  1746. materials.push(glTFMaterial);
  1747. materialMap[babylonPBRMetalRoughMaterial.uniqueId] = materials.length - 1;
  1748. return Promise.all(promises).then(function () { });
  1749. };
  1750. /**
  1751. * Converts an image typed array buffer to a base64 image
  1752. * @param buffer typed array buffer
  1753. * @param width width of the image
  1754. * @param height height of the image
  1755. * @param mimeType mimetype of the image
  1756. * @returns base64 image string
  1757. */
  1758. _GLTFMaterial._CreateBase64FromCanvas = function (buffer, width, height, mimeType) {
  1759. var imageCanvas = document.createElement('canvas');
  1760. imageCanvas.width = width;
  1761. imageCanvas.height = height;
  1762. imageCanvas.id = "WriteCanvas";
  1763. var ctx = imageCanvas.getContext('2d');
  1764. var imgData = ctx.createImageData(width, height);
  1765. imgData.data.set(buffer);
  1766. ctx.putImageData(imgData, 0, 0);
  1767. return imageCanvas.toDataURL(mimeType);
  1768. };
  1769. /**
  1770. * Generates a white texture based on the specified width and height
  1771. * @param width width of the texture in pixels
  1772. * @param height height of the texture in pixels
  1773. * @param scene babylonjs scene
  1774. * @returns white texture
  1775. */
  1776. _GLTFMaterial._CreateWhiteTexture = function (width, height, scene) {
  1777. var data = new Uint8Array(width * height * 4);
  1778. for (var i = 0; i < data.length; i = i + 4) {
  1779. data[i] = data[i + 1] = data[i + 2] = data[i + 3] = 0xFF;
  1780. }
  1781. var rawTexture = BABYLON.RawTexture.CreateRGBATexture(data, width, height, scene);
  1782. return rawTexture;
  1783. };
  1784. /**
  1785. * 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
  1786. * @param texture1 first texture to resize
  1787. * @param texture2 second texture to resize
  1788. * @param scene babylonjs scene
  1789. * @returns resized textures or null
  1790. */
  1791. _GLTFMaterial._ResizeTexturesToSameDimensions = function (texture1, texture2, scene) {
  1792. var texture1Size = texture1 ? texture1.getSize() : { width: 0, height: 0 };
  1793. var texture2Size = texture2 ? texture2.getSize() : { width: 0, height: 0 };
  1794. var resizedTexture1;
  1795. var resizedTexture2;
  1796. if (texture1Size.width < texture2Size.width) {
  1797. if (texture1) {
  1798. resizedTexture1 = BABYLON.TextureTools.CreateResizedCopy(texture1, texture2Size.width, texture2Size.height, true);
  1799. }
  1800. else {
  1801. resizedTexture1 = this._CreateWhiteTexture(texture2Size.width, texture2Size.height, scene);
  1802. }
  1803. resizedTexture2 = texture2;
  1804. }
  1805. else if (texture1Size.width > texture2Size.width) {
  1806. if (texture2) {
  1807. resizedTexture2 = BABYLON.TextureTools.CreateResizedCopy(texture2, texture1Size.width, texture1Size.height, true);
  1808. }
  1809. else {
  1810. resizedTexture2 = this._CreateWhiteTexture(texture1Size.width, texture1Size.height, scene);
  1811. }
  1812. resizedTexture1 = texture1;
  1813. }
  1814. else {
  1815. resizedTexture1 = texture1;
  1816. resizedTexture2 = texture2;
  1817. }
  1818. return {
  1819. "texture1": resizedTexture1,
  1820. "texture2": resizedTexture2
  1821. };
  1822. };
  1823. /**
  1824. * Convert Specular Glossiness Textures to Metallic Roughness
  1825. * See link below for info on the material conversions from PBR Metallic/Roughness and Specular/Glossiness
  1826. * @link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness/examples/convert-between-workflows-bjs/js/babylon.pbrUtilities.js
  1827. * @param diffuseTexture texture used to store diffuse information
  1828. * @param specularGlossinessTexture texture used to store specular and glossiness information
  1829. * @param factors specular glossiness material factors
  1830. * @param mimeType the mime type to use for the texture
  1831. * @returns pbr metallic roughness interface or null
  1832. */
  1833. _GLTFMaterial._ConvertSpecularGlossinessTexturesToMetallicRoughness = function (diffuseTexture, specularGlossinessTexture, factors, mimeType) {
  1834. if (!(diffuseTexture || specularGlossinessTexture)) {
  1835. BABYLON.Tools.Warn('_ConvertSpecularGlosinessTexturesToMetallicRoughness: diffuse and specular glossiness textures are not defined!');
  1836. return null;
  1837. }
  1838. var scene = diffuseTexture ? diffuseTexture.getScene() : specularGlossinessTexture ? specularGlossinessTexture.getScene() : null;
  1839. if (scene) {
  1840. var resizedTextures = this._ResizeTexturesToSameDimensions(diffuseTexture, specularGlossinessTexture, scene);
  1841. var diffuseSize = resizedTextures.texture1.getSize();
  1842. var diffuseBuffer = void 0;
  1843. var specularGlossinessBuffer = void 0;
  1844. var width = diffuseSize.width;
  1845. var height = diffuseSize.height;
  1846. var pixels = (resizedTextures.texture1.readPixels());
  1847. if (pixels instanceof Uint8Array) {
  1848. diffuseBuffer = (resizedTextures.texture1.readPixels());
  1849. pixels = resizedTextures.texture2.readPixels();
  1850. if (pixels instanceof Uint8Array) {
  1851. specularGlossinessBuffer = (resizedTextures.texture2.readPixels());
  1852. var byteLength = specularGlossinessBuffer.byteLength;
  1853. var metallicRoughnessBuffer = new Uint8Array(byteLength);
  1854. var baseColorBuffer = new Uint8Array(byteLength);
  1855. var strideSize = 4;
  1856. var maxBaseColor = BABYLON.Color3.Black();
  1857. var maxMetallic = 0;
  1858. var maxRoughness = 0;
  1859. for (var h = 0; h < height; ++h) {
  1860. for (var w = 0; w < width; ++w) {
  1861. var offset = (width * h + w) * strideSize;
  1862. var diffuseColor = BABYLON.Color3.FromInts(diffuseBuffer[offset], diffuseBuffer[offset + 1], diffuseBuffer[offset + 2]).toLinearSpace().multiply(factors.diffuseColor);
  1863. var specularColor = BABYLON.Color3.FromInts(specularGlossinessBuffer[offset], specularGlossinessBuffer[offset + 1], specularGlossinessBuffer[offset + 2]).toLinearSpace().multiply(factors.specularColor);
  1864. var glossiness = (specularGlossinessBuffer[offset + 3] / 255) * factors.glossiness;
  1865. var specularGlossiness = {
  1866. diffuseColor: diffuseColor,
  1867. specularColor: specularColor,
  1868. glossiness: glossiness
  1869. };
  1870. var metallicRoughness = this._ConvertSpecularGlossinessToMetallicRoughness(specularGlossiness);
  1871. maxBaseColor.r = Math.max(maxBaseColor.r, metallicRoughness.baseColor.r);
  1872. maxBaseColor.g = Math.max(maxBaseColor.g, metallicRoughness.baseColor.g);
  1873. maxBaseColor.b = Math.max(maxBaseColor.b, metallicRoughness.baseColor.b);
  1874. maxMetallic = Math.max(maxMetallic, metallicRoughness.metallic);
  1875. maxRoughness = Math.max(maxRoughness, metallicRoughness.roughness);
  1876. baseColorBuffer[offset] = metallicRoughness.baseColor.r * 255;
  1877. baseColorBuffer[offset + 1] = metallicRoughness.baseColor.g * 255;
  1878. baseColorBuffer[offset + 2] = metallicRoughness.baseColor.b * 255;
  1879. baseColorBuffer[offset + 3] = resizedTextures.texture1.hasAlpha ? diffuseBuffer[offset + 3] : 255;
  1880. metallicRoughnessBuffer[offset] = 0;
  1881. metallicRoughnessBuffer[offset + 1] = metallicRoughness.roughness * 255;
  1882. metallicRoughnessBuffer[offset + 2] = metallicRoughness.metallic * 255;
  1883. metallicRoughnessBuffer[offset + 3] = 255;
  1884. }
  1885. }
  1886. // Retrieves the metallic roughness factors from the maximum texture values.
  1887. var metallicRoughnessFactors = {
  1888. baseColor: maxBaseColor,
  1889. metallic: maxMetallic,
  1890. roughness: maxRoughness
  1891. };
  1892. var writeOutMetallicRoughnessTexture = false;
  1893. var writeOutBaseColorTexture = false;
  1894. for (var h = 0; h < height; ++h) {
  1895. for (var w = 0; w < width; ++w) {
  1896. var destinationOffset = (width * h + w) * strideSize;
  1897. baseColorBuffer[destinationOffset] /= metallicRoughnessFactors.baseColor.r > this._epsilon ? metallicRoughnessFactors.baseColor.r : 1;
  1898. baseColorBuffer[destinationOffset + 1] /= metallicRoughnessFactors.baseColor.g > this._epsilon ? metallicRoughnessFactors.baseColor.g : 1;
  1899. baseColorBuffer[destinationOffset + 2] /= metallicRoughnessFactors.baseColor.b > this._epsilon ? metallicRoughnessFactors.baseColor.b : 1;
  1900. var linearBaseColorPixel = BABYLON.Color3.FromInts(baseColorBuffer[destinationOffset], baseColorBuffer[destinationOffset + 1], baseColorBuffer[destinationOffset + 2]);
  1901. var sRGBBaseColorPixel = linearBaseColorPixel.toGammaSpace();
  1902. baseColorBuffer[destinationOffset] = sRGBBaseColorPixel.r * 255;
  1903. baseColorBuffer[destinationOffset + 1] = sRGBBaseColorPixel.g * 255;
  1904. baseColorBuffer[destinationOffset + 2] = sRGBBaseColorPixel.b * 255;
  1905. if (!this.FuzzyEquals(sRGBBaseColorPixel, BABYLON.Color3.White(), this._epsilon)) {
  1906. writeOutBaseColorTexture = true;
  1907. }
  1908. metallicRoughnessBuffer[destinationOffset + 1] /= metallicRoughnessFactors.roughness > this._epsilon ? metallicRoughnessFactors.roughness : 1;
  1909. metallicRoughnessBuffer[destinationOffset + 2] /= metallicRoughnessFactors.metallic > this._epsilon ? metallicRoughnessFactors.metallic : 1;
  1910. var metallicRoughnessPixel = BABYLON.Color3.FromInts(255, metallicRoughnessBuffer[destinationOffset + 1], metallicRoughnessBuffer[destinationOffset + 2]);
  1911. if (!this.FuzzyEquals(metallicRoughnessPixel, BABYLON.Color3.White(), this._epsilon)) {
  1912. writeOutMetallicRoughnessTexture = true;
  1913. }
  1914. }
  1915. }
  1916. if (writeOutMetallicRoughnessTexture) {
  1917. var metallicRoughnessBase64 = this._CreateBase64FromCanvas(metallicRoughnessBuffer, width, height, mimeType);
  1918. metallicRoughnessFactors.metallicRoughnessTextureBase64 = metallicRoughnessBase64;
  1919. }
  1920. if (writeOutBaseColorTexture) {
  1921. var baseColorBase64 = this._CreateBase64FromCanvas(baseColorBuffer, width, height, mimeType);
  1922. metallicRoughnessFactors.baseColorTextureBase64 = baseColorBase64;
  1923. }
  1924. return metallicRoughnessFactors;
  1925. }
  1926. else {
  1927. BABYLON.Tools.Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture2.name);
  1928. }
  1929. }
  1930. else {
  1931. BABYLON.Tools.Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Pixel array buffer type not supported for texture: " + resizedTextures.texture1.name);
  1932. }
  1933. }
  1934. else {
  1935. BABYLON.Tools.Error("_ConvertSpecularGlossinessTexturesToMetallicRoughness: Scene from textures is missing!");
  1936. }
  1937. return null;
  1938. };
  1939. /**
  1940. * Converts specular glossiness material properties to metallic roughness
  1941. * @param specularGlossiness interface with specular glossiness material properties
  1942. * @returns interface with metallic roughness material properties
  1943. */
  1944. _GLTFMaterial._ConvertSpecularGlossinessToMetallicRoughness = function (specularGlossiness) {
  1945. var diffusePerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.diffuseColor);
  1946. var specularPerceivedBrightness = _GLTFMaterial._GetPerceivedBrightness(specularGlossiness.specularColor);
  1947. var oneMinusSpecularStrength = 1 - _GLTFMaterial._GetMaxComponent(specularGlossiness.specularColor);
  1948. var metallic = _GLTFMaterial._SolveMetallic(diffusePerceivedBrightness, specularPerceivedBrightness, oneMinusSpecularStrength);
  1949. var baseColorFromDiffuse = specularGlossiness.diffuseColor.scale(oneMinusSpecularStrength / (1.0 - this._dielectricSpecular.r) / Math.max(1 - metallic, this._epsilon));
  1950. var baseColorFromSpecular = specularGlossiness.specularColor.subtract(this._dielectricSpecular.scale(1 - metallic)).scale(1 / Math.max(metallic, this._epsilon));
  1951. var baseColor = BABYLON.Color3.Lerp(baseColorFromDiffuse, baseColorFromSpecular, metallic * metallic);
  1952. baseColor = baseColor.clampToRef(0, 1, baseColor);
  1953. var metallicRoughness = {
  1954. baseColor: baseColor,
  1955. metallic: metallic,
  1956. roughness: 1 - specularGlossiness.glossiness
  1957. };
  1958. return metallicRoughness;
  1959. };
  1960. /**
  1961. * Calculates the surface reflectance, independent of lighting conditions
  1962. * @param color Color source to calculate brightness from
  1963. * @returns number representing the perceived brightness, or zero if color is undefined
  1964. */
  1965. _GLTFMaterial._GetPerceivedBrightness = function (color) {
  1966. if (color) {
  1967. return Math.sqrt(0.299 * color.r * color.r + 0.587 * color.g * color.g + 0.114 * color.b * color.b);
  1968. }
  1969. return 0;
  1970. };
  1971. /**
  1972. * Returns the maximum color component value
  1973. * @param color
  1974. * @returns maximum color component value, or zero if color is null or undefined
  1975. */
  1976. _GLTFMaterial._GetMaxComponent = function (color) {
  1977. if (color) {
  1978. return Math.max(color.r, Math.max(color.g, color.b));
  1979. }
  1980. return 0;
  1981. };
  1982. /**
  1983. * Convert a PBRMaterial (Metallic/Roughness) to Metallic Roughness factors
  1984. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  1985. * @param mimeType mime type to use for the textures
  1986. * @param images array of glTF image interfaces
  1987. * @param textures array of glTF texture interfaces
  1988. * @param glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  1989. * @param imageData map of image file name to data
  1990. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  1991. * @returns glTF PBR Metallic Roughness factors
  1992. */
  1993. _GLTFMaterial._ConvertMetalRoughFactorsToMetallicRoughnessAsync = function (babylonPBRMaterial, mimeType, images, textures, samplers, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  1994. var alphaMode = this._GetAlphaMode(babylonPBRMaterial);
  1995. var useAlpha = alphaMode !== "OPAQUE" /* OPAQUE */ ? true : false;
  1996. var promises = [];
  1997. var metallicRoughness = {
  1998. baseColor: babylonPBRMaterial.albedoColor,
  1999. metallic: babylonPBRMaterial.metallic,
  2000. roughness: babylonPBRMaterial.roughness
  2001. };
  2002. if (hasTextureCoords) {
  2003. if (babylonPBRMaterial.albedoTexture) {
  2004. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMaterial.albedoTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  2005. if (glTFTexture) {
  2006. glTFPbrMetallicRoughness.baseColorTexture = glTFTexture;
  2007. }
  2008. });
  2009. promises.push(promise);
  2010. }
  2011. if (babylonPBRMaterial.metallicTexture) {
  2012. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMaterial.metallicTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  2013. if (glTFTexture) {
  2014. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFTexture;
  2015. }
  2016. });
  2017. promises.push(promise);
  2018. }
  2019. }
  2020. return Promise.all(promises).then(function () {
  2021. return metallicRoughness;
  2022. });
  2023. };
  2024. _GLTFMaterial._GetGLTFTextureSampler = function (texture) {
  2025. var sampler = _GLTFMaterial._GetGLTFTextureWrapModesSampler(texture);
  2026. var samplingMode = texture instanceof BABYLON.Texture ? texture.samplingMode : null;
  2027. if (samplingMode != null) {
  2028. switch (samplingMode) {
  2029. case BABYLON.Texture.LINEAR_LINEAR: {
  2030. sampler.magFilter = 9729 /* LINEAR */;
  2031. sampler.minFilter = 9729 /* LINEAR */;
  2032. break;
  2033. }
  2034. case BABYLON.Texture.LINEAR_NEAREST: {
  2035. sampler.magFilter = 9729 /* LINEAR */;
  2036. sampler.minFilter = 9728 /* NEAREST */;
  2037. break;
  2038. }
  2039. case BABYLON.Texture.NEAREST_LINEAR: {
  2040. sampler.magFilter = 9728 /* NEAREST */;
  2041. sampler.minFilter = 9729 /* LINEAR */;
  2042. break;
  2043. }
  2044. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR: {
  2045. sampler.magFilter = 9728 /* NEAREST */;
  2046. sampler.minFilter = 9987 /* LINEAR_MIPMAP_LINEAR */;
  2047. break;
  2048. }
  2049. case BABYLON.Texture.NEAREST_NEAREST: {
  2050. sampler.magFilter = 9728 /* NEAREST */;
  2051. sampler.minFilter = 9728 /* NEAREST */;
  2052. break;
  2053. }
  2054. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST: {
  2055. sampler.magFilter = 9728 /* NEAREST */;
  2056. sampler.minFilter = 9985 /* LINEAR_MIPMAP_NEAREST */;
  2057. break;
  2058. }
  2059. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST: {
  2060. sampler.magFilter = 9729 /* LINEAR */;
  2061. sampler.minFilter = 9984 /* NEAREST_MIPMAP_NEAREST */;
  2062. break;
  2063. }
  2064. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR: {
  2065. sampler.magFilter = 9729 /* LINEAR */;
  2066. sampler.minFilter = 9986 /* NEAREST_MIPMAP_LINEAR */;
  2067. break;
  2068. }
  2069. case BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR: {
  2070. sampler.magFilter = 9728 /* NEAREST */;
  2071. sampler.minFilter = 9986 /* NEAREST_MIPMAP_LINEAR */;
  2072. break;
  2073. }
  2074. case BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR: {
  2075. sampler.magFilter = 9729 /* LINEAR */;
  2076. sampler.minFilter = 9987 /* LINEAR_MIPMAP_LINEAR */;
  2077. break;
  2078. }
  2079. case BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST: {
  2080. sampler.magFilter = 9729 /* LINEAR */;
  2081. sampler.minFilter = 9985 /* LINEAR_MIPMAP_NEAREST */;
  2082. break;
  2083. }
  2084. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST: {
  2085. sampler.magFilter = 9728 /* NEAREST */;
  2086. sampler.minFilter = 9984 /* NEAREST_MIPMAP_NEAREST */;
  2087. break;
  2088. }
  2089. }
  2090. }
  2091. return sampler;
  2092. };
  2093. _GLTFMaterial._GetGLTFTextureWrapMode = function (wrapMode) {
  2094. switch (wrapMode) {
  2095. case BABYLON.Texture.WRAP_ADDRESSMODE: {
  2096. return 10497 /* REPEAT */;
  2097. }
  2098. case BABYLON.Texture.CLAMP_ADDRESSMODE: {
  2099. return 33071 /* CLAMP_TO_EDGE */;
  2100. }
  2101. case BABYLON.Texture.MIRROR_ADDRESSMODE: {
  2102. return 33648 /* MIRRORED_REPEAT */;
  2103. }
  2104. default: {
  2105. BABYLON.Tools.Error("Unsupported Texture Wrap Mode " + wrapMode + "!");
  2106. return 10497 /* REPEAT */;
  2107. }
  2108. }
  2109. };
  2110. _GLTFMaterial._GetGLTFTextureWrapModesSampler = function (texture) {
  2111. var wrapS = _GLTFMaterial._GetGLTFTextureWrapMode(texture instanceof BABYLON.Texture ? texture.wrapU : BABYLON.Texture.WRAP_ADDRESSMODE);
  2112. var wrapT = _GLTFMaterial._GetGLTFTextureWrapMode(texture instanceof BABYLON.Texture ? texture.wrapV : BABYLON.Texture.WRAP_ADDRESSMODE);
  2113. if (wrapS === 10497 /* REPEAT */ && wrapT === 10497 /* REPEAT */) { // default wrapping mode in glTF, so omitting
  2114. return {};
  2115. }
  2116. return { wrapS: wrapS, wrapT: wrapT };
  2117. };
  2118. /**
  2119. * Convert a PBRMaterial (Specular/Glossiness) to Metallic Roughness factors
  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 glTFPbrMetallicRoughness glTF PBR Metallic Roughness interface
  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. * @returns glTF PBR Metallic Roughness factors
  2128. */
  2129. _GLTFMaterial._ConvertSpecGlossFactorsToMetallicRoughness = function (babylonPBRMaterial, mimeType, images, textures, samplers, glTFPbrMetallicRoughness, imageData, hasTextureCoords) {
  2130. var specGloss = {
  2131. diffuseColor: babylonPBRMaterial.albedoColor || BABYLON.Color3.White(),
  2132. specularColor: babylonPBRMaterial.reflectivityColor || BABYLON.Color3.White(),
  2133. glossiness: babylonPBRMaterial.microSurface || 1,
  2134. };
  2135. var samplerIndex = null;
  2136. var sampler = this._GetGLTFTextureSampler(babylonPBRMaterial.albedoTexture);
  2137. if (sampler.magFilter != null && sampler.minFilter != null && sampler.wrapS != null && sampler.wrapT != null) {
  2138. samplers.push(sampler);
  2139. samplerIndex = samplers.length - 1;
  2140. }
  2141. if (babylonPBRMaterial.reflectivityTexture && !babylonPBRMaterial.useMicroSurfaceFromReflectivityMapAlpha) {
  2142. BABYLON.Tools.Error("_ConvertPBRMaterial: Glossiness values not included in the reflectivity texture are currently not supported");
  2143. return null;
  2144. }
  2145. var metallicRoughnessFactors = this._ConvertSpecularGlossinessTexturesToMetallicRoughness(babylonPBRMaterial.albedoTexture, babylonPBRMaterial.reflectivityTexture, specGloss, mimeType);
  2146. if (metallicRoughnessFactors) {
  2147. if (hasTextureCoords) {
  2148. if (metallicRoughnessFactors.baseColorTextureBase64) {
  2149. var glTFBaseColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.baseColorTextureBase64, "bjsBaseColorTexture_" + (textures.length) + ".png", mimeType, images, textures, babylonPBRMaterial.albedoTexture ? babylonPBRMaterial.albedoTexture.coordinatesIndex : null, samplerIndex, imageData);
  2150. if (glTFBaseColorTexture != null) {
  2151. glTFPbrMetallicRoughness.baseColorTexture = glTFBaseColorTexture;
  2152. }
  2153. }
  2154. if (metallicRoughnessFactors.metallicRoughnessTextureBase64) {
  2155. var glTFMRColorTexture = _GLTFMaterial._GetTextureInfoFromBase64(metallicRoughnessFactors.metallicRoughnessTextureBase64, "bjsMetallicRoughnessTexture_" + (textures.length) + ".png", mimeType, images, textures, babylonPBRMaterial.reflectivityTexture ? babylonPBRMaterial.reflectivityTexture.coordinatesIndex : null, samplerIndex, imageData);
  2156. if (glTFMRColorTexture != null) {
  2157. glTFPbrMetallicRoughness.metallicRoughnessTexture = glTFMRColorTexture;
  2158. }
  2159. }
  2160. return metallicRoughnessFactors;
  2161. }
  2162. }
  2163. return this._ConvertSpecularGlossinessToMetallicRoughness(specGloss);
  2164. };
  2165. /**
  2166. * Converts a Babylon PBR Metallic Roughness Material to a glTF Material
  2167. * @param babylonPBRMaterial BJS PBR Metallic Roughness Material
  2168. * @param mimeType mime type to use for the textures
  2169. * @param images array of glTF image interfaces
  2170. * @param textures array of glTF texture interfaces
  2171. * @param materials array of glTF material interfaces
  2172. * @param imageData map of image file name to data
  2173. * @param hasTextureCoords specifies if texture coordinates are present on the submesh to determine if textures should be applied
  2174. */
  2175. _GLTFMaterial._ConvertPBRMaterialAsync = function (babylonPBRMaterial, mimeType, images, textures, samplers, materials, materialMap, imageData, hasTextureCoords) {
  2176. var glTFPbrMetallicRoughness = {};
  2177. var glTFMaterial = {
  2178. name: babylonPBRMaterial.name
  2179. };
  2180. var useMetallicRoughness = babylonPBRMaterial.isMetallicWorkflow();
  2181. if (useMetallicRoughness) {
  2182. if (babylonPBRMaterial.albedoColor) {
  2183. glTFPbrMetallicRoughness.baseColorFactor = [
  2184. babylonPBRMaterial.albedoColor.r,
  2185. babylonPBRMaterial.albedoColor.g,
  2186. babylonPBRMaterial.albedoColor.b,
  2187. babylonPBRMaterial.alpha
  2188. ];
  2189. }
  2190. return this._ConvertMetalRoughFactorsToMetallicRoughnessAsync(babylonPBRMaterial, mimeType, images, textures, samplers, glTFPbrMetallicRoughness, imageData, hasTextureCoords).then(function (metallicRoughness) {
  2191. return _GLTFMaterial.SetMetallicRoughnessPbrMaterial(metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, images, textures, samplers, materials, materialMap, imageData, hasTextureCoords);
  2192. });
  2193. }
  2194. else {
  2195. var metallicRoughness = this._ConvertSpecGlossFactorsToMetallicRoughness(babylonPBRMaterial, mimeType, images, textures, samplers, glTFPbrMetallicRoughness, imageData, hasTextureCoords);
  2196. return _GLTFMaterial.SetMetallicRoughnessPbrMaterial(metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, images, textures, samplers, materials, materialMap, imageData, hasTextureCoords);
  2197. }
  2198. };
  2199. _GLTFMaterial.SetMetallicRoughnessPbrMaterial = function (metallicRoughness, babylonPBRMaterial, glTFMaterial, glTFPbrMetallicRoughness, mimeType, images, textures, samplers, materials, materialMap, imageData, hasTextureCoords) {
  2200. var promises = [];
  2201. if (metallicRoughness) {
  2202. var alphaMode = null;
  2203. var useAlpha = false;
  2204. if (babylonPBRMaterial.transparencyMode != null) {
  2205. alphaMode = _GLTFMaterial._GetAlphaMode(babylonPBRMaterial);
  2206. if (alphaMode) {
  2207. if (alphaMode !== "OPAQUE" /* OPAQUE */) { //glTF defaults to opaque
  2208. useAlpha = true;
  2209. glTFMaterial.alphaMode = alphaMode;
  2210. if (alphaMode === "MASK" /* MASK */) {
  2211. glTFMaterial.alphaCutoff = babylonPBRMaterial.alphaCutOff;
  2212. }
  2213. }
  2214. }
  2215. }
  2216. if (!(this.FuzzyEquals(metallicRoughness.baseColor, BABYLON.Color3.White(), this._epsilon) && babylonPBRMaterial.alpha >= this._epsilon)) {
  2217. glTFPbrMetallicRoughness.baseColorFactor = [
  2218. metallicRoughness.baseColor.r,
  2219. metallicRoughness.baseColor.g,
  2220. metallicRoughness.baseColor.b,
  2221. babylonPBRMaterial.alpha
  2222. ];
  2223. }
  2224. if (metallicRoughness.metallic != null && metallicRoughness.metallic !== 1) {
  2225. glTFPbrMetallicRoughness.metallicFactor = metallicRoughness.metallic;
  2226. }
  2227. if (metallicRoughness.roughness != null && metallicRoughness.roughness !== 1) {
  2228. glTFPbrMetallicRoughness.roughnessFactor = metallicRoughness.roughness;
  2229. }
  2230. if (babylonPBRMaterial.backFaceCulling != null && !babylonPBRMaterial.backFaceCulling) {
  2231. if (!babylonPBRMaterial.twoSidedLighting) {
  2232. BABYLON.Tools.Warn(babylonPBRMaterial.name + ": Back-face culling enabled and two-sided lighting disabled is not supported in glTF.");
  2233. }
  2234. glTFMaterial.doubleSided = true;
  2235. }
  2236. if (hasTextureCoords) {
  2237. if (babylonPBRMaterial.bumpTexture) {
  2238. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMaterial.bumpTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  2239. if (glTFTexture) {
  2240. glTFMaterial.normalTexture = glTFTexture;
  2241. if (babylonPBRMaterial.bumpTexture.level !== 1) {
  2242. glTFMaterial.normalTexture.scale = babylonPBRMaterial.bumpTexture.level;
  2243. }
  2244. }
  2245. });
  2246. promises.push(promise);
  2247. }
  2248. if (babylonPBRMaterial.ambientTexture) {
  2249. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMaterial.ambientTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  2250. if (glTFTexture) {
  2251. var occlusionTexture = {
  2252. index: glTFTexture.index
  2253. };
  2254. glTFMaterial.occlusionTexture = occlusionTexture;
  2255. if (babylonPBRMaterial.ambientTextureStrength) {
  2256. occlusionTexture.strength = babylonPBRMaterial.ambientTextureStrength;
  2257. }
  2258. }
  2259. });
  2260. promises.push(promise);
  2261. }
  2262. if (babylonPBRMaterial.emissiveTexture) {
  2263. var promise = _GLTFMaterial._ExportTextureAsync(babylonPBRMaterial.emissiveTexture, mimeType, images, textures, samplers, imageData, useAlpha).then(function (glTFTexture) {
  2264. if (glTFTexture) {
  2265. glTFMaterial.emissiveTexture = glTFTexture;
  2266. }
  2267. });
  2268. promises.push(promise);
  2269. }
  2270. }
  2271. if (!this.FuzzyEquals(babylonPBRMaterial.emissiveColor, BABYLON.Color3.Black(), this._epsilon)) {
  2272. glTFMaterial.emissiveFactor = babylonPBRMaterial.emissiveColor.asArray();
  2273. }
  2274. glTFMaterial.pbrMetallicRoughness = glTFPbrMetallicRoughness;
  2275. materials.push(glTFMaterial);
  2276. materialMap[babylonPBRMaterial.uniqueId] = materials.length - 1;
  2277. }
  2278. return Promise.all(promises).then(function (result) { });
  2279. };
  2280. _GLTFMaterial.GetPixelsFromTexture = function (babylonTexture) {
  2281. var pixels = babylonTexture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT ? babylonTexture.readPixels() : babylonTexture.readPixels();
  2282. return pixels;
  2283. };
  2284. /**
  2285. * Extracts a texture from a Babylon texture into file data and glTF data
  2286. * @param babylonTexture Babylon texture to extract
  2287. * @param mimeType Mime Type of the babylonTexture
  2288. * @param images Array of glTF images
  2289. * @param textures Array of glTF textures
  2290. * @param imageData map of image file name and data
  2291. * @return glTF texture info, or null if the texture format is not supported
  2292. */
  2293. _GLTFMaterial._ExportTextureAsync = function (babylonTexture, mimeType, images, textures, samplers, imageData, useAlpha) {
  2294. var _this = this;
  2295. var sampler = _GLTFMaterial._GetGLTFTextureSampler(babylonTexture);
  2296. var samplerIndex = null;
  2297. // if a pre-existing sampler with identical parameters exists, then reuse the previous sampler
  2298. var foundSamplerIndex = null;
  2299. for (var i = 0; i < samplers.length; ++i) {
  2300. var s = samplers[i];
  2301. if (s.minFilter === sampler.minFilter && s.magFilter === sampler.magFilter &&
  2302. s.wrapS === sampler.wrapS && s.wrapT === sampler.wrapT) {
  2303. foundSamplerIndex = i;
  2304. break;
  2305. }
  2306. }
  2307. if (foundSamplerIndex == null) {
  2308. samplers.push(sampler);
  2309. samplerIndex = samplers.length - 1;
  2310. }
  2311. else {
  2312. samplerIndex = foundSamplerIndex;
  2313. }
  2314. var textureName = BABYLON.Tools.RandomId();
  2315. var textureData = babylonTexture.getInternalTexture();
  2316. if (textureData != null) {
  2317. textureName = textureData.url || textureName;
  2318. }
  2319. textureName = BABYLON.Tools.GetFilename(textureName);
  2320. var baseFile = textureName.split('.')[0];
  2321. var extension = "";
  2322. if (mimeType === "image/jpeg" /* JPEG */) {
  2323. extension = ".jpg";
  2324. }
  2325. else if (mimeType === "image/png" /* PNG */) {
  2326. extension = ".png";
  2327. }
  2328. else {
  2329. return Promise.reject("Unsupported mime type " + mimeType);
  2330. }
  2331. textureName = baseFile + extension;
  2332. return this._SetAlphaToOneAsync(babylonTexture, useAlpha).then(function (texture) {
  2333. var pixels = _GLTFMaterial.GetPixelsFromTexture(texture);
  2334. var size = babylonTexture.getSize();
  2335. var base64Data = _this._CreateBase64FromCanvas(pixels, size.width, size.height, mimeType);
  2336. var textureInfo = _this._GetTextureInfoFromBase64(base64Data, textureName, mimeType, images, textures, babylonTexture.coordinatesIndex, samplerIndex, imageData);
  2337. return textureInfo;
  2338. });
  2339. };
  2340. /**
  2341. * Builds a texture from base64 string
  2342. * @param base64Texture base64 texture string
  2343. * @param textureName Name to use for the texture
  2344. * @param mimeType image mime type for the texture
  2345. * @param images array of images
  2346. * @param textures array of textures
  2347. * @param imageData map of image data
  2348. * @returns glTF texture info, or null if the texture format is not supported
  2349. */
  2350. _GLTFMaterial._GetTextureInfoFromBase64 = function (base64Texture, textureName, mimeType, images, textures, texCoordIndex, samplerIndex, imageData) {
  2351. var textureInfo = null;
  2352. var glTFTexture = {
  2353. source: images.length,
  2354. name: textureName
  2355. };
  2356. if (samplerIndex != null) {
  2357. glTFTexture.sampler = samplerIndex;
  2358. }
  2359. var binStr = atob(base64Texture.split(',')[1]);
  2360. var arrBuff = new ArrayBuffer(binStr.length);
  2361. var arr = new Uint8Array(arrBuff);
  2362. for (var i = 0, length_1 = binStr.length; i < length_1; ++i) {
  2363. arr[i] = binStr.charCodeAt(i);
  2364. }
  2365. var imageValues = { data: arr, mimeType: mimeType };
  2366. imageData[textureName] = imageValues;
  2367. if (mimeType === "image/jpeg" /* JPEG */ || mimeType === "image/png" /* PNG */) {
  2368. var glTFImage = {
  2369. uri: textureName
  2370. };
  2371. var foundIndex = null;
  2372. for (var i = 0; i < images.length; ++i) {
  2373. if (images[i].uri === textureName) {
  2374. foundIndex = i;
  2375. break;
  2376. }
  2377. }
  2378. if (foundIndex == null) {
  2379. images.push(glTFImage);
  2380. glTFTexture.source = images.length - 1;
  2381. }
  2382. else {
  2383. glTFTexture.source = foundIndex;
  2384. }
  2385. textures.push(glTFTexture);
  2386. textureInfo = {
  2387. index: textures.length - 1
  2388. };
  2389. if (texCoordIndex != null) {
  2390. textureInfo.texCoord = texCoordIndex;
  2391. }
  2392. }
  2393. return textureInfo;
  2394. };
  2395. /**
  2396. * Represents the dielectric specular values for R, G and B
  2397. */
  2398. _GLTFMaterial._dielectricSpecular = new BABYLON.Color3(0.04, 0.04, 0.04);
  2399. /**
  2400. * Allows the maximum specular power to be defined for material calculations
  2401. */
  2402. _GLTFMaterial._maxSpecularPower = 1024;
  2403. /**
  2404. * Numeric tolerance value
  2405. */
  2406. _GLTFMaterial._epsilon = 1e-6;
  2407. return _GLTFMaterial;
  2408. }());
  2409. GLTF2._GLTFMaterial = _GLTFMaterial;
  2410. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  2411. })(BABYLON || (BABYLON = {}));
  2412. //# sourceMappingURL=babylon.glTFMaterial.js.map
  2413. /// <reference path="../../../../dist/preview release/gltf2Interface/babylon.glTF2Interface.d.ts"/>
  2414. var BABYLON;
  2415. (function (BABYLON) {
  2416. var GLTF2;
  2417. (function (GLTF2) {
  2418. /**
  2419. * @hidden
  2420. * Enum for handling in tangent and out tangent.
  2421. */
  2422. var _TangentType;
  2423. (function (_TangentType) {
  2424. /**
  2425. * Specifies that input tangents are used.
  2426. */
  2427. _TangentType[_TangentType["INTANGENT"] = 0] = "INTANGENT";
  2428. /**
  2429. * Specifies that output tangents are used.
  2430. */
  2431. _TangentType[_TangentType["OUTTANGENT"] = 1] = "OUTTANGENT";
  2432. })(_TangentType || (_TangentType = {}));
  2433. /**
  2434. * @hidden
  2435. * Utility class for generating glTF animation data from BabylonJS.
  2436. */
  2437. var _GLTFAnimation = /** @class */ (function () {
  2438. function _GLTFAnimation() {
  2439. }
  2440. /**
  2441. * @ignore
  2442. *
  2443. * Creates glTF channel animation from BabylonJS animation.
  2444. * @param babylonTransformNode - BabylonJS mesh.
  2445. * @param animation - animation.
  2446. * @param animationChannelTargetPath - The target animation channel.
  2447. * @param convertToRightHandedSystem - Specifies if the values should be converted to right-handed.
  2448. * @param useQuaternion - Specifies if quaternions are used.
  2449. * @returns nullable IAnimationData
  2450. */
  2451. _GLTFAnimation._CreateNodeAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  2452. var inputs = [];
  2453. var outputs = [];
  2454. var keyFrames = animation.getKeys();
  2455. var minMaxKeyFrames = _GLTFAnimation.calculateMinMaxKeyFrames(keyFrames);
  2456. var interpolationOrBake = _GLTFAnimation._DeduceInterpolation(keyFrames, animationChannelTargetPath, useQuaternion);
  2457. var frameDelta = minMaxKeyFrames.max - minMaxKeyFrames.min;
  2458. var interpolation = interpolationOrBake.interpolationType;
  2459. var shouldBakeAnimation = interpolationOrBake.shouldBakeAnimation;
  2460. if (shouldBakeAnimation) {
  2461. _GLTFAnimation._CreateBakedAnimation(babylonTransformNode, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  2462. }
  2463. else {
  2464. if (interpolation === "LINEAR" /* LINEAR */ || interpolation === "STEP" /* STEP */) {
  2465. _GLTFAnimation._CreateLinearOrStepAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2466. }
  2467. else if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  2468. _GLTFAnimation._CreateCubicSplineAnimation(babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2469. }
  2470. else {
  2471. _GLTFAnimation._CreateBakedAnimation(babylonTransformNode, animation, animationChannelTargetPath, minMaxKeyFrames.min, minMaxKeyFrames.max, animation.framePerSecond, animationSampleRate, inputs, outputs, minMaxKeyFrames, convertToRightHandedSystem, useQuaternion);
  2472. }
  2473. }
  2474. if (inputs.length && outputs.length) {
  2475. var result = {
  2476. inputs: inputs,
  2477. outputs: outputs,
  2478. samplerInterpolation: interpolation,
  2479. inputsMin: shouldBakeAnimation ? minMaxKeyFrames.min : BABYLON.Tools.FloatRound(minMaxKeyFrames.min / animation.framePerSecond),
  2480. inputsMax: shouldBakeAnimation ? minMaxKeyFrames.max : BABYLON.Tools.FloatRound(minMaxKeyFrames.max / animation.framePerSecond)
  2481. };
  2482. return result;
  2483. }
  2484. return null;
  2485. };
  2486. _GLTFAnimation._DeduceAnimationInfo = function (animation) {
  2487. var animationChannelTargetPath = null;
  2488. var dataAccessorType = "VEC3" /* VEC3 */;
  2489. var useQuaternion = false;
  2490. var property = animation.targetProperty.split('.');
  2491. switch (property[0]) {
  2492. case 'scaling': {
  2493. animationChannelTargetPath = "scale" /* SCALE */;
  2494. break;
  2495. }
  2496. case 'position': {
  2497. animationChannelTargetPath = "translation" /* TRANSLATION */;
  2498. break;
  2499. }
  2500. case 'rotation': {
  2501. dataAccessorType = "VEC4" /* VEC4 */;
  2502. animationChannelTargetPath = "rotation" /* ROTATION */;
  2503. break;
  2504. }
  2505. case 'rotationQuaternion': {
  2506. dataAccessorType = "VEC4" /* VEC4 */;
  2507. useQuaternion = true;
  2508. animationChannelTargetPath = "rotation" /* ROTATION */;
  2509. break;
  2510. }
  2511. default: {
  2512. BABYLON.Tools.Error("Unsupported animatable property " + property[0]);
  2513. }
  2514. }
  2515. if (animationChannelTargetPath) {
  2516. return { animationChannelTargetPath: animationChannelTargetPath, dataAccessorType: dataAccessorType, useQuaternion: useQuaternion };
  2517. }
  2518. else {
  2519. BABYLON.Tools.Error('animation channel target path and data accessor type could be deduced');
  2520. }
  2521. return null;
  2522. };
  2523. /**
  2524. * @ignore
  2525. * Create node animations from the transform node animations
  2526. * @param babylonTransformNode
  2527. * @param runtimeGLTFAnimation
  2528. * @param idleGLTFAnimations
  2529. * @param nodeMap
  2530. * @param nodes
  2531. * @param binaryWriter
  2532. * @param bufferViews
  2533. * @param accessors
  2534. * @param convertToRightHandedSystem
  2535. */
  2536. _GLTFAnimation._CreateNodeAnimationFromTransformNodeAnimations = function (babylonTransformNode, runtimeGLTFAnimation, idleGLTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  2537. var glTFAnimation;
  2538. if (babylonTransformNode.animations) {
  2539. for (var _i = 0, _a = babylonTransformNode.animations; _i < _a.length; _i++) {
  2540. var animation = _a[_i];
  2541. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(animation);
  2542. if (animationInfo) {
  2543. glTFAnimation = {
  2544. name: animation.name,
  2545. samplers: [],
  2546. channels: []
  2547. };
  2548. _GLTFAnimation.AddAnimation("" + animation.name, animation.hasRunningRuntimeAnimations ? runtimeGLTFAnimation : glTFAnimation, babylonTransformNode, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  2549. if (glTFAnimation.samplers.length && glTFAnimation.channels.length) {
  2550. idleGLTFAnimations.push(glTFAnimation);
  2551. }
  2552. }
  2553. }
  2554. ;
  2555. }
  2556. };
  2557. /**
  2558. * @ignore
  2559. * Create node animations from the animation groups
  2560. * @param babylonScene
  2561. * @param glTFAnimations
  2562. * @param nodeMap
  2563. * @param nodes
  2564. * @param binaryWriter
  2565. * @param bufferViews
  2566. * @param accessors
  2567. * @param convertToRightHandedSystem
  2568. */
  2569. _GLTFAnimation._CreateNodeAnimationFromAnimationGroups = function (babylonScene, glTFAnimations, nodeMap, nodes, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationSampleRate) {
  2570. var glTFAnimation;
  2571. if (babylonScene.animationGroups) {
  2572. var animationGroups = babylonScene.animationGroups;
  2573. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  2574. var animationGroup = animationGroups_1[_i];
  2575. glTFAnimation = {
  2576. name: animationGroup.name,
  2577. channels: [],
  2578. samplers: []
  2579. };
  2580. for (var _a = 0, _b = animationGroup.targetedAnimations; _a < _b.length; _a++) {
  2581. var targetAnimation = _b[_a];
  2582. var target = targetAnimation.target;
  2583. var animation = targetAnimation.animation;
  2584. if (target instanceof BABYLON.Mesh || target.length === 1 && target[0] instanceof BABYLON.Mesh) { // TODO: Update to support bones
  2585. var animationInfo = _GLTFAnimation._DeduceAnimationInfo(targetAnimation.animation);
  2586. if (animationInfo) {
  2587. var babylonMesh = target instanceof BABYLON.Mesh ? target : target[0];
  2588. _GLTFAnimation.AddAnimation("" + animation.name, glTFAnimation, babylonMesh, animation, animationInfo.dataAccessorType, animationInfo.animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, animationInfo.useQuaternion, animationSampleRate);
  2589. }
  2590. }
  2591. }
  2592. ;
  2593. if (glTFAnimation.channels.length && glTFAnimation.samplers.length) {
  2594. glTFAnimations.push(glTFAnimation);
  2595. }
  2596. }
  2597. ;
  2598. }
  2599. };
  2600. _GLTFAnimation.AddAnimation = function (name, glTFAnimation, babylonTransformNode, animation, dataAccessorType, animationChannelTargetPath, nodeMap, binaryWriter, bufferViews, accessors, convertToRightHandedSystem, useQuaternion, animationSampleRate) {
  2601. var animationData = _GLTFAnimation._CreateNodeAnimation(babylonTransformNode, animation, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion, animationSampleRate);
  2602. var bufferView;
  2603. var accessor;
  2604. var keyframeAccessorIndex;
  2605. var dataAccessorIndex;
  2606. var outputLength;
  2607. var animationSampler;
  2608. var animationChannel;
  2609. if (animationData) {
  2610. var nodeIndex = nodeMap[babylonTransformNode.uniqueId];
  2611. // Creates buffer view and accessor for key frames.
  2612. var byteLength = animationData.inputs.length * 4;
  2613. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " keyframe data view");
  2614. bufferViews.push(bufferView);
  2615. animationData.inputs.forEach(function (input) {
  2616. binaryWriter.setFloat32(input);
  2617. });
  2618. accessor = GLTF2._GLTFUtilities.CreateAccessor(bufferViews.length - 1, name + " keyframes", "SCALAR" /* SCALAR */, 5126 /* FLOAT */, animationData.inputs.length, null, [animationData.inputsMin], [animationData.inputsMax]);
  2619. accessors.push(accessor);
  2620. keyframeAccessorIndex = accessors.length - 1;
  2621. // create bufferview and accessor for keyed values.
  2622. outputLength = animationData.outputs.length;
  2623. byteLength = dataAccessorType === "VEC3" /* VEC3 */ ? animationData.outputs.length * 12 : animationData.outputs.length * 16;
  2624. // check for in and out tangents
  2625. bufferView = GLTF2._GLTFUtilities.CreateBufferView(0, binaryWriter.getByteOffset(), byteLength, undefined, name + " data view");
  2626. bufferViews.push(bufferView);
  2627. animationData.outputs.forEach(function (output) {
  2628. output.forEach(function (entry) {
  2629. binaryWriter.setFloat32(entry);
  2630. });
  2631. });
  2632. accessor = GLTF2._GLTFUtilities.CreateAccessor(bufferViews.length - 1, name + " data", dataAccessorType, 5126 /* FLOAT */, outputLength, null, null, null);
  2633. accessors.push(accessor);
  2634. dataAccessorIndex = accessors.length - 1;
  2635. // create sampler
  2636. animationSampler = {
  2637. interpolation: animationData.samplerInterpolation,
  2638. input: keyframeAccessorIndex,
  2639. output: dataAccessorIndex
  2640. };
  2641. glTFAnimation.samplers.push(animationSampler);
  2642. // create channel
  2643. animationChannel = {
  2644. sampler: glTFAnimation.samplers.length - 1,
  2645. target: {
  2646. node: nodeIndex,
  2647. path: animationChannelTargetPath
  2648. }
  2649. };
  2650. glTFAnimation.channels.push(animationChannel);
  2651. }
  2652. };
  2653. /**
  2654. * Create a baked animation
  2655. * @param babylonTransformNode BabylonJS mesh
  2656. * @param animation BabylonJS animation corresponding to the BabylonJS mesh
  2657. * @param animationChannelTargetPath animation target channel
  2658. * @param minFrame minimum animation frame
  2659. * @param maxFrame maximum animation frame
  2660. * @param fps frames per second of the animation
  2661. * @param inputs input key frames of the animation
  2662. * @param outputs output key frame data of the animation
  2663. * @param convertToRightHandedSystem converts the values to right-handed
  2664. * @param useQuaternion specifies if quaternions should be used
  2665. */
  2666. _GLTFAnimation._CreateBakedAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, minFrame, maxFrame, fps, sampleRate, inputs, outputs, minMaxFrames, convertToRightHandedSystem, useQuaternion) {
  2667. var value;
  2668. var quaternionCache = BABYLON.Quaternion.Identity();
  2669. var previousTime = null;
  2670. var time;
  2671. var maxUsedFrame = null;
  2672. var currKeyFrame = null;
  2673. var nextKeyFrame = null;
  2674. var prevKeyFrame = null;
  2675. var endFrame = null;
  2676. minMaxFrames.min = BABYLON.Tools.FloatRound(minFrame / fps);
  2677. var keyFrames = animation.getKeys();
  2678. for (var i = 0, length_1 = keyFrames.length; i < length_1; ++i) {
  2679. endFrame = null;
  2680. currKeyFrame = keyFrames[i];
  2681. if (i + 1 < length_1) {
  2682. nextKeyFrame = keyFrames[i + 1];
  2683. if (currKeyFrame.value.equals(nextKeyFrame.value)) {
  2684. if (i === 0) { // set the first frame to itself
  2685. endFrame = currKeyFrame.frame;
  2686. }
  2687. else {
  2688. continue;
  2689. }
  2690. }
  2691. else {
  2692. endFrame = nextKeyFrame.frame;
  2693. }
  2694. }
  2695. else {
  2696. // at the last key frame
  2697. prevKeyFrame = keyFrames[i - 1];
  2698. if (currKeyFrame.value.equals(prevKeyFrame.value)) {
  2699. continue;
  2700. }
  2701. else {
  2702. endFrame = maxFrame;
  2703. }
  2704. }
  2705. if (endFrame) {
  2706. for (var f = currKeyFrame.frame; f <= endFrame; f += sampleRate) {
  2707. time = BABYLON.Tools.FloatRound(f / fps);
  2708. if (time === previousTime) {
  2709. continue;
  2710. }
  2711. previousTime = time;
  2712. maxUsedFrame = time;
  2713. value = animation._interpolate(f, 0, undefined, animation.loopMode);
  2714. _GLTFAnimation._SetInterpolatedValue(babylonTransformNode, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion);
  2715. }
  2716. }
  2717. }
  2718. if (maxUsedFrame) {
  2719. minMaxFrames.max = maxUsedFrame;
  2720. }
  2721. };
  2722. _GLTFAnimation._ConvertFactorToVector3OrQuaternion = function (factor, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  2723. var property;
  2724. var componentName;
  2725. var value = null;
  2726. var basePositionRotationOrScale = _GLTFAnimation._GetBasePositionRotationOrScale(babylonTransformNode, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  2727. if (animationType === BABYLON.Animation.ANIMATIONTYPE_FLOAT) { // handles single component x, y, z or w component animation by using a base property and animating over a component.
  2728. property = animation.targetProperty.split('.');
  2729. componentName = property ? property[1] : ''; // x, y, or z component
  2730. value = useQuaternion ? BABYLON.Quaternion.FromArray(basePositionRotationOrScale).normalize() : BABYLON.Vector3.FromArray(basePositionRotationOrScale);
  2731. switch (componentName) {
  2732. case 'x': {
  2733. value[componentName] = (convertToRightHandedSystem && useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2734. break;
  2735. }
  2736. case 'y': {
  2737. value[componentName] = (convertToRightHandedSystem && useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2738. break;
  2739. }
  2740. case 'z': {
  2741. value[componentName] = (convertToRightHandedSystem && !useQuaternion && (animationChannelTargetPath !== "scale" /* SCALE */)) ? -factor : factor;
  2742. break;
  2743. }
  2744. case 'w': {
  2745. value.w = factor;
  2746. break;
  2747. }
  2748. default: {
  2749. BABYLON.Tools.Error("glTFAnimation: Unsupported component type \"" + componentName + "\" for scale animation!");
  2750. }
  2751. }
  2752. }
  2753. return value;
  2754. };
  2755. _GLTFAnimation._SetInterpolatedValue = function (babylonTransformNode, value, time, animation, animationChannelTargetPath, quaternionCache, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2756. var animationType = animation.dataType;
  2757. var cacheValue;
  2758. inputs.push(time);
  2759. if (typeof value === "number") {
  2760. value = this._ConvertFactorToVector3OrQuaternion(value, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  2761. }
  2762. if (value) {
  2763. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2764. if (useQuaternion) {
  2765. quaternionCache = value;
  2766. }
  2767. else {
  2768. cacheValue = value;
  2769. BABYLON.Quaternion.RotationYawPitchRollToRef(cacheValue.y, cacheValue.x, cacheValue.z, quaternionCache);
  2770. }
  2771. if (convertToRightHandedSystem) {
  2772. GLTF2._GLTFUtilities.GetRightHandedQuaternionFromRef(quaternionCache);
  2773. if (!babylonTransformNode.parent) {
  2774. quaternionCache = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(quaternionCache);
  2775. }
  2776. }
  2777. outputs.push(quaternionCache.asArray());
  2778. }
  2779. else {
  2780. cacheValue = value;
  2781. if (convertToRightHandedSystem && (animationChannelTargetPath !== "scale" /* SCALE */)) {
  2782. GLTF2._GLTFUtilities.GetRightHandedPositionVector3FromRef(cacheValue);
  2783. if (!babylonTransformNode.parent) {
  2784. cacheValue.x *= -1;
  2785. cacheValue.z *= -1;
  2786. }
  2787. }
  2788. outputs.push(cacheValue.asArray());
  2789. }
  2790. }
  2791. };
  2792. /**
  2793. * Creates linear animation from the animation key frames
  2794. * @param babylonTransformNode BabylonJS mesh
  2795. * @param animation BabylonJS animation
  2796. * @param animationChannelTargetPath The target animation channel
  2797. * @param frameDelta The difference between the last and first frame of the animation
  2798. * @param inputs Array to store the key frame times
  2799. * @param outputs Array to store the key frame data
  2800. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  2801. * @param useQuaternion Specifies if quaternions are used in the animation
  2802. */
  2803. _GLTFAnimation._CreateLinearOrStepAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2804. for (var _i = 0, _a = animation.getKeys(); _i < _a.length; _i++) {
  2805. var keyFrame = _a[_i];
  2806. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  2807. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion);
  2808. }
  2809. ;
  2810. };
  2811. /**
  2812. * Creates cubic spline animation from the animation key frames
  2813. * @param babylonTransformNode BabylonJS mesh
  2814. * @param animation BabylonJS animation
  2815. * @param animationChannelTargetPath The target animation channel
  2816. * @param frameDelta The difference between the last and first frame of the animation
  2817. * @param inputs Array to store the key frame times
  2818. * @param outputs Array to store the key frame data
  2819. * @param convertToRightHandedSystem Specifies if the position data should be converted to right handed
  2820. * @param useQuaternion Specifies if quaternions are used in the animation
  2821. */
  2822. _GLTFAnimation._CreateCubicSplineAnimation = function (babylonTransformNode, animation, animationChannelTargetPath, frameDelta, inputs, outputs, convertToRightHandedSystem, useQuaternion) {
  2823. animation.getKeys().forEach(function (keyFrame) {
  2824. inputs.push(keyFrame.frame / animation.framePerSecond); // keyframes in seconds.
  2825. _GLTFAnimation.AddSplineTangent(babylonTransformNode, _TangentType.INTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  2826. _GLTFAnimation._AddKeyframeValue(keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion);
  2827. _GLTFAnimation.AddSplineTangent(babylonTransformNode, _TangentType.OUTTANGENT, outputs, animationChannelTargetPath, "CUBICSPLINE" /* CUBICSPLINE */, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem);
  2828. });
  2829. };
  2830. _GLTFAnimation._GetBasePositionRotationOrScale = function (babylonTransformNode, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion) {
  2831. var basePositionRotationOrScale;
  2832. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2833. if (useQuaternion) {
  2834. if (babylonTransformNode.rotationQuaternion) {
  2835. basePositionRotationOrScale = babylonTransformNode.rotationQuaternion.asArray();
  2836. if (convertToRightHandedSystem) {
  2837. GLTF2._GLTFUtilities.GetRightHandedQuaternionArrayFromRef(basePositionRotationOrScale);
  2838. if (!babylonTransformNode.parent) {
  2839. basePositionRotationOrScale = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(basePositionRotationOrScale)).asArray();
  2840. }
  2841. }
  2842. }
  2843. else {
  2844. basePositionRotationOrScale = BABYLON.Quaternion.Identity().asArray();
  2845. }
  2846. }
  2847. else {
  2848. basePositionRotationOrScale = babylonTransformNode.rotation.asArray();
  2849. GLTF2._GLTFUtilities.GetRightHandedNormalArray3FromRef(basePositionRotationOrScale);
  2850. }
  2851. }
  2852. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  2853. basePositionRotationOrScale = babylonTransformNode.position.asArray();
  2854. if (convertToRightHandedSystem) {
  2855. GLTF2._GLTFUtilities.GetRightHandedPositionArray3FromRef(basePositionRotationOrScale);
  2856. }
  2857. }
  2858. else { // scale
  2859. basePositionRotationOrScale = babylonTransformNode.scaling.asArray();
  2860. }
  2861. return basePositionRotationOrScale;
  2862. };
  2863. /**
  2864. * Adds a key frame value
  2865. * @param keyFrame
  2866. * @param animation
  2867. * @param outputs
  2868. * @param animationChannelTargetPath
  2869. * @param basePositionRotationOrScale
  2870. * @param convertToRightHandedSystem
  2871. * @param useQuaternion
  2872. */
  2873. _GLTFAnimation._AddKeyframeValue = function (keyFrame, animation, outputs, animationChannelTargetPath, babylonTransformNode, convertToRightHandedSystem, useQuaternion) {
  2874. var value;
  2875. var newPositionRotationOrScale;
  2876. var animationType = animation.dataType;
  2877. if (animationType === BABYLON.Animation.ANIMATIONTYPE_VECTOR3) {
  2878. value = keyFrame.value.asArray();
  2879. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2880. var array = BABYLON.Vector3.FromArray(value);
  2881. var rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(array.y, array.x, array.z);
  2882. if (convertToRightHandedSystem) {
  2883. GLTF2._GLTFUtilities.GetRightHandedQuaternionFromRef(rotationQuaternion);
  2884. if (!babylonTransformNode.parent) {
  2885. rotationQuaternion = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(rotationQuaternion);
  2886. }
  2887. }
  2888. value = rotationQuaternion.asArray();
  2889. }
  2890. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  2891. if (convertToRightHandedSystem) {
  2892. GLTF2._GLTFUtilities.GetRightHandedNormalArray3FromRef(value);
  2893. if (!babylonTransformNode.parent) {
  2894. value[0] *= -1;
  2895. value[2] *= -1;
  2896. }
  2897. }
  2898. }
  2899. outputs.push(value); // scale vector.
  2900. }
  2901. else if (animationType === BABYLON.Animation.ANIMATIONTYPE_FLOAT) { // handles single component x, y, z or w component animation by using a base property and animating over a component.
  2902. newPositionRotationOrScale = this._ConvertFactorToVector3OrQuaternion(keyFrame.value, babylonTransformNode, animation, animationType, animationChannelTargetPath, convertToRightHandedSystem, useQuaternion);
  2903. if (newPositionRotationOrScale) {
  2904. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  2905. var posRotScale = useQuaternion ? newPositionRotationOrScale : BABYLON.Quaternion.RotationYawPitchRoll(newPositionRotationOrScale.y, newPositionRotationOrScale.x, newPositionRotationOrScale.z).normalize();
  2906. if (convertToRightHandedSystem) {
  2907. GLTF2._GLTFUtilities.GetRightHandedQuaternionFromRef(posRotScale);
  2908. if (!babylonTransformNode.parent) {
  2909. posRotScale = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(posRotScale);
  2910. }
  2911. }
  2912. outputs.push(posRotScale.asArray());
  2913. }
  2914. else if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  2915. if (convertToRightHandedSystem) {
  2916. GLTF2._GLTFUtilities.GetRightHandedNormalVector3FromRef(newPositionRotationOrScale);
  2917. if (!babylonTransformNode.parent) {
  2918. newPositionRotationOrScale.x *= -1;
  2919. newPositionRotationOrScale.z *= -1;
  2920. }
  2921. }
  2922. }
  2923. outputs.push(newPositionRotationOrScale.asArray());
  2924. }
  2925. }
  2926. else if (animationType === BABYLON.Animation.ANIMATIONTYPE_QUATERNION) {
  2927. value = keyFrame.value.normalize().asArray();
  2928. if (convertToRightHandedSystem) {
  2929. GLTF2._GLTFUtilities.GetRightHandedQuaternionArrayFromRef(value);
  2930. if (!babylonTransformNode.parent) {
  2931. value = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(value)).asArray();
  2932. }
  2933. }
  2934. outputs.push(value);
  2935. }
  2936. else {
  2937. BABYLON.Tools.Error('glTFAnimation: Unsupported key frame values for animation!');
  2938. }
  2939. };
  2940. /**
  2941. * Determine the interpolation based on the key frames
  2942. * @param keyFrames
  2943. * @param animationChannelTargetPath
  2944. * @param useQuaternion
  2945. */
  2946. _GLTFAnimation._DeduceInterpolation = function (keyFrames, animationChannelTargetPath, useQuaternion) {
  2947. var interpolationType;
  2948. var shouldBakeAnimation = false;
  2949. var key;
  2950. if (animationChannelTargetPath === "rotation" /* ROTATION */ && !useQuaternion) {
  2951. return { interpolationType: "LINEAR" /* LINEAR */, shouldBakeAnimation: true };
  2952. }
  2953. for (var i = 0, length_2 = keyFrames.length; i < length_2; ++i) {
  2954. key = keyFrames[i];
  2955. if (key.inTangent || key.outTangent) {
  2956. if (interpolationType) {
  2957. if (interpolationType !== "CUBICSPLINE" /* CUBICSPLINE */) {
  2958. interpolationType = "LINEAR" /* LINEAR */;
  2959. shouldBakeAnimation = true;
  2960. break;
  2961. }
  2962. }
  2963. else {
  2964. interpolationType = "CUBICSPLINE" /* CUBICSPLINE */;
  2965. }
  2966. }
  2967. else {
  2968. if (interpolationType) {
  2969. if (interpolationType === "CUBICSPLINE" /* CUBICSPLINE */ ||
  2970. (key.interpolation && (key.interpolation === BABYLON.AnimationKeyInterpolation.STEP) && interpolationType !== "STEP" /* STEP */)) {
  2971. interpolationType = "LINEAR" /* LINEAR */;
  2972. shouldBakeAnimation = true;
  2973. break;
  2974. }
  2975. }
  2976. else {
  2977. if (key.interpolation && (key.interpolation === BABYLON.AnimationKeyInterpolation.STEP)) {
  2978. interpolationType = "STEP" /* STEP */;
  2979. }
  2980. else {
  2981. interpolationType = "LINEAR" /* LINEAR */;
  2982. }
  2983. }
  2984. }
  2985. }
  2986. if (!interpolationType) {
  2987. interpolationType = "LINEAR" /* LINEAR */;
  2988. }
  2989. return { interpolationType: interpolationType, shouldBakeAnimation: shouldBakeAnimation };
  2990. };
  2991. /**
  2992. * Adds an input tangent or output tangent to the output data
  2993. * If an input tangent or output tangent is missing, it uses the zero vector or zero quaternion
  2994. * @param tangentType Specifies which type of tangent to handle (inTangent or outTangent)
  2995. * @param outputs The animation data by keyframe
  2996. * @param animationChannelTargetPath The target animation channel
  2997. * @param interpolation The interpolation type
  2998. * @param keyFrame The key frame with the animation data
  2999. * @param frameDelta Time difference between two frames used to scale the tangent by the frame delta
  3000. * @param useQuaternion Specifies if quaternions are used
  3001. * @param convertToRightHandedSystem Specifies if the values should be converted to right-handed
  3002. */
  3003. _GLTFAnimation.AddSplineTangent = function (babylonTransformNode, tangentType, outputs, animationChannelTargetPath, interpolation, keyFrame, frameDelta, useQuaternion, convertToRightHandedSystem) {
  3004. var tangent;
  3005. var tangentValue = tangentType === _TangentType.INTANGENT ? keyFrame.inTangent : keyFrame.outTangent;
  3006. if (interpolation === "CUBICSPLINE" /* CUBICSPLINE */) {
  3007. if (animationChannelTargetPath === "rotation" /* ROTATION */) {
  3008. if (tangentValue) {
  3009. if (useQuaternion) {
  3010. tangent = tangentValue.scale(frameDelta).asArray();
  3011. }
  3012. else {
  3013. var array = tangentValue.scale(frameDelta);
  3014. tangent = BABYLON.Quaternion.RotationYawPitchRoll(array.y, array.x, array.z).asArray();
  3015. }
  3016. if (convertToRightHandedSystem) {
  3017. GLTF2._GLTFUtilities.GetRightHandedQuaternionArrayFromRef(tangent);
  3018. if (!babylonTransformNode.parent) {
  3019. tangent = BABYLON.Quaternion.FromArray([0, 1, 0, 0]).multiply(BABYLON.Quaternion.FromArray(tangent)).asArray();
  3020. }
  3021. }
  3022. }
  3023. else {
  3024. tangent = [0, 0, 0, 0];
  3025. }
  3026. }
  3027. else {
  3028. if (tangentValue) {
  3029. tangent = tangentValue.scale(frameDelta).asArray();
  3030. if (convertToRightHandedSystem) {
  3031. if (animationChannelTargetPath === "translation" /* TRANSLATION */) {
  3032. GLTF2._GLTFUtilities.GetRightHandedPositionArray3FromRef(tangent);
  3033. if (!babylonTransformNode.parent) {
  3034. tangent[0] *= -1; // x
  3035. tangent[2] *= -1; // z
  3036. }
  3037. }
  3038. }
  3039. }
  3040. else {
  3041. tangent = [0, 0, 0];
  3042. }
  3043. }
  3044. outputs.push(tangent);
  3045. }
  3046. };
  3047. /**
  3048. * Get the minimum and maximum key frames' frame values
  3049. * @param keyFrames animation key frames
  3050. * @returns the minimum and maximum key frame value
  3051. */
  3052. _GLTFAnimation.calculateMinMaxKeyFrames = function (keyFrames) {
  3053. var min = Infinity;
  3054. var max = -Infinity;
  3055. keyFrames.forEach(function (keyFrame) {
  3056. min = Math.min(min, keyFrame.frame);
  3057. max = Math.max(max, keyFrame.frame);
  3058. });
  3059. return { min: min, max: max };
  3060. };
  3061. return _GLTFAnimation;
  3062. }());
  3063. GLTF2._GLTFAnimation = _GLTFAnimation;
  3064. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3065. })(BABYLON || (BABYLON = {}));
  3066. //# sourceMappingURL=babylon.glTFAnimation.js.map
  3067. /// <reference path="../../../../dist/preview release/gltf2Interface/babylon.glTF2Interface.d.ts"/>
  3068. var BABYLON;
  3069. (function (BABYLON) {
  3070. var GLTF2;
  3071. (function (GLTF2) {
  3072. /**
  3073. * @hidden
  3074. */
  3075. var _GLTFUtilities = /** @class */ (function () {
  3076. function _GLTFUtilities() {
  3077. }
  3078. /**
  3079. * Creates a buffer view based on the supplied arguments
  3080. * @param bufferIndex index value of the specified buffer
  3081. * @param byteOffset byte offset value
  3082. * @param byteLength byte length of the bufferView
  3083. * @param byteStride byte distance between conequential elements
  3084. * @param name name of the buffer view
  3085. * @returns bufferView for glTF
  3086. */
  3087. _GLTFUtilities.CreateBufferView = function (bufferIndex, byteOffset, byteLength, byteStride, name) {
  3088. var bufferview = { buffer: bufferIndex, byteLength: byteLength };
  3089. if (byteOffset) {
  3090. bufferview.byteOffset = byteOffset;
  3091. }
  3092. if (name) {
  3093. bufferview.name = name;
  3094. }
  3095. if (byteStride) {
  3096. bufferview.byteStride = byteStride;
  3097. }
  3098. return bufferview;
  3099. };
  3100. /**
  3101. * Creates an accessor based on the supplied arguments
  3102. * @param bufferviewIndex The index of the bufferview referenced by this accessor
  3103. * @param name The name of the accessor
  3104. * @param type The type of the accessor
  3105. * @param componentType The datatype of components in the attribute
  3106. * @param count The number of attributes referenced by this accessor
  3107. * @param byteOffset The offset relative to the start of the bufferView in bytes
  3108. * @param min Minimum value of each component in this attribute
  3109. * @param max Maximum value of each component in this attribute
  3110. * @returns accessor for glTF
  3111. */
  3112. _GLTFUtilities.CreateAccessor = function (bufferviewIndex, name, type, componentType, count, byteOffset, min, max) {
  3113. var accessor = { name: name, bufferView: bufferviewIndex, componentType: componentType, count: count, type: type };
  3114. if (min != null) {
  3115. accessor.min = min;
  3116. }
  3117. if (max != null) {
  3118. accessor.max = max;
  3119. }
  3120. if (byteOffset != null) {
  3121. accessor.byteOffset = byteOffset;
  3122. }
  3123. return accessor;
  3124. };
  3125. /**
  3126. * Calculates the minimum and maximum values of an array of position floats
  3127. * @param positions Positions array of a mesh
  3128. * @param vertexStart Starting vertex offset to calculate min and max values
  3129. * @param vertexCount Number of vertices to check for min and max values
  3130. * @returns min number array and max number array
  3131. */
  3132. _GLTFUtilities.CalculateMinMaxPositions = function (positions, vertexStart, vertexCount, convertToRightHandedSystem) {
  3133. var min = [Infinity, Infinity, Infinity];
  3134. var max = [-Infinity, -Infinity, -Infinity];
  3135. var positionStrideSize = 3;
  3136. var indexOffset;
  3137. var position;
  3138. var vector;
  3139. if (vertexCount) {
  3140. for (var i = vertexStart, length_1 = vertexStart + vertexCount; i < length_1; ++i) {
  3141. indexOffset = positionStrideSize * i;
  3142. position = BABYLON.Vector3.FromArray(positions, indexOffset);
  3143. if (convertToRightHandedSystem) {
  3144. _GLTFUtilities.GetRightHandedPositionVector3FromRef(position);
  3145. }
  3146. vector = position.asArray();
  3147. for (var j = 0; j < positionStrideSize; ++j) {
  3148. var num = vector[j];
  3149. if (num < min[j]) {
  3150. min[j] = num;
  3151. }
  3152. if (num > max[j]) {
  3153. max[j] = num;
  3154. }
  3155. ++indexOffset;
  3156. }
  3157. }
  3158. }
  3159. return { min: min, max: max };
  3160. };
  3161. /**
  3162. * Converts a new right-handed Vector3
  3163. * @param vector vector3 array
  3164. * @returns right-handed Vector3
  3165. */
  3166. _GLTFUtilities.GetRightHandedPositionVector3 = function (vector) {
  3167. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  3168. };
  3169. /**
  3170. * Converts a Vector3 to right-handed
  3171. * @param vector Vector3 to convert to right-handed
  3172. */
  3173. _GLTFUtilities.GetRightHandedPositionVector3FromRef = function (vector) {
  3174. vector.z *= -1;
  3175. };
  3176. /**
  3177. * Converts a three element number array to right-handed
  3178. * @param vector number array to convert to right-handed
  3179. */
  3180. _GLTFUtilities.GetRightHandedPositionArray3FromRef = function (vector) {
  3181. vector[2] *= -1;
  3182. };
  3183. /**
  3184. * Converts a new right-handed Vector3
  3185. * @param vector vector3 array
  3186. * @returns right-handed Vector3
  3187. */
  3188. _GLTFUtilities.GetRightHandedNormalVector3 = function (vector) {
  3189. return new BABYLON.Vector3(vector.x, vector.y, -vector.z);
  3190. };
  3191. /**
  3192. * Converts a Vector3 to right-handed
  3193. * @param vector Vector3 to convert to right-handed
  3194. */
  3195. _GLTFUtilities.GetRightHandedNormalVector3FromRef = function (vector) {
  3196. vector.z *= -1;
  3197. };
  3198. /**
  3199. * Converts a three element number array to right-handed
  3200. * @param vector number array to convert to right-handed
  3201. */
  3202. _GLTFUtilities.GetRightHandedNormalArray3FromRef = function (vector) {
  3203. vector[2] *= -1;
  3204. };
  3205. /**
  3206. * Converts a Vector4 to right-handed
  3207. * @param vector Vector4 to convert to right-handed
  3208. */
  3209. _GLTFUtilities.GetRightHandedVector4FromRef = function (vector) {
  3210. vector.z *= -1;
  3211. vector.w *= -1;
  3212. };
  3213. /**
  3214. * Converts a Vector4 to right-handed
  3215. * @param vector Vector4 to convert to right-handed
  3216. */
  3217. _GLTFUtilities.GetRightHandedArray4FromRef = function (vector) {
  3218. vector[2] *= -1;
  3219. vector[3] *= -1;
  3220. };
  3221. /**
  3222. * Converts a Quaternion to right-handed
  3223. * @param quaternion Source quaternion to convert to right-handed
  3224. */
  3225. _GLTFUtilities.GetRightHandedQuaternionFromRef = function (quaternion) {
  3226. quaternion.x *= -1;
  3227. quaternion.y *= -1;
  3228. };
  3229. /**
  3230. * Converts a Quaternion to right-handed
  3231. * @param quaternion Source quaternion to convert to right-handed
  3232. */
  3233. _GLTFUtilities.GetRightHandedQuaternionArrayFromRef = function (quaternion) {
  3234. quaternion[0] *= -1;
  3235. quaternion[1] *= -1;
  3236. };
  3237. return _GLTFUtilities;
  3238. }());
  3239. GLTF2._GLTFUtilities = _GLTFUtilities;
  3240. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  3241. })(BABYLON || (BABYLON = {}));
  3242. //# sourceMappingURL=babylon.glTFUtilities.js.map