/* COPYRIGHT Esri - https://js.arcgis.com/5.0.18/LICENSE.txt */
import{getBasisTranscoder as e}from"../../../../libs/basisu/BasisUTranscoder.js";import{CompressedTextureFormat as t}from"../../../webgl/enums.js";import n from"../../../webgl/Texture.js";import{getFormatBytesPerElement as s}from"../../../webgl/Util.js";let r=null,i=null;async function a(){return null==i&&(i=e(),r=await i),i}function l(e,t){if(null==r)return e.byteLength;const n=new r.BasisFile(new Uint8Array(e)),s=u(n)?o(n.getNumLevels(0),n.getHasAlpha(),n.getImageWidth(0,0),n.getImageHeight(0,0),t):0;return n.close(),n.delete(),s}function g(e,t){if(null==r)return e.byteLength;const n=new r.KTX2File(new Uint8Array(e)),s=c(n)?o(n.getLevels(),n.getHasAlpha(),n.getWidth(),n.getHeight(),t):0;return n.close(),n.delete(),s}function o(e,n,r,i,a){const l=s(n?t.COMPRESSED_RGBA8_ETC2_EAC:t.COMPRESSED_RGB8_ETC2),g=a&&e>1?(4**e-1)/(3*4**(e-1)):1;return Math.ceil(r*i*l*g)}function u(e){return e.getNumImages()>=1&&!e.isUASTC()}function c(e){return e.getFaces()>=1&&e.isETC1S()}async function m(e,t,n){null==r&&(r=await a());const s=new r.BasisFile(new Uint8Array(n));if(!u(s))return null;s.startTranscoding();const i=T(e,t,s.getNumLevels(0),s.getHasAlpha(),s.getImageWidth(0,0),s.getImageHeight(0,0),(e,t)=>s.getImageTranscodedSizeInBytes(0,e,t),(e,t,n)=>s.transcodeImage(n,0,e,t,0,0));return s.close(),s.delete(),i}async function h(e,t,n){null==r&&(r=await a());const s=new r.KTX2File(new Uint8Array(n));if(!c(s))return null;s.startTranscoding();const i=T(e,t,s.getLevels(),s.getHasAlpha(),s.getWidth(),s.getHeight(),(e,t)=>s.getImageTranscodedSizeInBytes(e,0,0,t),(e,t,n)=>s.transcodeImage(n,e,0,0,t,0,-1,-1));return s.close(),s.delete(),i}function T(e,s,r,i,a,l,g,o){const{compressedTextureETC:u,compressedTextureS3TC:c}=e.capabilities,[m,h]=u?i?[1,t.COMPRESSED_RGBA8_ETC2_EAC]:[0,t.COMPRESSED_RGB8_ETC2]:c?i?[3,t.COMPRESSED_RGBA_S3TC_DXT5_EXT]:[2,t.COMPRESSED_RGB_S3TC_DXT1_EXT]:[13,6408],T=s.hasMipmap?r:Math.min(1,r),d=[];for(let t=0;t<T;t++)d.push(new Uint8Array(g(t,m))),o(t,m,d[t]);return s.internalFormat=h,s.hasMipmap=d.length>1,s.samplingMode=s.hasMipmap?9987:9729,s.width=a,s.height=l,new n(e,s,{type:"compressed",levels:d})}export{c as checkKTX2,m as createTextureBasis,h as createTextureKTX2,l as estimateMemoryBasis,g as estimateMemoryKTX2,a as loadBasisTranscoder};
