babylonjs.serializers.js 222 KB

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