/*
All material copyright ESRI, All Rights Reserved, unless otherwise specified.
See https://js.arcgis.com/4.24/esri/copyright.txt for details.
*/
define(["./RectangleBinPack","../webgl/Rect","../../../webgl/enums","../../../webgl/Texture"],(function(t,e,i,s){"use strict";return function(){function h(e,i,s){this.width=0,this.height=0,this._dirties=[],this._glyphData=[],this._currentPage=0,this._glyphIndex={},this._textures=[],this._rangePromises=new Map,this.width=e,this.height=i,this._glyphSource=s,this._binPack=new t(e-4,i-4),this._glyphData.push(new Uint8Array(e*i)),this._dirties.push(!0),this._textures.push(void 0)}var n=h.prototype;return n.getGlyphItems=function(i,s){const h=[],n=this._glyphSource,r=new Set,a=1/256;for(const t of s){const e=Math.floor(t*a);r.add(e)}const o=[];return r.forEach((t=>{if(t<=256){const e=i+t;if(this._rangePromises.has(e))o.push(this._rangePromises.get(e));else{const s=n.getRange(i,t).then((()=>{this._rangePromises.delete(e)}),(()=>{this._rangePromises.delete(e)}));this._rangePromises.set(e,s),o.push(s)}}})),Promise.all(o).then((()=>{let r=this._glyphIndex[i];r||(r={},this._glyphIndex[i]=r);for(const a of s){const s=r[a];if(s){h[a]={sdf:!0,rect:s.rect,metrics:s.metrics,page:s.page,code:a};continue}const o=n.getGlyph(i,a);if(!o||!o.metrics)continue;const c=o.metrics;let l;if(0===c.width)l=new e(0,0,0,0);else{const e=3,i=c.width+2*e,s=c.height+2*e;let h=i%4?4-i%4:4,n=s%4?4-s%4:4;1===h&&(h=5),1===n&&(n=5),l=this._binPack.allocate(i+h,s+n),l.isEmpty&&(this._dirties[this._currentPage]||(this._glyphData[this._currentPage]=null),this._currentPage=this._glyphData.length,this._glyphData.push(new Uint8Array(this.width*this.height)),this._dirties.push(!0),this._textures.push(void 0),this._binPack=new t(this.width-4,this.height-4),l=this._binPack.allocate(i+h,s+n));const r=this._glyphData[this._currentPage],a=o.bitmap;let g,_;if(a)for(let t=0;t<s;t++){g=i*t,_=this.width*(l.y+t+1)+l.x;for(let t=0;t<i;t++)r[_+t+1]=a[g+t]}}r[a]={rect:l,metrics:c,tileIDs:null,page:this._currentPage},h[a]={sdf:!0,rect:l,metrics:c,page:this._currentPage,code:a},this._dirties[this._currentPage]=!0}return h}))},n.removeGlyphs=function(t){for(const e in this._glyphIndex){const i=this._glyphIndex[e];if(!i)continue;let s;for(const e in i)if(s=i[e],s.tileIDs.delete(t),0===s.tileIDs.size){const t=this._glyphData[s.page],h=s.rect;let n,r;for(let e=0;e<h.height;e++)for(n=this.width*(h.y+e)+h.x,r=0;r<h.width;r++)t[n+r]=0;delete i[e],this._dirties[s.page]=!0}}},n.bind=function(t,e,h,n=0){this._textures[h]||(this._textures[h]=new s.Texture(t,{pixelFormat:i.PixelFormat.ALPHA,dataType:i.PixelType.UNSIGNED_BYTE,width:this.width,height:this.height},new Uint8Array(this.width*this.height)));const r=this._textures[h];r.setSamplingMode(e),this._dirties[h]&&r.setData(this._glyphData[h]),t.bindTexture(r,n),this._dirties[h]=!1},n.dispose=function(){this._binPack=null;for(const t of this._textures)t&&t.dispose();this._textures.length=0},h}()}));
