babylonjs.serializers.js 222 KB

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