Created
August 19, 2018 20:17
-
-
Save diska/ce2fea00a5e1c8b080e41d7c2a7f6379 to your computer and use it in GitHub Desktop.
三葉レイ動画の最初のやつ18:02時点のGLSL実装。暫定。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<meta charset="utf-8"><br/> | |
<canvas id="CNVS"></canvas><hr/> | |
<script> | |
const vsrc=`attribute vec4 p;void main(){gl_PointSize=64.;gl_Position=p;}`; | |
const fsrc=`precision mediump float; | |
struct Ray{ vec3 o, d;}; | |
struct Sph{ vec3 o; float r;}; | |
const float width=120., height=80.; | |
float intersect(Sph sph, Ray ray, float tmin, float tmax){ | |
vec3 op=sph.o-ray.o; | |
float bo=dot(op, ray.d); | |
float det=bo*bo-dot(op,op)+sph.r*sph.r; | |
if(det<0.){return -1.;} | |
float t1=bo-sqrt(det); | |
if(tmin<t1&&t1<tmax){return t1;} | |
float t2=bo+sqrt(det); | |
if(tmin<t2&&t2<tmax){return t2;} | |
return -1.; | |
} | |
vec3 tonemap(vec3 c){ | |
float r=pow(c.r, 1./2.2); | |
float g=pow(c.g, 1./2.2); | |
float b=pow(c.b, 1./2.2); | |
return vec3(r,g,b);// かなり怪しい。 | |
} | |
void main(){ | |
vec3 color=vec3(1,0,1); | |
vec2 rp=vec2(2.*gl_FragCoord.x/width-1., 2.*gl_FragCoord.y/height-1.); | |
Ray ray; | |
ray.o=vec3(vec2(rp), 5); | |
ray.d=vec3(0,0,-1); | |
Sph sph, sphs[2]; | |
sphs[0].o=vec3( .5,0,0), sphs[0].r=1.; | |
sphs[1].o=vec3(-.5,0,0), sphs[1].r=1.; | |
float h, minh=-1., tmax=1000.; | |
for(int i=0; i<2; i++){ | |
h=intersect(sphs[i], ray, 0., tmax); | |
if(h<0.){continue;} | |
sph=sphs[i]; | |
minh=h; | |
tmax=h; | |
} | |
vec3 p, n; | |
if(minh>0.){ | |
p=ray.o+ray.d*minh; | |
n=(p-sph.o)/sph.r; | |
} | |
if(minh>0.){ | |
gl_FragColor=vec4(color,1); | |
gl_FragColor=vec4(tonemap(n),1); | |
}else{ | |
gl_FragColor=vec4(0,0,0,1); | |
} | |
}`; | |
function draw(){ | |
const width=120, height=80; // Image size | |
CNVS.width=width, CNVS.height=height; | |
var cx=CNVS.getContext("webgl"); | |
var vs=cx.createShader(cx.VERTEX_SHADER);cx.shaderSource(vs,vsrc); | |
var fs=cx.createShader(cx.FRAGMENT_SHADER);cx.shaderSource(fs,fsrc); | |
var pg=cx.createProgram();cx.attachShader(pg,vs);cx.attachShader(pg,fs); | |
cx.compileShader(vs);cx.compileShader(fs);cx.linkProgram(pg); | |
console.log(`vs:${cx.getShaderInfoLog(vs)}\nfs:${cx.getShaderInfoLog(fs)}\n`); | |
console.log(`pg:${cx.getProgramInfoLog(pg)}\n`); | |
cx.enableVertexAttribArray(0); | |
cx.useProgram(pg); | |
var abuf=cx.createBuffer(cx.ARRAY_BUFFER); | |
var data=new Float32Array([-1,-1, 1,-1, -1,1, 1,1]) | |
cx.bindBuffer(cx.ARRAY_BUFFER,abuf); | |
cx.bufferData(cx.ARRAY_BUFFER, data, cx.STATIC_DRAW); | |
cx.vertexAttribPointer(0, 2,cx.FLOAT, false, 0,0); | |
cx.bindBuffer(cx.ARRAY_BUFFER,null); | |
cx.drawArrays(cx.TRIANGLE_STRIP,0,4); | |
}; draw(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment