Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #version 300 es
- precision highp float;
- uniform vec2 resolution;
- uniform float time;
- out vec4 fragColor;
- const int maxSteps = 500;
- mat3 lookAt(vec3 origin, vec3 target, float roll) {
- vec3 rr = vec3(sin(roll), cos(roll), 0.0);
- vec3 ww = normalize(target - origin);
- vec3 uu = normalize(cross(ww, rr));
- vec3 vv = normalize(cross(uu, ww));
- return mat3(uu, vv, ww);
- }
- float sdSphere(vec3 p, float r) {
- return length(p) - r;
- }
- float sdPlane(vec3 p, vec3 n, float h) {
- return dot(p, n) - h;
- }
- vec2 minx(vec2 a, vec2 b) {
- return a.x < b.x ? a : b;
- }
- vec2 map(vec3 p) {
- vec2 a = vec2(sdPlane(p, vec3(0, 1, 0), 0.5), 1);
- vec2 b = vec2(sdSphere(p - vec3(0, 1, 0), 0.5), 2);
- vec2 t = minx(a, b);
- return t;
- }
- float shadow(vec3 ro, vec3 rd, float maxt, float k) {
- float res = 1.0;
- for (float t = 0.001; t < maxt;) {
- float h = map(ro + rd*t).x;
- if( h<0.001 )
- return 0.0;
- res = min( res, k*h/t );
- t += h;
- }
- return res;
- }
- vec2 raymarch(vec3 ro, vec3 rd) {
- float t;
- float m;
- float mint = 0.001;
- float maxt = 1000.0;
- for (int i = 0; i < maxSteps; i++) {
- vec3 p = ro + rd * t;
- vec2 d = map(p);
- t += abs(d.x);
- m = d.y;
- if (d.x < 0.001) { break; }
- if (t > 100.0) { return vec2(-1.0, -1.0); }
- }
- return vec2(t, m);
- }
- vec3 skyColor(vec3 rd) {
- return mix(vec3(1), vec3(0.5, 0.7, 1.0), rd.y*0.5+0.5);
- }
- vec3 getNormal(vec3 p) {
- float eps = 0.001;
- float a = map(p).x;
- float x = map(p + vec3(eps, 0, 0)).x;
- float y = map(p + vec3(0, eps, 0)).x;
- float z = map(p + vec3(0, 0, eps)).x;
- return normalize((vec3(x, y, z) - a) / eps);
- }
- vec3 getMaterial(float id) {
- if (id == 2.0) {
- return vec3(0.4, 0.5, 1.0);
- }
- return vec3(0.2, 0.6, 0.3);
- }
- const vec3 sunDir = normalize(-vec3(-1.0, -1.0, -1.0));
- const vec3 sunCol = vec3(1.5, 1.3, 1.2);
- vec3 getLighting(vec3 pos, vec3 nor) {
- vec3 sampSun = max(0.0, dot(nor, sunDir)) * sunCol;
- float shadow = shadow(pos+nor*0.001, sunDir, 1000.0, 32.0);
- vec3 sampSky = skyColor(nor) * 0.2 /** (nor.y*0.5+0.5)*/;
- return sampSun*shadow + sampSky;
- }
- void main() {
- vec2 p = gl_FragCoord.xy;
- vec2 uv = (p - 0.5*resolution) / resolution.y;
- vec3 ro = vec3(sin(time / 6000.0)*4.0, 1.5, cos(time/6000.0)*4.0);
- mat3 ma = lookAt(ro, vec3(0), 0.0);
- vec3 rd = normalize(ma * vec3(uv, 1.0));
- vec3 outColor;
- vec2 t = raymarch(ro, rd);
- if (t.x > 0.0) {
- vec3 pos = ro + rd * t.x;
- vec3 nor = getNormal(pos);
- vec3 col = getMaterial(t.y) * getLighting(pos, nor);
- outColor = col;
- //outColor = nor * 0.5+0.5;
- } else {
- outColor = skyColor(rd);
- }
- fragColor = vec4(pow(outColor, vec3(0.4545)), 1.0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement