UNPKG

webgl-dsl

Version:

Thin functional WebGL wrapper with strong typed GLSL DSL

19 lines (18 loc) 29 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=(()=>{let r=0;return function(){return r++}})();exports.Type=(r=>(r.Scalar="float",r.Vector2="vec2",r.Matrix2="mat2",r.Vector3="vec3",r.Matrix3="mat3",r.Vector4="vec4",r.Matrix4="mat4",r.Boolean="bool",r.Sampler="sampler2D",r))(exports.Type||{});var re=(r=>(r.High="highp",r.Medium="mediump",r.Low="lowp",r))(re||{});(r=>{function e(a){switch(a){case"bool":case"float":case"sampler2D":return 1;case"vec2":case"mat2":return 2;case"vec3":case"mat3":return 3;case"vec4":case"mat4":return 4}}r.size=e;function t(a){switch(a){case 2:return"vec2";case 3:return"vec3";case 4:return"vec4"}}r.vector=t;function s(a){switch(a){case 1:return"float";case 2:return"vec2";case 3:return"vec3";case 4:return"vec4"}}r.numeric=s;function n(a){return a==="vec2"||a==="vec3"||a==="vec4"}r.isVector=n;function i(a){return a==="mat2"||a==="mat3"||a==="mat4"}r.isMatrix=i})(exports.Type||(exports.Type={}));class w{constructor(e=new Map){this.cache=e,this.global="",this.local=""}once(e,t){if(this.cache.has(e))return this.cache.get(e);{const s=t();return this.cache.set(e,s),s}}getGlobal(){return this.global}addGlobal(e){return this.global+=e,this}getLocal(){return this.local}addLocal(e){return this.local+=e,this}child(){return new w(this.cache)}}const Te="==+-*/<><=>=!&&||",o=class o{constructor(e){this.getValue=e}static call(e,t,s){const n=Te.indexOf(e)!==-1,i=t.map(a=>typeof a=="number"?E(a):a);return t.length===2&&n?new o(a=>{const h=i.map(c=>c.getValue(a));return{type:s(h.map(c=>c.type)),content:`((${h[0].content}) ${e} (${h[1].content}))`}}):new o(a=>{const h=i.map(c=>c.getValue(a));return{type:s(h.map(c=>c.type)),content:`${e}(${h.map(c=>c.content).join(", ")})`}})}unary(e){return o.call(e,[this],t=>t[0])}sin(){return this.unary("sin")}cos(){return this.unary("cos")}radians(){return this.unary("radians")}degrees(){return this.unary("degrees")}tan(){return this.unary("tan")}asin(){return this.unary("asin")}acos(){return this.unary("acos")}exp(){return this.unary("exp")}log(){return this.unary("log")}exp2(){return this.unary("exp2")}log2(){return this.unary("log2")}sqrt(){return this.unary("sqrt")}inversesqrt(){return this.unary("inversesqrt")}abs(){return this.unary("abs")}sign(){return this.unary("sign")}floor(){return this.unary("floor")}ceil(){return this.unary("ceil")}fract(){return this.unary("fract")}normalize(){return this.unary("normalize")}round(){return this.add(.5).floor()}not(){return this.unary("!")}atan(e){return e===void 0?o.call("atan",[this],([t])=>t):o.call("atan",[this,e],t=>t[0])}pow(e){const t=typeof e=="number"?E(e):e;return o.call("pow",[this,t],([s])=>s)}mod(e){const t=typeof e=="number"?E(e):e;return o.call("mod",[this,t],([s])=>s)}min(e){const t=typeof e=="number"?E(e):e;return o.call("min",[this,t],([s])=>s)}max(e){return o.call("max",[this,e],([t])=>t)}mix(e,t){return o.call("mix",[this,e,t],([s])=>s)}clamp(e,t){return o.call("clamp",[this,e,t],([s])=>s)}smoothstep(e,t){return o.call("smoothstep",[e,t,this],([s])=>s)}length(){return o.call("length",[this],()=>"float")}distance(e){return o.call("distance",[this,e],()=>"float")}dot(e){return o.call("dot",[this,e],()=>"float")}reflect(e){return o.call("reflect",[this,e],([t])=>t)}refract(e,t){return o.call("refract",[this,e,t],([s])=>s)}texture2D(e){return o.call("texture2D",[this,e],()=>"vec4")}add(e){return o.call("+",[this,e],([t,s])=>t==="float"?s:t)}sub(e){return o.call("-",[this,e],([t,s])=>t==="float"?s:t)}div(e){return o.call("/",[this,e],([t,s])=>t==="float"?s:t)}mul(e){return o.call("*",[this,e],([t,s])=>t==="float"||t===s?s:s==="float"||exports.Type.isVector(t)?t:exports.Type.isVector(s)?s:t)}bool(e,t){return o.call(e,[this,t],()=>"bool")}lt(e){return this.bool("<",e)}gt(e){return this.bool(">",e)}lte(e){return this.bool("<=",e)}gte(e){return this.bool(">=",e)}eq(e){return this.bool("==",e)}neq(e){return this.bool("!=",e)}and(e){return o.call("&&",[this,e],()=>"bool")}or(e){return o.call("||",[this,e],()=>"bool")}mem(e){const t=`mem${D()}`;return new o(s=>{const n=this.getValue(s);return s.once(t,()=>{const i=n.type!=="bool";s.addLocal(`${i?`${e} `:""}${n.type} ${t} = ${n.content}; `)}),{type:n.type,content:t}})}memHQ(){return this.mem("highp")}memMQ(){return this.mem("mediump")}memLQ(){return this.mem("lowp")}cond(e,t,s){const n=`cond${D()}`;let i=null;return new o(a=>(a.once(n,()=>{const h=this.getValue(a),c=a.child(),u=t.getValue(c),d=a.child(),f=s.getValue(d);i=u.type,a.addGlobal(c.getGlobal()).addGlobal(d.getGlobal()),a.addLocal(`${u.type!=="bool"?e+" ":""}${u.type} ${n}; `).addLocal(`if (${h.content}) { `).addLocal(c.getLocal()).addLocal(`${n} = ${u.content}; `).addLocal(`} else { `).addLocal(d.getLocal()).addLocal(`${n} = ${f.content}; `).addLocal(`} `)}),{type:i,content:n}))}condHQ(e,t){return this.cond("highp",e,t)}condMQ(e,t){return this.cond("mediump",e,t)}condLQ(e,t){return this.cond("lowp",e,t)}take(e,t,s,n){return new o(i=>{const a=[e,t,s,n].filter(c=>c!==void 0),h=this.getValue(i);return{type:a.length===1?"float":exports.Type.vector(a.length),content:`(${h.content}).${a.map(c=>"xyzw".charAt(c)).join("")}`}})}vec2(){return new o(e=>({type:"vec2",content:`vec2(${this.getValue(e).content})`}))}vec3(){return new o(e=>({type:"vec3",content:`vec3(${this.getValue(e).content})`}))}vec4(){return new o(e=>({type:"vec4",content:`vec4(${this.getValue(e).content})`}))}x(){return this.take(0)}y(){return this.take(1)}z(){return this.take(2)}w(){return this.take(3)}r(){return this.take(0)}g(){return this.take(1)}b(){return this.take(2)}a(){return this.take(3)}cat(e){return typeof e=="number"?this.cat(o.val(e)):new o(t=>{const s=this.getValue(t),n=e.getValue(t),i=exports.Type.numeric(exports.Type.size(s.type)+exports.Type.size(n.type));return{type:i,content:`${i}(${s.content}, ${n.content})`}})}static val(...e){if(e.length===1){if(typeof e[0]=="boolean")return new o(()=>({type:"bool",content:e[0]?"1":"0"}));if(e[0]instanceof o)return e[0];{const t=e[0].toString();return new o(()=>({type:"float",content:/[e\.]/.test(t)?t:`${t}.0`}))}}else if(e.some(t=>typeof t=="number")){const t=e.map(s=>o.val(s));return o.val.apply(null,t)}else return e.reduce((t,s)=>t.cat(s))}};o.PI=o.val(Math.PI);let m=o;exports.TypeMap=void 0;(r=>{function e(h){return Array.isArray(h)?h[0]:h}r.getType=e;function t(h){return Array.isArray(h)?h[1]:"highp"}r.getPrecision=t;function s(h){return Object.keys(h).reduce((c,u)=>(c[u]=e(h[u]),c),{})}r.withoutPrecision=s;function n(h,c){const u={};return Object.keys(c).forEach(d=>{const f=c[d];u[d]=new m(g=>(g.once(`types_map_value_${d}`,()=>{g.addGlobal(`${h} ${r.getPrecision(f)} ${r.getType(f)} ${d}; `)}),{type:r.getType(f),content:d}))}),u}r.values=n;function i(h){let c=0;for(const u in h)c+=exports.Type.size(e(h[u]));return c}r.stride=i;function a(h){const c=i(h);return Object.keys(h).sort().reduce((u,d)=>{const f=u.length?u[u.length-1]:null;return u.push({name:d,stride:c,size:exports.Type.size(e(h[d])),offset:f?f.offset+f.size:0}),u},[])}r.layout=a})(exports.TypeMap||(exports.TypeMap={}));function se({uniforms:r,attributes:e,varyings:t,instances:s,fragment:n,vertex:i}){const a=exports.TypeMap.values("uniform",r),h=exports.TypeMap.values("attribute",{...e,...s||{}}),c=t?exports.TypeMap.values("varying",t):{},u=new w;Object.keys(c).forEach(y=>{c[y].getValue(u)});const d=i({...a,...h}),f=Object.keys(d).map(y=>`${y} = ${d[y].getValue(u).content}; `).join(""),g=u.getGlobal()+`void main() { `+u.getLocal()+f+`} `,M=new w;Object.keys(c).forEach(y=>{c[y].getValue(u)});const Se=n({...a,...c,gl_FragCoord:new m(()=>({type:"vec4",content:"gl_FragCoord"})),gl_PointCoord:new m(()=>({type:"vec2",content:"gl_FragCoord"})),gl_FrontFacing:new m(()=>({type:"bool",content:"gl_FrontFacing"}))}).gl_FragColor.getValue(M),Re=M.getGlobal()+`void main() { `+M.getLocal()+`gl_FragColor = ${Se.content}; } `;return{vertex:g,fragment:Re,uniforms:exports.TypeMap.withoutPrecision(r),attributes:exports.TypeMap.withoutPrecision(e),instances:exports.TypeMap.withoutPrecision(s||{})}}const E=m.val,W=256,j=16384,Me=0,Ve=1,Oe=2,Ie=3,Be=4,Ne=5,Ce=6,Pe=0,$e=1,Fe=768,Ge=769,qe=770,Ue=771,ke=772,He=773,ze=774,De=775,We=776,je=32774,Xe=32778,Qe=32779,B=34962,N=34963,Ye=35040,Ze=35044,Ke=35048,Je=1028,_e=1029,et=1032,X=2884,Q=3042,Y=2929,Z=3089,tt=0,rt=1280,st=1281,nt=1282,at=1285,it=33901,L=5121,K=5123,T=5126,ne=6406,ae=6407,ie=6408,lt=6409,ct=6410,ht=35632,ot=35633,ut=35714,dt=35718,ft=35721,pt=512,mt=513,gt=514,yt=515,At=516,bt=517,Et=518,wt=519,Lt=9728,vt=9729,J=10240,_=10241,xt=10242,St=10243,p=3553,Rt=33984,ee=33071,C=35664,P=35665,$=35666,le=35670,ce=35674,he=35675,oe=35676,ue=35678,Tt=35713,V=36160,v=36161,te=33189,Mt=36064,Vt=36096,Ot=37440,It=35904,Bt=35907;var F=(r=>(r[r.Front=Je]="Front",r[r.Back=_e]="Back",r[r.FrontAndBack=et]="FrontAndBack",r))(F||{}),x=(r=>(r[r.Add=je]="Add",r[r.Sub=Xe]="Sub",r[r.RSub=Qe]="RSub",r[r.Min=32775]="Min",r[r.Max=32776]="Max",r))(x||{}),G=(r=>(r[r.Never=pt]="Never",r[r.Less=mt]="Less",r[r.Equal=gt]="Equal",r[r.LEqual=yt]="LEqual",r[r.Greater=At]="Greater",r[r.NotEqual=bt]="NotEqual",r[r.GEqual=Et]="GEqual",r[r.Always=wt]="Always",r))(G||{}),A=(r=>(r[r.Zero=Pe]="Zero",r[r.One=$e]="One",r[r.SrcColor=Fe]="SrcColor",r[r.OneMinusSrcColor=Ge]="OneMinusSrcColor",r[r.DstColor=ze]="DstColor",r[r.OneMinusDstColor=De]="OneMinusDstColor",r[r.SrcAlpha=qe]="SrcAlpha",r[r.OneMinusSrcAlpha=Ue]="OneMinusSrcAlpha",r[r.DstAlpha=ke]="DstAlpha",r[r.OneMinusDstAlpha=He]="OneMinusDstAlpha",r[r.SrcAlphaSaturate=We]="SrcAlphaSaturate",r))(A||{}),q=(r=>(r[r.Nearest=Lt]="Nearest",r[r.Linear=vt]="Linear",r))(q||{}),U=(r=>(r[r.Alpha=ne]="Alpha",r[r.Luminance=lt]="Luminance",r[r.LuminanceAlpha=ct]="LuminanceAlpha",r[r.Rgb=ae]="Rgb",r[r.Rgba=ie]="Rgba",r[r.Srgb=It]="Srgb",r[r.Srgba=Bt]="Srgba",r))(U||{});exports.PixelFormat=(r=>(r[r.Rgba=ie]="Rgba",r[r.Rgb=ae]="Rgb",r[r.Alpha=ne]="Alpha",r))(exports.PixelFormat||{});(r=>{function e(t){switch(t){case r.Rgb:return 3;case r.Rgba:return 4;case r.Alpha:return 1}}r.getChannelsCount=e})(exports.PixelFormat||(exports.PixelFormat={}));var S=(r=>(r[r.Vertex=ot]="Vertex",r[r.Fragment=ht]="Fragment",r))(S||{}),de=(r=>(r[r.NoError=tt]="NoError",r[r.InvalidEnum=rt]="InvalidEnum",r[r.InvalidValue=st]="InvalidValue",r[r.InvalidOperation=nt]="InvalidOperation",r[r.OutOfMemory=at]="OutOfMemory",r))(de||{}),b=(r=>(r[r.Stream=Ye]="Stream",r[r.Static=Ze]="Static",r[r.Dynamic=Ke]="Dynamic",r))(b||{}),fe=(r=>(r[r.Array=B]="Array",r[r.Elements=N]="Elements",r))(fe||{}),pe=(r=>(r[r.Points=Me]="Points",r[r.Lines=Ve]="Lines",r[r.LineStrip=Ie]="LineStrip",r[r.LineLoop=Oe]="LineLoop",r[r.Triangles=Be]="Triangles",r[r.TriangleStrip=Ne]="TriangleStrip",r[r.TriangleFan=Ce]="TriangleFan",r))(pe||{});exports.AttributeDataType=(r=>(r[r.Float=T]="Float",r[r.Vec2=C]="Vec2",r[r.Vec3=P]="Vec3",r[r.Vec4=$]="Vec4",r))(exports.AttributeDataType||{});var me=(r=>(r[r.Bool=le]="Bool",r[r.Sampler=ue]="Sampler",r[r.Float=T]="Float",r[r.Vec2=C]="Vec2",r[r.Vec3=P]="Vec3",r[r.Vec4=$]="Vec4",r[r.Mat2=ce]="Mat2",r[r.Mat3=he]="Mat3",r[r.Mat4=oe]="Mat4",r))(me||{});(r=>{function e(n){switch(n){case r.Float:return 1;case r.Vec2:return 2;case r.Vec3:return 3;case r.Vec4:return 4}}r.getSizeInFloats=e;function t(n){return e(n)*4}r.getSizeInBytes=t;function s(n){return n===r.Vec2||n===r.Vec3||n===r.Vec4}r.isVec=s})(exports.AttributeDataType||(exports.AttributeDataType={}));class k{constructor(e,t){this.gl=e,this.handle=e.handle.createTexture(),this.format=t.format||U.Rgba,this.filter=t.filter||q.Nearest,"image"in t?(this.width=t.image instanceof HTMLImageElement?t.image.naturalWidth:t.image instanceof VideoFrame?t.image.codedWidth:t.image.width,this.height=t.image instanceof HTMLImageElement?t.image.naturalHeight:t.image instanceof VideoFrame?t.image.codedHeight:t.image.height):(this.width=t.width,this.height=t.height),e.settings().activeTexture(0).texture(0,this).apply(()=>{e.handle.pixelStorei(Ot,1),e.handle.texParameteri(p,J,this.filter),e.handle.texParameteri(p,_,this.filter),e.handle.texParameteri(p,xt,ee),e.handle.texParameteri(p,St,ee),"image"in t?e.handle.texImage2D(p,0,this.format,this.format,L,t.image):e.handle.texImage2D(p,0,this.format,this.width,this.height,0,this.format,L,"data"in t?t.data:null)})}read(e=exports.PixelFormat.Rgba){const t=new Uint8Array(this.width*this.height*exports.PixelFormat.getChannelsCount(e));return this.gl.settings().renderTarget(this).viewport(0,0,this.width,this.height).apply(()=>{this.gl.handle.readPixels(0,0,this.width,this.height,e,L,t)}),t}setFilter(e){this.gl.handle.texParameteri(p,J,e),this.gl.handle.texParameteri(p,_,e)}dispose(){this.gl.handle.deleteTexture(this.handle)}}class ge{constructor(e,t,s){this.gl=e,this.primitivesType=t,this.source=s,this.textureInstances=new Map,this.textureIndexes=new Map,this.program=e.program(s.vertex,s.fragment),this.attributes=e.arrayBuffer(),this.instances=e.arrayBuffer(),this.elements=e.elementsBuffer(),this.attributesStride=exports.TypeMap.stride(s.attributes),this.attributesLayout=exports.TypeMap.layout(s.attributes),this.instancesStride=exports.TypeMap.stride(s.instances),this.instancesLayout=exports.TypeMap.layout(s.instances);for(const n in s.uniforms)exports.TypeMap.getType(s.uniforms[n])===exports.Type.Sampler&&this.textureIndexes.set(n,this.textureIndexes.size)}prepareData(e,t,s){const n=new Float32Array(e*s.length);return s.forEach((i,a)=>{t.forEach(h=>{const c=i[h.name],u=e*a+h.offset;if(Array.isArray(c))for(let d=0;d<c.length;d++)n[u+d]=c[d];else if(h.size===1&&typeof c=="number")n[u]=c;else if(h.size===2){const{x:d,y:f}=c;n[u]=d,n[u+1]=f}else if(h.size===3){const{x:d,y:f,z:g}=c;n[u]=d,n[u+1]=f,n[u+2]=g}else throw new Error(`Unsupported attribute '${h.name}' value: ${JSON.stringify(c)}`)})}),n}setAttributes(e){const t=this.prepareData(this.attributesStride,this.attributesLayout,e);return this.attributes.setContent(t),this}setInstances(e){const t=this.prepareData(this.instancesStride,this.instancesLayout,e);return this.instances.setContent(t),this}setElements(e){return this.elements.setContent(e),this}setUniforms(e){const t=this.source.uniforms;for(const s in e){const n=e[s];let i;if(typeof n=="number")i=[n];else if(Array.isArray(n))i=n;else if(n instanceof k){const a=this.textureIndexes.get(s);this.textureInstances.set(a,n),i=[a]}else if(t[s]===exports.Type.Vector2){const{x:a,y:h}=n;i=[a,h]}else if(t[s]===exports.Type.Vector3){const{x:a,y:h,z:c}=n;i=[a,h,c]}else throw new Error(`Invalid value for uniform '${s}', expected ${t[s]}`);this.program.setUniform(s,i)}return this}draw(e=this.instancesStride?this.instances.length/this.instancesStride:null,t=this.attributesStride?this.attributes.length/this.attributesStride:null,s=this.elements.length){const n=this.gl,i=(a,h)=>({name:c,stride:u,offset:d})=>{const f=this.program.attributes.get(c);return[f.location,{buffer:a,type:f.type,stride:u*4,offset:d*4,divisor:h}]};n.settings().program(this.program).arrayBuffer(this.attributes).attributes(new Map([...this.attributesLayout.map(i(this.attributes,0)),...this.instancesLayout.map(i(this.instances,1))])).textures(Array.from(this.textureInstances.entries()).reduce((a,[h,c])=>(a[h]=c,a),new Array(16).fill(null))).apply(()=>{if(e!==null&&s!==0)n.settings().elementsBuffer(this.elements).apply(()=>{n.drawsInstancedElements(this.primitivesType,s,e)});else if(e!==null&&t!==null)n.drawInstancedArrays(this.primitivesType,t,e);else if(s!==0)n.settings().elementsBuffer(this.elements).apply(()=>{n.drawsElements(this.primitivesType,s)});else if(t)n.drawArrays(this.primitivesType,t);else throw new Error("Invalid draw dataset")})}dispose(){this.program.dispose(),this.attributes.dispose(),this.instances.dispose(),this.elements.dispose()}}function ye(r,e,t){return new ge(r,e,"vertex"in t&&typeof t.vertex=="string"?t:se(t))}class Nt{constructor(e){this.values=e}dispose(){this.values.forEach(e=>e.dispose())}}function Ct(...r){return new Nt(r)}function Ae(...r){r.forEach(e=>e.dispose())}function be(...r){const e=[];try{for(let t=0;t<r.length;t++)e.push(r[t](...e));return e}catch(t){throw e.reverse().forEach(s=>s.dispose()),t}}function H(r,e){try{return e(r)}finally{r.dispose()}}function z(...r){const e=r.length-1,t=[];try{for(let s=0;s<e;s++)t.push(r[s](...t));return r[e](...t)}finally{t.reverse().forEach(s=>s.dispose())}}exports.Disposable=void 0;(r=>{r.join=Ct,r.dispose=Ae,r.create=be,r.use=H,r.uses=z})(exports.Disposable||(exports.Disposable={}));var O;(r=>{function e(){return{blend:!1,viewport:[0,0,0,0],scissorTest:!1,scissorBox:[0,0,0,0],depthTest:!1,depthFunction:G.Less,clearDepth:1,lineWidth:1,blendEquation:[x.Add,x.Add],blendFunction:[A.One,A.Zero,A.One,A.Zero],clearColor:[0,0,0,0],activeTexture:0,textures:new Map,arrayBuffer:null,elementsBuffer:null,program:null,attributes:new Map,renderBuffer:null,frameBuffer:null,cullFace:!1,cullFaceMode:F.Back}}r.initial=e})(O||(O={}));const l=class l{constructor(e,t,s=n=>n()){this.gl=e,this.cache=t,this.apply=s}static cached({read:e,write:t,equals:s,apply:n}){return function(i,a){const{gl:h,cache:c}=i;return i.then(new l(h,c,u=>{const d=e(c);if(s(d,a))return u();try{return t(c,a),n(h,a),u()}finally{t(c,d),n(h,d)}}))}}then(e){return new l(this.gl,this.cache,t=>this.apply(()=>e.apply(t)))}blend(e){return l.blend(this,e)}cullFace(e){return l.cullFace(this,e)}cullFaceMode(e){return l.cullFaceMode(this,e)}viewport(e,t,s,n){return l.viewport(this,e,t,s,n)}scissorTest(e){return l.scissorTest(this,e)}scissorBox(e,t,s,n){return l.scissorBox(this,e,t,s,n)}depthTest(e){return l.depthTest(this,e)}clearDepth(e){return l.clearDepth(this,e)}lineWidth(e){return l.lineWidth(this,e)}blendEquation(e,t){return l.blendEquation(this,e,t)}blendFunction(e,t,s,n){return l.blendFunction(this,e,t,s,n)}depthFunction(e){return l.depthFunction(this,e)}clearColor(e,t,s,n){return l.clearColor(this,e,t,s,n)}activeTexture(e){return l.activeTexture(this,e)}texture(e,t){return l.texture(this,e,t)}textures(e){let t=this;for(let s=0;s<16;s++)t=t.texture(s,s>=e.length?null:e[s]);return t}arrayBuffer(e){return l.arrayBuffer(this,e)}elementsBuffer(e){return l.elementsBuffer(this,e)}program(e){return l.program(this,e)}renderBuffer(e){return l.renderBuffer(this,e)}frameBuffer(e){return l.frameBuffer(this,e)}renderTarget(e){return new l(this.gl,this.cache,t=>H(this.gl.frameBuffer(e),s=>this.gl.settings().frameBuffer(s).viewport(0,0,e.width,e.height).apply(t)))}writeAttributePointer(e,t){const{gl:s}=this,{handle:n,instancedArraysExtension:i}=s;t?(n.enableVertexAttribArray(e),s.settings().arrayBuffer(t.buffer).apply(()=>{n.vertexAttribPointer(e,exports.AttributeDataType.getSizeInFloats(t.type),T,!1,t.stride,t.offset)}),i.vertexAttribDivisorANGLE(e,t.divisor),this.cache.attributes.set(e,t)):(n.disableVertexAttribArray(e),this.cache.attributes.delete(e))}attribute(e,t){const s=this.gl;return s.handle,this.then(new l(s,this.cache,n=>{const{attributes:i}=this.cache,a=i.get(e)??null;if(!t&&!a||t&&a&&t.buffer===a.buffer&&t.offset===a.offset&&t.stride===a.stride&&t.type===a.type&&t.divisor===a.divisor)return n();try{return this.writeAttributePointer(e,t),n()}finally{this.writeAttributePointer(e,a)}}))}attributes(e){const t=new Set(this.cache.attributes.keys());return Array.from(e.entries()).reduce((s,[n,i])=>s.attribute(n,i),this).then(Array.from(t).reduce((s,n)=>e.has(n)?s:s.attribute(n,null),new l(this.gl,this.cache)))}};l.blend=l.cached({read:e=>e.blend,write:(e,t)=>{e.blend=t},equals:(e,t)=>e===t,apply:(e,t)=>{t?e.handle.enable(Q):e.handle.disable(Q)}}),l.cullFace=l.cached({read:e=>e.cullFace,write:(e,t)=>{e.cullFace=t},equals:(e,t)=>e===t,apply:(e,t)=>{t?e.handle.enable(X):e.handle.disable(X)}}),l.cullFaceMode=l.cached({read:e=>e.cullFaceMode,write:(e,t)=>{e.cullFaceMode=t},equals:(e,t)=>e===t,apply:(e,t)=>{e.handle.cullFace(t)}}),l.viewport=(()=>{const e=l.cached({read:t=>t.viewport,write:(t,s)=>{t.viewport=s},equals:(t,s)=>t.every((n,i)=>n===s[i]),apply:(t,[s,n,i,a])=>{t.handle.viewport(s,n,i,a)}});return function(t,s,n,i,a){return e(t,[s,n,i,a])}})(),l.scissorTest=l.cached({read:e=>e.scissorTest,write:(e,t)=>{e.scissorTest=t},equals:(e,t)=>e===t,apply:(e,t)=>{t?e.handle.enable(Z):e.handle.disable(Z)}}),l.scissorBox=(()=>{const e=l.cached({read:t=>t.scissorBox,write:(t,s)=>{t.scissorBox=s},equals:(t,s)=>t.every((n,i)=>n===s[i]),apply:(t,[s,n,i,a])=>{t.handle.scissor(s,n,i,a)}});return function(t,s,n,i,a){return e(t,[s,n,i,a])}})(),l.depthTest=l.cached({read:e=>e.depthTest,write:(e,t)=>{e.depthTest=t},equals:(e,t)=>e===t,apply:(e,t)=>{t?e.handle.enable(Y):e.handle.disable(Y)}}),l.clearDepth=l.cached({read:e=>e.clearDepth,write:(e,t)=>{e.clearDepth=t},equals:(e,t)=>e===t,apply:(e,t)=>{e.handle.clearDepth(t)}}),l.lineWidth=l.cached({read:e=>e.lineWidth,write:(e,t)=>{e.lineWidth=t},equals:(e,t)=>e===t,apply:(e,t)=>{e.handle.lineWidth(t)}}),l.blendEquation=(()=>{const e=l.cached({read:t=>t.blendEquation,write:(t,s)=>{t.blendEquation=s},equals:(t,s)=>t.every((n,i)=>n===s[i]),apply:(t,[s,n])=>{t.handle.blendEquationSeparate(s,n)}});return function(t,s,n=s){return e(t,[s,n])}})(),l.blendFunction=(()=>{const e=l.cached({read:t=>t.blendFunction,write:(t,s)=>{t.blendFunction=s},equals:(t,s)=>t.every((n,i)=>n===s[i]),apply:(t,[s,n,i,a])=>{t.handle.blendFuncSeparate(s,n,i,a)}});return function(t,s,n,i=s,a=n){return e(t,[s,n,i,a])}})(),l.depthFunction=l.cached({read:e=>e.depthFunction,write:(e,t)=>{e.depthFunction=t},equals:(e,t)=>e===t,apply:(e,t)=>{e.handle.depthFunc(t)}}),l.clearColor=(()=>{const e=l.cached({read:t=>t.clearColor,write:(t,s)=>{t.clearColor=s},equals:(t,s)=>t.every((n,i)=>n===s[i]),apply:(t,[s,n,i,a])=>{t.handle.clearColor(s,n,i,a)}});return function(t,s,n,i,a){return e(t,[s,n,i,a])}})(),l.activeTexture=l.cached({read:e=>e.activeTexture,write:(e,t)=>{e.activeTexture=t},equals:(e,t)=>e===t,apply:(e,t)=>{e.handle.activeTexture(Rt+t)}}),l.texture=(()=>{const e=new Array(16).fill(null).map((t,s)=>l.cached({read:n=>n.textures.get(s)||null,write:(n,i)=>{i?n.textures.set(s,i):n.textures.delete(s)},equals:(n,i)=>n===i,apply:(n,i)=>{n.settings().activeTexture(s).apply(()=>{n.handle.bindTexture(p,i?.handle||null)})}}));return function(t,s,n){return e[s](t,n)}})(),l.arrayBuffer=l.cached({read:e=>e.arrayBuffer,write:(e,t)=>{e.arrayBuffer=t},equals:(e,t)=>e===t,apply:(e,t)=>{e.handle.bindBuffer(B,t?.handle??null)}}),l.elementsBuffer=l.cached({read:e=>e.elementsBuffer,write:(e,t)=>{e.elementsBuffer=t},equals:(e,t)=>e===t,apply:(e,t)=>{e.handle.bindBuffer(N,t?.handle??null)}}),l.program=l.cached({read:e=>e.program,write:(e,t)=>{e.program=t},equals:(e,t)=>e===t,apply:(e,t)=>{e.handle.useProgram(t?t.handle:null)}}),l.renderBuffer=l.cached({read:e=>e.renderBuffer,write:(e,t)=>{e.renderBuffer=t},equals:(e,t)=>e===t,apply:(e,t)=>{e.handle.bindRenderbuffer(v,t?t.handle:null)}}),l.frameBuffer=l.cached({read:e=>e.frameBuffer,write:(e,t)=>{e.frameBuffer=t},equals:(e,t)=>e===t,apply:(e,t)=>{e.handle.bindFramebuffer(V,t?t.handle:null)}});let R=l;class I{constructor(e,t,s){this.gl=e,this.type=t,this.source=s;const n=this.handle=e.handle.createShader(t);if(e.handle.shaderSource(n,s),e.handle.compileShader(n),e.handle.getShaderParameter(n,Tt)===!1)throw new Error(`WebGL error '${e.handle.getShaderInfoLog(n)}' in '${s}'`)}dispose(){this.gl.handle.deleteShader(this.handle)}}class Ee{constructor(e,t,s){this.gl=e,this.vertex=t,this.fragment=s,this.uniforms=new Map,this.attributes=new Map;const n=this.handle=e.handle.createProgram();if(e.handle.attachShader(n,t.handle),e.handle.attachShader(n,s.handle),e.handle.linkProgram(n),e.handle.validateProgram(n),e.handle.getProgramParameter(n,ut)===!1)throw new Error(e.handle.getProgramInfoLog(n)||`Program linking error: ${t.source}; ${s.source}`);const i=e.handle.getProgramParameter(n,dt);for(let h=0;h<i;h++){const c=e.handle.getActiveUniform(n,h);c!==null&&this.uniforms.set(c.name,{name:c.name,type:c.type,location:e.handle.getUniformLocation(n,c.name)})}const a=e.handle.getProgramParameter(n,ft);for(let h=0;h<a;h++){const c=e.handle.getActiveAttrib(n,h);c!=null&&this.attributes.set(c.name,{name:c.name,type:c.type,location:h})}}setUniform(e,t){const{gl:s,uniforms:n}=this,i=n.get(e);if(i){const{location:a,type:h}=i;s.settings().program(this).apply(()=>{switch(h){case le:s.handle.uniform1i(a,t[0]?1:0);break;case ue:s.handle.uniform1iv(a,t);break;case T:s.handle.uniform1fv(a,t);break;case C:s.handle.uniform2fv(a,t);break;case P:s.handle.uniform3fv(a,t);break;case $:s.handle.uniform4fv(a,t);break;case ce:s.handle.uniformMatrix2fv(a,!1,t);break;case he:s.handle.uniformMatrix3fv(a,!1,t);break;case oe:s.handle.uniformMatrix4fv(a,!1,t);break}})}}dispose(){this.gl.handle.deleteProgram(this.handle)}}class we{constructor(e,t=null,s=b.Dynamic){this.gl=e,this.usage=s,this.lengthValue=0,this.handle=e.handle.createBuffer(),t&&this.setContent(t)}get length(){return this.lengthValue}setContent(e){const t=e instanceof Uint8Array||e instanceof Uint16Array?e:new Uint16Array(e);this.lengthValue=t.length;const s=this.gl;return s.settings().elementsBuffer(this).apply(()=>{s.handle.bufferData(N,t,this.usage)}),this}dispose(){this.gl.handle.deleteBuffer(this.handle)}}class Le{constructor(e,t=null,s=b.Dynamic){this.gl=e,this.usage=s,this.lengthValue=0,this.handle=e.handle.createBuffer(),t&&this.setContent(t)}get length(){return this.lengthValue}setContent(e){const t=e instanceof Float32Array?e:new Float32Array(e);this.lengthValue=t.length;const s=this.gl;return s.settings().arrayBuffer(this).apply(()=>{s.handle.bufferData(B,t,this.usage)}),this}dispose(){this.gl.handle.deleteBuffer(this.handle)}}class ve{constructor(e,t,s){this.gl=e,this.widthValue=t,this.heightValue=s,this.handle=e.handle.createRenderbuffer(),e.settings().renderBuffer(this).apply(()=>{e.handle.renderbufferStorage(v,te,t,s)})}get width(){return this.widthValue}get height(){return this.heightValue}resize(e,t){const{gl:s}=this;return(e!==this.width||t!==this.height)&&(this.widthValue=e,this.heightValue=t,s.settings().renderBuffer(this).apply(()=>{s.handle.renderbufferStorage(v,te,e,t)})),this}dispose(){this.gl.handle.deleteRenderbuffer(this.handle)}}class xe{constructor(e,t,s){this.gl=e,this.colorBuffer=t,this.depthBuffer=s,this.handle=e.handle.createFramebuffer(),e.settings().frameBuffer(this).apply(()=>{e.handle.framebufferTexture2D(V,Mt,p,t.handle,0),s&&e.handle.framebufferRenderbuffer(V,Vt,v,s.handle)})}dispose(){this.gl.handle.deleteFramebuffer(this.handle)}}class Pt{constructor(...e){this.settingsCache=O.initial();const[t,s]=e;typeof HTMLCanvasElement<"u"&&t instanceof HTMLCanvasElement?this.handle=t.getContext("webgl",s):this.handle=t,this.instancedArraysExtension=this.handle.getExtension("ANGLE_instanced_arrays"),this.minMaxExtension=this.handle.getExtension("EXT_blend_minmax"),this.srgbExtension=this.handle.getExtension("EXT_sRGB")}get width(){return this.handle.drawingBufferWidth}get height(){return this.handle.drawingBufferHeight}isContextLost(){return this.handle.isContextLost()}getPointSizeRange(){return this.handle.getParameter(it)}clearColorBuffer(){return this.handle.clear(j),this}clearDepthBuffer(){return this.handle.clear(W),this}clearBuffers(){return this.handle.clear(j|W),this}read(e=exports.PixelFormat.Rgba){const{width:t,height:s}=this,n=new Uint8Array(t*s*exports.PixelFormat.getChannelsCount(e));return this.settings().viewport(0,0,t,s).apply(()=>{this.handle.readPixels(0,0,t,s,e,L,n)}),n}drawArrays(e,t){return this.handle.drawArrays(e,0,t),this}drawsElements(e,t){return this.handle.drawElements(e,t,K,0),this}drawInstancedArrays(e,t,s){return this.instancedArraysExtension.drawArraysInstancedANGLE(e,0,t,s),this}drawsInstancedElements(e,t,s){return this.instancedArraysExtension.drawElementsInstancedANGLE(e,t,K,0,s),this}settings(){return new R(this,this.settingsCache)}texture(e){return new k(this,e)}renderBuffer(e,t){return new ve(this,e,t)}frameBuffer(e,t){return new xe(this,e,t)}arrayBuffer(e=null,t=b.Dynamic){return new Le(this,e,t)}elementsBuffer(e=null,t=b.Dynamic){return new we(this,e,t)}program(e,t){return z(()=>new I(this,S.Vertex,e),()=>new I(this,S.Fragment,t),(s,n)=>new Ee(this,s,n))}command(e,t){return ye(this,e,t)}hasSrgbExtension(){return!!this.srgbExtension}getErrorCode(){return this.handle.getError()}dispose(){const e=this.handle.getExtension("WEBGL_lose_context");e&&e.loseContext()}}exports.ArrayBuffer=Le;exports.BlendEquation=x;exports.BlendFunction=A;exports.BufferTarget=fe;exports.BufferUsage=b;exports.Command=ge;exports.DepthFunction=G;exports.ElementsBuffer=we;exports.ErrorCode=de;exports.FaceCulling=F;exports.FrameBuffer=xe;exports.Gl=Pt;exports.Glsl=m;exports.GlslBuilder=w;exports.Precision=re;exports.PrimitivesType=pe;exports.Program=Ee;exports.RenderBuffer=ve;exports.Settings=R;exports.Shader=I;exports.ShaderType=S;exports.Texture=k;exports.TextureFilter=q;exports.TextureFormat=U;exports.UniformDataType=me;exports.command=ye;exports.create=be;exports.dispose=Ae;exports.source=se;exports.use=H;exports.uses=z;exports.val=E; //# sourceMappingURL=index.cjs.map