Skip to content

Instantly share code, notes, and snippets.

@diska
Last active February 10, 2021 08:04
Show Gist options
  • Select an option

  • Save diska/f7f4614aca1c3bc7528c4d86ae950a1e to your computer and use it in GitHub Desktop.

Select an option

Save diska/f7f4614aca1c3bc7528c4d86ae950a1e to your computer and use it in GitHub Desktop.
「textureにパースを付ける仕組み」を試行錯誤しているWebGLコード。
<canvas width="256" height="256"></canvas><hr/>
<textarea id="LG" cols="30" rows="10"></textarea>
<script>"use strict";
const vsrc=`attribute vec4 p;uniform float tm;varying vec2 co;
mat4 m=mat4(cos(tm),0,sin(tm),0,0,1,0,0,-sin(tm),0,cos(tm),0,0,0,0,1);
void main(){
gl_Position=vec4(2.*p.xy-1.,0,1)*m;
gl_Position.w=1./(1.+(gl_Position.z*0.2)); co=p.xy;
}`;
const fsrc=`precision highp float;uniform sampler2D tx;varying vec2 co;
void main(){gl_FragColor=texture2D(tx, co*9.);}`;
let cx=document.querySelector("canvas").getContext("webgl");
let pg=cx.createProgram();
let vs=cx.createShader(cx.VERTEX_SHADER); cx.attachShader(pg,vs);
let fs=cx.createShader(cx.FRAGMENT_SHADER); cx.attachShader(pg,fs);
cx.shaderSource(vs,vsrc); cx.compileShader(vs);
cx.shaderSource(fs,fsrc); cx.compileShader(fs);cx.linkProgram(pg);
LG.value+=`pg:${cx.getProgramInfoLog(pg)}\n`;
LG.value+=`vs:${cx.getShaderInfoLog(vs)}\n`;
LG.value+=`fs:${cx.getShaderInfoLog(fs)}\n`;// LG.hidden=true;
let pgTx=cx.getUniformLocation(pg,"tx");
let pgTm=cx.getUniformLocation(pg,"tm");
let bfdata=new Int8Array([0,0, 127,0, 0,127, 127,127]);
let bf=cx.createBuffer(); cx.bindBuffer(cx.ARRAY_BUFFER,bf);
cx.bufferData(cx.ARRAY_BUFFER,bfdata,cx.STATIC_DRAW);
cx.enableVertexAttribArray(0);cx.vertexAttribPointer(0,2,cx.BYTE,true,0,0);
cx.bindBuffer(cx.ARRAY_BUFFER,null);
let txdata=new Uint16Array(64);for(let i=0;i<64;i++)txdata[i]=Math.random()*0xffff;
let tx=cx.createTexture(); cx.activeTexture(cx.TEXTURE0+0);
cx.bindTexture(cx.TEXTURE_2D,tx);
cx.texImage2D(cx.TEXTURE_2D,0,cx.RGBA,4,4,0,cx.RGBA,cx.UNSIGNED_SHORT_4_4_4_4,txdata);
cx.generateMipmap(cx.TEXTURE_2D);
cx.uniform1i(pgTx, 0);
// draw
cx.useProgram(pg);
function draw(now){
cx.uniform1f(pgTm, now/1000);
cx.clearColor(.2,.2,.2,1); cx.clear(0x4000); cx.drawArrays(5,0,4);
requestAnimationFrame(draw);
}; requestAnimationFrame(draw);
//
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment