babylonjs.serializers.js 194 KB

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