id
stringlengths 6
6
| author
stringclasses 55
values | date
timestamp[ns] | image_code
stringlengths 746
52.3k
| license
stringclasses 7
values | func_bytes
sequencelengths 5
5
| functions
sequencelengths 1
32
| comment
stringlengths 7
1.29k
| header
stringlengths 18
169
| body
stringlengths 18
2.14k
| model_inp
stringlengths 30
1.35k
| function_frequency
int64 1
176
| header_frequency
int64 1
16.3k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
lsfXWH | iq | 2014-05-15T00:14:43 | // The MIT License
// Copyright © 2014 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// https://www.youtube.com/c/InigoQuilez
// https://iquilezles.org
// Four bands of Spherical Harmonics functions (or atomic orbitals if you want). For
// reference and fun.
#if HW_PERFORMANCE==0
#define AA 1
#else
#define AA 2 // antialias level (try 1, 2, 3, ...)
#endif
//#define SHOW_SPHERES
//---------------------------------------------------------------------------------
// Constants, see here: http://en.wikipedia.org/wiki/Table_of_spherical_harmonics
#define k01 0.2820947918 // sqrt( 1/PI)/2
#define k02 0.4886025119 // sqrt( 3/PI)/2
#define k03 1.0925484306 // sqrt( 15/PI)/2
#define k04 0.3153915652 // sqrt( 5/PI)/4
#define k05 0.5462742153 // sqrt( 15/PI)/4
#define k06 0.5900435860 // sqrt( 70/PI)/8
#define k07 2.8906114210 // sqrt(105/PI)/2
#define k08 0.4570214810 // sqrt( 42/PI)/8
#define k09 0.3731763300 // sqrt( 7/PI)/4
#define k10 1.4453057110 // sqrt(105/PI)/4
// Y_l_m(s), where l is the band and m the range in [-l..l]
float SH( in int l, in int m, in vec3 s )
{
vec3 n = s.zxy;
//----------------------------------------------------------
if( l==0 ) return k01;
//----------------------------------------------------------
if( l==1 && m==-1 ) return -k02*n.y;
if( l==1 && m== 0 ) return k02*n.z;
if( l==1 && m== 1 ) return -k02*n.x;
//----------------------------------------------------------
if( l==2 && m==-2 ) return k03*n.x*n.y;
if( l==2 && m==-1 ) return -k03*n.y*n.z;
if( l==2 && m== 0 ) return k04*(3.0*n.z*n.z-1.0);
if( l==2 && m== 1 ) return -k03*n.x*n.z;
if( l==2 && m== 2 ) return k05*(n.x*n.x-n.y*n.y);
//----------------------------------------------------------
if( l==3 && m==-3 ) return -k06*n.y*(3.0*n.x*n.x-n.y*n.y);
if( l==3 && m==-2 ) return k07*n.z*n.y*n.x;
if( l==3 && m==-1 ) return -k08*n.y*(5.0*n.z*n.z-1.0);
if( l==3 && m== 0 ) return k09*n.z*(5.0*n.z*n.z-3.0);
if( l==3 && m== 1 ) return -k08*n.x*(5.0*n.z*n.z-1.0);
if( l==3 && m== 2 ) return k10*n.z*(n.x*n.x-n.y*n.y);
if( l==3 && m== 3 ) return -k06*n.x*(n.x*n.x-3.0*n.y*n.y);
//----------------------------------------------------------
return 0.0;
}
// unrolled version of the above
float SH_0_0( in vec3 s ) { vec3 n = s.zxy; return k01; }
float SH_1_0( in vec3 s ) { vec3 n = s.zxy; return -k02*n.y; }
float SH_1_1( in vec3 s ) { vec3 n = s.zxy; return k02*n.z; }
float SH_1_2( in vec3 s ) { vec3 n = s.zxy; return -k02*n.x; }
float SH_2_0( in vec3 s ) { vec3 n = s.zxy; return k03*n.x*n.y; }
float SH_2_1( in vec3 s ) { vec3 n = s.zxy; return -k03*n.y*n.z; }
float SH_2_2( in vec3 s ) { vec3 n = s.zxy; return k04*(3.0*n.z*n.z-1.0); }
float SH_2_3( in vec3 s ) { vec3 n = s.zxy; return -k03*n.x*n.z; }
float SH_2_4( in vec3 s ) { vec3 n = s.zxy; return k05*(n.x*n.x-n.y*n.y); }
float SH_3_0( in vec3 s ) { vec3 n = s.zxy; return -k06*n.y*(3.0*n.x*n.x-n.y*n.y); }
float SH_3_1( in vec3 s ) { vec3 n = s.zxy; return k07*n.z*n.y*n.x; }
float SH_3_2( in vec3 s ) { vec3 n = s.zxy; return -k08*n.y*(5.0*n.z*n.z-1.0); }
float SH_3_3( in vec3 s ) { vec3 n = s.zxy; return k09*n.z*(5.0*n.z*n.z-3.0); }
float SH_3_4( in vec3 s ) { vec3 n = s.zxy; return -k08*n.x*(5.0*n.z*n.z-1.0); }
float SH_3_5( in vec3 s ) { vec3 n = s.zxy; return k10*n.z*(n.x*n.x-n.y*n.y); }
float SH_3_6( in vec3 s ) { vec3 n = s.zxy; return -k06*n.x*(n.x*n.x-3.0*n.y*n.y); }
vec3 map( in vec3 p )
{
vec3 p00 = p - vec3( 0.00, 2.5,0.0);
vec3 p01 = p - vec3(-1.25, 1.0,0.0);
vec3 p02 = p - vec3( 0.00, 1.0,0.0);
vec3 p03 = p - vec3( 1.25, 1.0,0.0);
vec3 p04 = p - vec3(-2.50,-0.5,0.0);
vec3 p05 = p - vec3(-1.25,-0.5,0.0);
vec3 p06 = p - vec3( 0.00,-0.5,0.0);
vec3 p07 = p - vec3( 1.25,-0.5,0.0);
vec3 p08 = p - vec3( 2.50,-0.5,0.0);
vec3 p09 = p - vec3(-3.75,-2.0,0.0);
vec3 p10 = p - vec3(-2.50,-2.0,0.0);
vec3 p11 = p - vec3(-1.25,-2.0,0.0);
vec3 p12 = p - vec3( 0.00,-2.0,0.0);
vec3 p13 = p - vec3( 1.25,-2.0,0.0);
vec3 p14 = p - vec3( 2.50,-2.0,0.0);
vec3 p15 = p - vec3( 3.75,-2.0,0.0);
float r, d; vec3 n, s, res;
#ifdef SHOW_SPHERES
#define SHAPE (vec3(d-0.35, -1.0+2.0*clamp(0.5 + 16.0*r,0.0,1.0),d))
#else
#define SHAPE (vec3(d-abs(r), sign(r),d))
#endif
d=length(p00); n=p00/d; r = SH_0_0( n ); s = SHAPE; res = s;
d=length(p01); n=p01/d; r = SH_1_0( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p02); n=p02/d; r = SH_1_1( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p03); n=p03/d; r = SH_1_2( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p04); n=p04/d; r = SH_2_0( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p05); n=p05/d; r = SH_2_1( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p06); n=p06/d; r = SH_2_2( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p07); n=p07/d; r = SH_2_3( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p08); n=p08/d; r = SH_2_4( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p09); n=p09/d; r = SH_3_0( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p10); n=p10/d; r = SH_3_1( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p11); n=p11/d; r = SH_3_2( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p12); n=p12/d; r = SH_3_3( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p13); n=p13/d; r = SH_3_4( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p14); n=p14/d; r = SH_3_5( n ); s = SHAPE; if( s.x<res.x ) res=s;
d=length(p15); n=p15/d; r = SH_3_6( n ); s = SHAPE; if( s.x<res.x ) res=s;
return vec3( res.x, 0.5+0.5*res.y, res.z );
}
vec3 intersect( in vec3 ro, in vec3 rd )
{
vec3 res = vec3(1e10,-1.0, 1.0);
float maxd = 10.0;
float h = 1.0;
float t = 0.0;
vec2 m = vec2(-1.0);
for( int i=0; i<200; i++ )
{
if( h<0.001||t>maxd ) break;
vec3 res = map( ro+rd*t );
h = res.x;
m = res.yz;
t += h*0.3;
}
if( t<maxd && t<res.x ) res=vec3(t,m);
return res;
}
vec3 calcNormal( in vec3 pos )
{
vec3 eps = vec3(0.001,0.0,0.0);
return normalize( vec3(
map(pos+eps.xyy).x - map(pos-eps.xyy).x,
map(pos+eps.yxy).x - map(pos-eps.yxy).x,
map(pos+eps.yyx).x - map(pos-eps.yyx).x ) );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera
float an = 0.314*iTime - 10.0*iMouse.x/iResolution.x;
vec3 ro = vec3(6.0*sin(an),0.0,6.0*cos(an));
vec3 ta = vec3(0.0,0.0,0.0);
// camera matrix
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(0.0,1.0,0.0) ) );
vec3 vv = normalize( cross(uu,ww));
vec3 tot = vec3(0.0);
#define ZERO min(iFrame,0)
for( int m=ZERO; m<AA; m++ )
for( int n=ZERO; n<AA; n++ )
{
vec2 p = (-iResolution.xy + 2.0*(fragCoord+vec2(float(m),float(n))/float(AA))) / iResolution.y;
// create view ray
vec3 rd = normalize( p.x*uu + p.y*vv + 2.0*ww );
// background
vec3 col = vec3(0.3) * clamp(1.0-length(p)*0.45,0.0,1.0);
// raymarch
vec3 tmat = intersect(ro,rd);
if( tmat.y>-0.5 )
{
// geometry
vec3 pos = ro + tmat.x*rd;
vec3 nor = calcNormal(pos);
vec3 ref = reflect( rd, nor );
// material
vec3 mate = 0.5*mix( vec3(1.0,0.6,0.15), vec3(0.2,0.4,0.5), tmat.y );
float occ = clamp( 2.0*tmat.z, 0.0, 1.0 );
float sss = pow( clamp( 1.0 + dot(nor,rd), 0.0, 1.0 ), 1.0 );
// lights
vec3 lin = 2.5*occ*vec3(1.0,1.00,1.00)*(0.6+0.4*nor.y);
lin += 1.0*sss*vec3(1.0,0.95,0.70)*occ;
// surface-light interacion
col = mate.xyz * lin;
}
// gamma
col = pow( clamp(col,0.0,1.0), vec3(0.4545) );
tot += col;
}
tot /= float(AA*AA);
// bad dither
tot += (1.0/255.0)*fract(sin(fragCoord.x+1111.0*fragCoord.y)*1111.0);
fragColor = vec4( tot, 1.0 );
}
| mit | [
3256,
3289,
3316,
3316,
3347
] | [
[
1978,
2039,
2083,
2083,
3254
],
[
3256,
3289,
3316,
3316,
3347
],
[
3348,
3348,
3375,
3375,
3410
],
[
3411,
3411,
3438,
3438,
3473
],
[
3474,
3474,
3501,
3501,
3536
],
[
3537,
3537,
3564,
3564,
3603
],
[
3604,
3604,
3631,
3631,
3670
],
[
3671,
3671,
3698,
3698,
3747
],
[
3748,
3748,
3775,
3775,
3814
],
[
3815,
3815,
3842,
3842,
3891
],
[
3892,
3892,
3919,
3919,
3976
],
[
3977,
3977,
4004,
4004,
4047
],
[
4048,
4048,
4075,
4075,
4128
],
[
4129,
4129,
4156,
4156,
4209
],
[
4210,
4210,
4237,
4237,
4290
],
[
4291,
4291,
4318,
4318,
4371
],
[
4372,
4372,
4399,
4399,
4456
],
[
4458,
4458,
4481,
4481,
6528
],
[
6530,
6530,
6572,
6572,
6914
],
[
6916,
6916,
6948,
6948,
7172
],
[
7174,
7174,
7231,
7245,
8939
]
] | // unrolled version of the above
| float SH_0_0( in vec3 s ) { | vec3 n = s.zxy; return k01; } | // unrolled version of the above
float SH_0_0( in vec3 s ) { | 3 | 3 |
4ssSRl | iq | 2014-07-18T08:21:44 | // The MIT License
// Copyright © 2014 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// https://www.youtube.com/c/InigoQuilez
// https://iquilezles.org
// distance to a line (can't get simpler than this)
float line( in vec2 a, in vec2 b, in vec2 p )
{
vec2 pa = p - a;
vec2 ba = b - a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
return length( pa - ba*h );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 p = (-iResolution.xy + 2.0*fragCoord.xy) / iResolution.yy;
vec2 q = p;
vec2 c = vec2(0.0);
if( iMouse.z>0.0 ) c=(-iResolution.xy + 2.0*iMouse.xy) / iResolution.yy;
// background
vec3 col = vec3(0.5,0.85,0.9)*(1.0-0.2*length(p));
if( q.x>c.x && q.y>c.y ) col = pow(col,vec3(2.2));
// zoom in and out
p *= 1.0 + 0.2*sin(iTime*0.4);
// compute distance to a set of lines
float d = 1e20;
for( int i=0; i<7; i++ )
{
float anA = 6.2831*float(i+0)/7.0 + 0.15*iTime;
float anB = 6.2831*float(i+3)/7.0 + 0.20*iTime;
vec2 pA = 0.95*vec2( cos(anA), sin(anA) );
vec2 pB = 0.95*vec2( cos(anB), sin(anB) );
float h = line( pA, pB, p );
d = min( d, h );
}
// lines/start, left side of screen : not filtered
if( q.x<c.x )
{
if( d<0.12 ) col = vec3(0.0,0.0,0.0); // black
if( d<0.04 ) col = vec3(1.0,0.6,0.0); // orange
}
// lines/start, right side of the screen: filtered
else
{
float w = 0.5*fwidth(d);
w *= 1.5; // extra blur
if( q.y<c.y )
{
col = mix( vec3(0.0,0.0,0.0), col, smoothstep(-w,w,d-0.12) ); // black
col = mix( vec3(1.0,0.6,0.0), col, smoothstep(-w,w,d-0.04) ); // orange
}
else
{
col = mix( pow(vec3(0.0,0.0,0.0),vec3(2.2)), col, smoothstep(-w,w,d-0.12) ); // black
col = mix( pow(vec3(1.0,0.6,0.0),vec3(2.2)), col, smoothstep(-w,w,d-0.04) ); // orange
}
}
if( q.x>c.x && q.y>c.y )
col = pow( col, vec3(1.0/2.2) );
// draw left/right separating line
col = mix( vec3(0.0), col, smoothstep(0.007,0.008,abs(q.x-c.x)) );
col = mix( col, vec3(0.0), (1.0-smoothstep(0.007,0.008,abs(q.y-c.y)))*step(0.0,q.x-c.x) );
fragColor = vec4( col, 1.0 );
} | mit | [
0,
1196,
1243,
1243,
1363
] | [
[
0,
1196,
1243,
1243,
1363
],
[
1365,
1365,
1422,
1422,
3103
]
] | // The MIT License
// Copyright © 2014 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// https://www.youtube.com/c/InigoQuilez
// https://iquilezles.org
// distance to a line (can't get simpler than this)
| float line( in vec2 a, in vec2 b, in vec2 p )
{ |
vec2 pa = p - a;
vec2 ba = b - a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
return length( pa - ba*h );
} | // The MIT License
// Copyright © 2014 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// https://www.youtube.com/c/InigoQuilez
// https://iquilezles.org
// distance to a line (can't get simpler than this)
float line( in vec2 a, in vec2 b, in vec2 p )
{ | 3 | 5 |
4djXzz | otaviogood | 2014-08-21T06:53:07 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// various noise functions
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 47.0;
return fract(cos(f*3.333)*100003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(cos(f*3.333)*100003.9);
}
float mixP(float f0, float f1, float a)
{
return mix(f0, f1, a*a*(3.0-2.0*a));
}
const vec2 zeroOne = vec2(0.0, 1.0);
float noise2d(vec2 uv)
{
vec2 fr = fract(uv.xy);
vec2 fl = floor(uv.xy);
float h00 = Hash2d(fl);
float h10 = Hash2d(fl + zeroOne.yx);
float h01 = Hash2d(fl + zeroOne);
float h11 = Hash2d(fl + zeroOne.yy);
return mixP(mixP(h00, h10, fr.x), mixP(h01, h11, fr.x), fr.y);
}
float noise2dT(vec2 uv)
{
vec2 fr = fract(uv);
vec2 smoothv = fr*fr*(3.0-2.0*fr);
vec2 fl = floor(uv);
uv = smoothv + fl;
return textureLod(iChannel0, (uv + 0.5)/iChannelResolution[0].xy, 0.0).y; // use constant here instead?
}
float noise(vec3 uv)
{
vec3 fr = fract(uv.xyz);
vec3 fl = floor(uv.xyz);
float h000 = Hash3d(fl);
float h100 = Hash3d(fl + zeroOne.yxx);
float h010 = Hash3d(fl + zeroOne.xyx);
float h110 = Hash3d(fl + zeroOne.yyx);
float h001 = Hash3d(fl + zeroOne.xxy);
float h101 = Hash3d(fl + zeroOne.yxy);
float h011 = Hash3d(fl + zeroOne.xyy);
float h111 = Hash3d(fl + zeroOne.yyy);
return mixP(
mixP(mixP(h000, h100, fr.x), mixP(h010, h110, fr.x), fr.y),
mixP(mixP(h001, h101, fr.x), mixP(h011, h111, fr.x), fr.y)
, fr.z);
}
float PI=3.14159265;
vec3 saturate(vec3 a)
{
return clamp(a, 0.0, 1.0);
}
vec2 saturate(vec2 a)
{
return clamp(a, 0.0, 1.0);
}
float saturate(float a)
{
return clamp(a, 0.0, 1.0);
}
float Density(vec3 p)
{
//float ws = 0.06125*0.125;
//vec3 warp = vec3(noise(p*ws), noise(p*ws + 111.11), noise(p*ws + 7111.11));
float final = noise(p*0.06125);// + sin(iTime)*0.5-1.95 + warp.x*4.0;
float other = noise(p*0.06125 + 1234.567);
other -= 0.5;
final -= 0.5;
final = 0.1/(abs(final*final*other));
final += 0.5;
return final*0.0001;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// ---------------- First, set up the camera rays for ray marching ----------------
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;// - 0.5;
// Camera up vector.
vec3 camUp=vec3(0,1,0); // vuv
// Camera lookat.
vec3 camLookat=vec3(0,0.0,0); // vrp
float mx=iMouse.x/iResolution.x*PI*2.0 + iTime * 0.01;
float my=-iMouse.y/iResolution.y*10.0 + sin(iTime * 0.03)*0.2+0.2;//*PI/2.01;
vec3 camPos=vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*(200.2); // prp
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);//vpn
vec3 sideNorm=normalize(cross(camUp, camVec)); // u
vec3 upNorm=cross(camVec, sideNorm);//v
vec3 worldFacing=(camPos + camVec);//vcv
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;//scrCoord
vec3 relVec = normalize(worldPix - camPos);//scp
// --------------------------------------------------------------------------------
float t = 0.0;
float inc = 0.02;
float maxDepth = 70.0;
vec3 pos = vec3(0,0,0);
float density = 0.0;
// ray marching time
for (int i = 0; i < 37; i++) // This is the count of how many times the ray actually marches.
{
if ((t > maxDepth)) break;
pos = camPos + relVec * t;
float temp = Density(pos);
//temp *= saturate(t-1.0);
inc = 1.9 + temp*0.05; // add temp because this makes it look extra crazy!
density += temp * inc;
t += inc;
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this.
vec3 finalColor = vec3(0.01,0.1,1.0)* density*0.2;
// output the final color with sqrt for "gamma correction"
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
562,
589,
612,
612,
689
] | [
[
562,
589,
612,
612,
689
],
[
690,
690,
713,
713,
805
],
[
806,
806,
847,
847,
890
],
[
928,
928,
952,
952,
1225
],
[
1226,
1226,
1251,
1251,
1473
],
[
1474,
1474,
1496,
1496,
2055
],
[
2079,
2079,
2102,
2102,
2132
],
[
2133,
2133,
2156,
2156,
2186
],
[
2187,
2187,
2212,
2212,
2242
],
[
2244,
2244,
2267,
2381,
2625
],
[
2627,
2627,
2684,
2769,
4448
]
] | // various noise functions
| float Hash2d(vec2 uv)
{ |
float f = uv.x + uv.y * 47.0;
return fract(cos(f*3.333)*100003.9);
} | // various noise functions
float Hash2d(vec2 uv)
{ | 4 | 17 |
4dBXz3 | iq | 2014-10-24T08:55:07 | // The MIT License
// Copyright © 2014 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// A useful trick to avoid certain type of discontinuities
// during rendering and procedural content generation. More info:
//
// https://iquilezles.org/www/articles/dontflip/dontflip.htm
// Flip v if in the negative half plane defined by r (this works in 3D too)
vec2 flipIfNeg( in vec2 v, in vec2 r )
{
float k = dot(v,r);
return (k>0.0) ? v : -v;
}
// Reflect v if in the negative half plane defined by r (this works in 3D too)
vec2 reflIfNeg( in vec2 v, in vec2 r )
{
float k = dot(v,r);
return (k>0.0) ? v : v-2.0*r*k;
}
// Clip v if in the negative half plane defined by r (this works in 3D too)
vec2 clipIfNeg( in vec2 v, in vec2 r )
{
float k = dot(v,r);
return (k>0.0) ? v : (v-r*k)*inversesqrt(1.0-k*k/dot(v,v));
}
//===============================================================
float sdLine( in vec2 p, in vec2 a, in vec2 b )
{
vec2 pa = p - a;
vec2 ba = b - a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
return length( pa - ba*h );
}
// https://www.shadertoy.com/view/slj3Dd
float sdArrow( in vec2 p, vec2 a, vec2 b, float w1, float w2 )
{
const float k = 3.0;
vec2 ba = b - a;
float l2 = dot(ba,ba);
float l = sqrt(l2);
p = p-a;
p = mat2(ba.x,-ba.y,ba.y,ba.x)*p/l;
p.y = abs(p.y);
vec2 pz = p-vec2(l-w2*k,w2);
vec2 q = p;
q.x -= clamp( q.x, 0.0, l-w2*k );
q.y -= w1;
float di = dot(q,q);
q = pz;
q.y -= clamp( q.y, w1-w2, 0.0 );
di = min( di, dot(q,q) );
if( p.x<w1 )
{
q = p;
q.y -= clamp( q.y, 0.0, w1 );
di = min( di, dot(q,q) );
}
if( pz.x>0.0 )
{
q = pz;
q -= vec2(k,-1.0)*clamp( (q.x*k-q.y)/(k*k+1.0), 0.0, w2 );
di = min( di, dot(q,q) );
}
float si = 1.0;
float z = l - p.x;
if( min(p.x,z)>0.0 )
{
float h = (pz.x<0.0) ? w1 : z/k;
if( p.y<h ) si = -1.0;
}
return si*sqrt(di);
}
//===============================================================
float line( in vec2 p, in vec2 a, in vec2 b, float w , float e)
{
return 1.0 - smoothstep( -e, e, sdLine( p, a, b ) - w );
}
float arrow( in vec2 p, in vec2 a, in vec2 b, float w1, float w2, float e )
{
return 1.0 - smoothstep( -e, e, sdArrow( p, a, b, w1, w2) );
}
//===============================================================
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 p = fragCoord/iResolution.x;
vec2 q = p;
p.x = mod(p.x,1.0/3.0) - 1.0/6.0;
p.y -= 0.5*iResolution.y/iResolution.x;
p.y += 0.04;
float e = 1.0/iResolution.x;
float time = iTime;
//time = mod( time, 8.0 );
float an = 0.3*(1.0-smoothstep(-0.1,0.1,sin(0.125*6.283185*(time+1.0/2.0))));
vec2 r = vec2( sin(an), cos(an) );
vec2 pe = r.yx*vec2(-1.0,1.0);
vec3 col = vec3(0.15);
col = vec3(21,32,43)/255.0;
float wi = 0.0015;
float s = dot(p,r);
if( s>0.0 )
{
float r = length(p);
if( r<0.12 )
{
float nr = r/0.12;
col += 0.25*nr*nr;
}
col = mix(col,vec3(0.7), 1.0-smoothstep(-e,e,abs(r-0.12)-wi));
}
col = mix( col, vec3(0.7), arrow(p, vec2(0.0), r*0.18, wi, 0.01, e) );
col = mix( col, vec3(0.7), line(p, -0.12*pe, 0.12*pe, wi, e) );
{
float an = cos(0.5*6.283185*time);
vec2 v = vec2( -cos(an), sin(an) )*0.12;
vec2 f;
if( q.x<0.333 ) f = flipIfNeg( v, r );
else if( q.x<0.666 ) f = reflIfNeg( v, r );
else f = clipIfNeg( v, r );
col = mix( col, col+0.2, arrow(p, vec2(0.0), v, wi, 5.0*wi, e) );
col = mix( col, vec3(1.0,0.7,0.2), arrow(p, vec2(0.0), f, wi, 5.0*wi, e) );
}
fragColor = vec4( col, 1.0 );
} | mit | [
1272,
1348,
1388,
1388,
1443
] | [
[
1272,
1348,
1388,
1388,
1443
],
[
1445,
1524,
1564,
1564,
1626
],
[
1628,
1704,
1744,
1744,
1834
],
[
1903,
1903,
1952,
1952,
2072
],
[
2074,
2115,
2179,
2179,
2977
],
[
3046,
3046,
3111,
3111,
3174
],
[
3176,
3176,
3253,
3253,
3320
],
[
3389,
3389,
3446,
3446,
4797
]
] | // Flip v if in the negative half plane defined by r (this works in 3D too)
| vec2 flipIfNeg( in vec2 v, in vec2 r )
{ |
float k = dot(v,r);
return (k>0.0) ? v : -v;
} | // Flip v if in the negative half plane defined by r (this works in 3D too)
vec2 flipIfNeg( in vec2 v, in vec2 r )
{ | 1 | 1 |
4dBXz3 | iq | 2014-10-24T08:55:07 | // The MIT License
// Copyright © 2014 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// A useful trick to avoid certain type of discontinuities
// during rendering and procedural content generation. More info:
//
// https://iquilezles.org/www/articles/dontflip/dontflip.htm
// Flip v if in the negative half plane defined by r (this works in 3D too)
vec2 flipIfNeg( in vec2 v, in vec2 r )
{
float k = dot(v,r);
return (k>0.0) ? v : -v;
}
// Reflect v if in the negative half plane defined by r (this works in 3D too)
vec2 reflIfNeg( in vec2 v, in vec2 r )
{
float k = dot(v,r);
return (k>0.0) ? v : v-2.0*r*k;
}
// Clip v if in the negative half plane defined by r (this works in 3D too)
vec2 clipIfNeg( in vec2 v, in vec2 r )
{
float k = dot(v,r);
return (k>0.0) ? v : (v-r*k)*inversesqrt(1.0-k*k/dot(v,v));
}
//===============================================================
float sdLine( in vec2 p, in vec2 a, in vec2 b )
{
vec2 pa = p - a;
vec2 ba = b - a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
return length( pa - ba*h );
}
// https://www.shadertoy.com/view/slj3Dd
float sdArrow( in vec2 p, vec2 a, vec2 b, float w1, float w2 )
{
const float k = 3.0;
vec2 ba = b - a;
float l2 = dot(ba,ba);
float l = sqrt(l2);
p = p-a;
p = mat2(ba.x,-ba.y,ba.y,ba.x)*p/l;
p.y = abs(p.y);
vec2 pz = p-vec2(l-w2*k,w2);
vec2 q = p;
q.x -= clamp( q.x, 0.0, l-w2*k );
q.y -= w1;
float di = dot(q,q);
q = pz;
q.y -= clamp( q.y, w1-w2, 0.0 );
di = min( di, dot(q,q) );
if( p.x<w1 )
{
q = p;
q.y -= clamp( q.y, 0.0, w1 );
di = min( di, dot(q,q) );
}
if( pz.x>0.0 )
{
q = pz;
q -= vec2(k,-1.0)*clamp( (q.x*k-q.y)/(k*k+1.0), 0.0, w2 );
di = min( di, dot(q,q) );
}
float si = 1.0;
float z = l - p.x;
if( min(p.x,z)>0.0 )
{
float h = (pz.x<0.0) ? w1 : z/k;
if( p.y<h ) si = -1.0;
}
return si*sqrt(di);
}
//===============================================================
float line( in vec2 p, in vec2 a, in vec2 b, float w , float e)
{
return 1.0 - smoothstep( -e, e, sdLine( p, a, b ) - w );
}
float arrow( in vec2 p, in vec2 a, in vec2 b, float w1, float w2, float e )
{
return 1.0 - smoothstep( -e, e, sdArrow( p, a, b, w1, w2) );
}
//===============================================================
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 p = fragCoord/iResolution.x;
vec2 q = p;
p.x = mod(p.x,1.0/3.0) - 1.0/6.0;
p.y -= 0.5*iResolution.y/iResolution.x;
p.y += 0.04;
float e = 1.0/iResolution.x;
float time = iTime;
//time = mod( time, 8.0 );
float an = 0.3*(1.0-smoothstep(-0.1,0.1,sin(0.125*6.283185*(time+1.0/2.0))));
vec2 r = vec2( sin(an), cos(an) );
vec2 pe = r.yx*vec2(-1.0,1.0);
vec3 col = vec3(0.15);
col = vec3(21,32,43)/255.0;
float wi = 0.0015;
float s = dot(p,r);
if( s>0.0 )
{
float r = length(p);
if( r<0.12 )
{
float nr = r/0.12;
col += 0.25*nr*nr;
}
col = mix(col,vec3(0.7), 1.0-smoothstep(-e,e,abs(r-0.12)-wi));
}
col = mix( col, vec3(0.7), arrow(p, vec2(0.0), r*0.18, wi, 0.01, e) );
col = mix( col, vec3(0.7), line(p, -0.12*pe, 0.12*pe, wi, e) );
{
float an = cos(0.5*6.283185*time);
vec2 v = vec2( -cos(an), sin(an) )*0.12;
vec2 f;
if( q.x<0.333 ) f = flipIfNeg( v, r );
else if( q.x<0.666 ) f = reflIfNeg( v, r );
else f = clipIfNeg( v, r );
col = mix( col, col+0.2, arrow(p, vec2(0.0), v, wi, 5.0*wi, e) );
col = mix( col, vec3(1.0,0.7,0.2), arrow(p, vec2(0.0), f, wi, 5.0*wi, e) );
}
fragColor = vec4( col, 1.0 );
} | mit | [
1445,
1524,
1564,
1564,
1626
] | [
[
1272,
1348,
1388,
1388,
1443
],
[
1445,
1524,
1564,
1564,
1626
],
[
1628,
1704,
1744,
1744,
1834
],
[
1903,
1903,
1952,
1952,
2072
],
[
2074,
2115,
2179,
2179,
2977
],
[
3046,
3046,
3111,
3111,
3174
],
[
3176,
3176,
3253,
3253,
3320
],
[
3389,
3389,
3446,
3446,
4797
]
] | // Reflect v if in the negative half plane defined by r (this works in 3D too)
| vec2 reflIfNeg( in vec2 v, in vec2 r )
{ |
float k = dot(v,r);
return (k>0.0) ? v : v-2.0*r*k;
} | // Reflect v if in the negative half plane defined by r (this works in 3D too)
vec2 reflIfNeg( in vec2 v, in vec2 r )
{ | 1 | 1 |
4dBXz3 | iq | 2014-10-24T08:55:07 | // The MIT License
// Copyright © 2014 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// A useful trick to avoid certain type of discontinuities
// during rendering and procedural content generation. More info:
//
// https://iquilezles.org/www/articles/dontflip/dontflip.htm
// Flip v if in the negative half plane defined by r (this works in 3D too)
vec2 flipIfNeg( in vec2 v, in vec2 r )
{
float k = dot(v,r);
return (k>0.0) ? v : -v;
}
// Reflect v if in the negative half plane defined by r (this works in 3D too)
vec2 reflIfNeg( in vec2 v, in vec2 r )
{
float k = dot(v,r);
return (k>0.0) ? v : v-2.0*r*k;
}
// Clip v if in the negative half plane defined by r (this works in 3D too)
vec2 clipIfNeg( in vec2 v, in vec2 r )
{
float k = dot(v,r);
return (k>0.0) ? v : (v-r*k)*inversesqrt(1.0-k*k/dot(v,v));
}
//===============================================================
float sdLine( in vec2 p, in vec2 a, in vec2 b )
{
vec2 pa = p - a;
vec2 ba = b - a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
return length( pa - ba*h );
}
// https://www.shadertoy.com/view/slj3Dd
float sdArrow( in vec2 p, vec2 a, vec2 b, float w1, float w2 )
{
const float k = 3.0;
vec2 ba = b - a;
float l2 = dot(ba,ba);
float l = sqrt(l2);
p = p-a;
p = mat2(ba.x,-ba.y,ba.y,ba.x)*p/l;
p.y = abs(p.y);
vec2 pz = p-vec2(l-w2*k,w2);
vec2 q = p;
q.x -= clamp( q.x, 0.0, l-w2*k );
q.y -= w1;
float di = dot(q,q);
q = pz;
q.y -= clamp( q.y, w1-w2, 0.0 );
di = min( di, dot(q,q) );
if( p.x<w1 )
{
q = p;
q.y -= clamp( q.y, 0.0, w1 );
di = min( di, dot(q,q) );
}
if( pz.x>0.0 )
{
q = pz;
q -= vec2(k,-1.0)*clamp( (q.x*k-q.y)/(k*k+1.0), 0.0, w2 );
di = min( di, dot(q,q) );
}
float si = 1.0;
float z = l - p.x;
if( min(p.x,z)>0.0 )
{
float h = (pz.x<0.0) ? w1 : z/k;
if( p.y<h ) si = -1.0;
}
return si*sqrt(di);
}
//===============================================================
float line( in vec2 p, in vec2 a, in vec2 b, float w , float e)
{
return 1.0 - smoothstep( -e, e, sdLine( p, a, b ) - w );
}
float arrow( in vec2 p, in vec2 a, in vec2 b, float w1, float w2, float e )
{
return 1.0 - smoothstep( -e, e, sdArrow( p, a, b, w1, w2) );
}
//===============================================================
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 p = fragCoord/iResolution.x;
vec2 q = p;
p.x = mod(p.x,1.0/3.0) - 1.0/6.0;
p.y -= 0.5*iResolution.y/iResolution.x;
p.y += 0.04;
float e = 1.0/iResolution.x;
float time = iTime;
//time = mod( time, 8.0 );
float an = 0.3*(1.0-smoothstep(-0.1,0.1,sin(0.125*6.283185*(time+1.0/2.0))));
vec2 r = vec2( sin(an), cos(an) );
vec2 pe = r.yx*vec2(-1.0,1.0);
vec3 col = vec3(0.15);
col = vec3(21,32,43)/255.0;
float wi = 0.0015;
float s = dot(p,r);
if( s>0.0 )
{
float r = length(p);
if( r<0.12 )
{
float nr = r/0.12;
col += 0.25*nr*nr;
}
col = mix(col,vec3(0.7), 1.0-smoothstep(-e,e,abs(r-0.12)-wi));
}
col = mix( col, vec3(0.7), arrow(p, vec2(0.0), r*0.18, wi, 0.01, e) );
col = mix( col, vec3(0.7), line(p, -0.12*pe, 0.12*pe, wi, e) );
{
float an = cos(0.5*6.283185*time);
vec2 v = vec2( -cos(an), sin(an) )*0.12;
vec2 f;
if( q.x<0.333 ) f = flipIfNeg( v, r );
else if( q.x<0.666 ) f = reflIfNeg( v, r );
else f = clipIfNeg( v, r );
col = mix( col, col+0.2, arrow(p, vec2(0.0), v, wi, 5.0*wi, e) );
col = mix( col, vec3(1.0,0.7,0.2), arrow(p, vec2(0.0), f, wi, 5.0*wi, e) );
}
fragColor = vec4( col, 1.0 );
} | mit | [
1628,
1704,
1744,
1744,
1834
] | [
[
1272,
1348,
1388,
1388,
1443
],
[
1445,
1524,
1564,
1564,
1626
],
[
1628,
1704,
1744,
1744,
1834
],
[
1903,
1903,
1952,
1952,
2072
],
[
2074,
2115,
2179,
2179,
2977
],
[
3046,
3046,
3111,
3111,
3174
],
[
3176,
3176,
3253,
3253,
3320
],
[
3389,
3389,
3446,
3446,
4797
]
] | // Clip v if in the negative half plane defined by r (this works in 3D too)
| vec2 clipIfNeg( in vec2 v, in vec2 r )
{ |
float k = dot(v,r);
return (k>0.0) ? v : (v-r*k)*inversesqrt(1.0-k*k/dot(v,v));
} | // Clip v if in the negative half plane defined by r (this works in 3D too)
vec2 clipIfNeg( in vec2 v, in vec2 r )
{ | 1 | 1 |
4dBXz3 | iq | 2014-10-24T08:55:07 | // The MIT License
// Copyright © 2014 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// A useful trick to avoid certain type of discontinuities
// during rendering and procedural content generation. More info:
//
// https://iquilezles.org/www/articles/dontflip/dontflip.htm
// Flip v if in the negative half plane defined by r (this works in 3D too)
vec2 flipIfNeg( in vec2 v, in vec2 r )
{
float k = dot(v,r);
return (k>0.0) ? v : -v;
}
// Reflect v if in the negative half plane defined by r (this works in 3D too)
vec2 reflIfNeg( in vec2 v, in vec2 r )
{
float k = dot(v,r);
return (k>0.0) ? v : v-2.0*r*k;
}
// Clip v if in the negative half plane defined by r (this works in 3D too)
vec2 clipIfNeg( in vec2 v, in vec2 r )
{
float k = dot(v,r);
return (k>0.0) ? v : (v-r*k)*inversesqrt(1.0-k*k/dot(v,v));
}
//===============================================================
float sdLine( in vec2 p, in vec2 a, in vec2 b )
{
vec2 pa = p - a;
vec2 ba = b - a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
return length( pa - ba*h );
}
// https://www.shadertoy.com/view/slj3Dd
float sdArrow( in vec2 p, vec2 a, vec2 b, float w1, float w2 )
{
const float k = 3.0;
vec2 ba = b - a;
float l2 = dot(ba,ba);
float l = sqrt(l2);
p = p-a;
p = mat2(ba.x,-ba.y,ba.y,ba.x)*p/l;
p.y = abs(p.y);
vec2 pz = p-vec2(l-w2*k,w2);
vec2 q = p;
q.x -= clamp( q.x, 0.0, l-w2*k );
q.y -= w1;
float di = dot(q,q);
q = pz;
q.y -= clamp( q.y, w1-w2, 0.0 );
di = min( di, dot(q,q) );
if( p.x<w1 )
{
q = p;
q.y -= clamp( q.y, 0.0, w1 );
di = min( di, dot(q,q) );
}
if( pz.x>0.0 )
{
q = pz;
q -= vec2(k,-1.0)*clamp( (q.x*k-q.y)/(k*k+1.0), 0.0, w2 );
di = min( di, dot(q,q) );
}
float si = 1.0;
float z = l - p.x;
if( min(p.x,z)>0.0 )
{
float h = (pz.x<0.0) ? w1 : z/k;
if( p.y<h ) si = -1.0;
}
return si*sqrt(di);
}
//===============================================================
float line( in vec2 p, in vec2 a, in vec2 b, float w , float e)
{
return 1.0 - smoothstep( -e, e, sdLine( p, a, b ) - w );
}
float arrow( in vec2 p, in vec2 a, in vec2 b, float w1, float w2, float e )
{
return 1.0 - smoothstep( -e, e, sdArrow( p, a, b, w1, w2) );
}
//===============================================================
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 p = fragCoord/iResolution.x;
vec2 q = p;
p.x = mod(p.x,1.0/3.0) - 1.0/6.0;
p.y -= 0.5*iResolution.y/iResolution.x;
p.y += 0.04;
float e = 1.0/iResolution.x;
float time = iTime;
//time = mod( time, 8.0 );
float an = 0.3*(1.0-smoothstep(-0.1,0.1,sin(0.125*6.283185*(time+1.0/2.0))));
vec2 r = vec2( sin(an), cos(an) );
vec2 pe = r.yx*vec2(-1.0,1.0);
vec3 col = vec3(0.15);
col = vec3(21,32,43)/255.0;
float wi = 0.0015;
float s = dot(p,r);
if( s>0.0 )
{
float r = length(p);
if( r<0.12 )
{
float nr = r/0.12;
col += 0.25*nr*nr;
}
col = mix(col,vec3(0.7), 1.0-smoothstep(-e,e,abs(r-0.12)-wi));
}
col = mix( col, vec3(0.7), arrow(p, vec2(0.0), r*0.18, wi, 0.01, e) );
col = mix( col, vec3(0.7), line(p, -0.12*pe, 0.12*pe, wi, e) );
{
float an = cos(0.5*6.283185*time);
vec2 v = vec2( -cos(an), sin(an) )*0.12;
vec2 f;
if( q.x<0.333 ) f = flipIfNeg( v, r );
else if( q.x<0.666 ) f = reflIfNeg( v, r );
else f = clipIfNeg( v, r );
col = mix( col, col+0.2, arrow(p, vec2(0.0), v, wi, 5.0*wi, e) );
col = mix( col, vec3(1.0,0.7,0.2), arrow(p, vec2(0.0), f, wi, 5.0*wi, e) );
}
fragColor = vec4( col, 1.0 );
} | mit | [
2074,
2115,
2179,
2179,
2977
] | [
[
1272,
1348,
1388,
1388,
1443
],
[
1445,
1524,
1564,
1564,
1626
],
[
1628,
1704,
1744,
1744,
1834
],
[
1903,
1903,
1952,
1952,
2072
],
[
2074,
2115,
2179,
2179,
2977
],
[
3046,
3046,
3111,
3111,
3174
],
[
3176,
3176,
3253,
3253,
3320
],
[
3389,
3389,
3446,
3446,
4797
]
] | // https://www.shadertoy.com/view/slj3Dd
| float sdArrow( in vec2 p, vec2 a, vec2 b, float w1, float w2 )
{ |
const float k = 3.0;
vec2 ba = b - a;
float l2 = dot(ba,ba);
float l = sqrt(l2);
p = p-a;
p = mat2(ba.x,-ba.y,ba.y,ba.x)*p/l;
p.y = abs(p.y);
vec2 pz = p-vec2(l-w2*k,w2);
vec2 q = p;
q.x -= clamp( q.x, 0.0, l-w2*k );
q.y -= w1;
float di = dot(q,q);
q = pz;
q.y -= clamp( q.y, w1-w2, 0.0 );
di = min( di, dot(q,q) );
if( p.x<w1 )
{
q = p;
q.y -= clamp( q.y, 0.0, w1 );
di = min( di, dot(q,q) );
}
if( pz.x>0.0 )
{
q = pz;
q -= vec2(k,-1.0)*clamp( (q.x*k-q.y)/(k*k+1.0), 0.0, w2 );
di = min( di, dot(q,q) );
}
float si = 1.0;
float z = l - p.x;
if( min(p.x,z)>0.0 )
{
float h = (pz.x<0.0) ? w1 : z/k;
if( p.y<h ) si = -1.0;
}
return si*sqrt(di);
} | // https://www.shadertoy.com/view/slj3Dd
float sdArrow( in vec2 p, vec2 a, vec2 b, float w1, float w2 )
{ | 1 | 2 |
ld2SzK | otaviogood | 2014-10-27T05:24:30 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
-Otavio Good
*/
// The noise function in this was inspired by IQ's "Terrain Tubes" shader. I never really figured out
// his function completely, so I'm not sure of the exact similarities. It's nice though because it
// works the same on all computers (I think). It's not based on a hash that changes from computer to
// computer. That means I can finally rely on the terrain being the same and make a camera path. :)
// It's also a much faster noise function, although it can look a bit repetitive.
#define MOTION_BLUR
#define MOVING_SUN
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 47.0;
return fract(cos(f*3.333)*100003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(cos(f*3.333)*100003.9);
}
float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
//else return new float3(x, cos * y - sin * z, sin * y + cos * z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
//else return new float3(cos * x + sin * z, y, -sin * x + cos * z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
// This function basically is a procedural environment map that makes the sun
vec3 sunCol = vec3(258.0, 208.0, 100.0) / 4255.0;//unfortunately, i seem to have 2 different sun colors. :(
vec3 GetSunColorReflection(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.015 / dist;
sunIntensity = pow(sunIntensity, 0.3)*100.0;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.0425;
}
vec3 GetSunColorSmall(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.05 / dist;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.025;
}
// This is a spline used for the camera path
vec4 CatmullRom(vec4 p0, vec4 p1, vec4 p2, vec4 p3, float t)
{
float t2 = t*t;
float t3 = t*t*t;
return 0.5 *((2.0 * p1) +
(-p0 + p2) * t +
(2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 +
(-p0 + 3.0 * p1- 3.0 * p2 + p3) * t3);
}
// This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.739513; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
float SpiralNoiseC(vec3 p)
{
float n = 0.0; // noise amount
float iter = 1.0;
for (int i = 0; i < 8; i++)
{
// add sin and cos scaled inverse with the frequency
n += -abs(sin(p.y*iter) + cos(p.x*iter)) / iter; // abs for a ridged look
// rotate by adding perpendicular and scaling down
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
// rotate on other axis
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
// increase the frequency
iter *= 1.733733;
}
return n;
}
float SpiralNoiseD(vec3 p)
{
float n = 0.0;
float iter = 1.0;
for (int i = 0; i < 6; i++)
{
n += abs(sin(p.y*iter) + cos(p.x*iter)) / iter; // abs for a ridged look
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.733733;
}
return n;
}
float SpiralNoise3D(vec3 p)
{
float n = 0.0;
float iter = 1.0;
for (int i = 0; i < 5; i++)
{
n += (sin(p.y*iter) + cos(p.x*iter)) / iter;
//p.xy += vec2(p.y, -p.x) * nudge;
//p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.33733;
}
return n;
}
// These are the xyz camera positions and a left/right facing angle relative to the path line
// I think webgl glsl can only access arrays using a constant, so I'm writing all these out.
// Someone please tell me if I'm wrong.
vec4 c00 = vec4(3.5, 2.0, 13.1, 0.0); // start point
vec4 c01 = vec4(12.5, 2.2, 17.0, 0.0); // run up to canyon 2 before hole in large rock face
vec4 c02 = vec4(21.5, 4.0, 8.1, 0.0); // canyon 2 before hole in large rock face
vec4 c03 = vec4(21.0, 5.0, 1.1, -0.5); // before hole in large rock face
vec4 c04 = vec4(17.8, 5.4, -0.2, 0.0); // hole in large rock face
vec4 c05 = vec4(14.7, 2.5, 1.4, 0.0); // after hole in large rock face
vec4 c06 = vec4(7.9, 2.3, -2.1, 0.0);
vec4 c07 = vec4(0.5, -0.7, -3.5, 1.0);
vec4 c08 = vec4(-3.0, -1.0, -3.5, 1.3);
vec4 c09 = vec4(-3.5, -1.0, 4.0, 1.3);
vec4 c10 = vec4(3.0, -0.7, 3.3, 0.8);
vec4 c11 = vec4(3.5, -1.0, -4.75, 0.0);
vec4 c12 = vec4(-6.0, -0.2, 1.0, 3.14);
vec4 c13 = vec4(-6.0, -1.0, 5.5, 0.0);
vec4 cXX = vec4(0.0, 3.0, 0.0, 0.0);
float camPathOffset = 0.0; // where to start on the camera path - parametric t var for catmull-rom spline
vec3 camPos = vec3(0.0), camFacing;
vec3 camLookat=vec3(0,0.0,0);
float waterLevel = 1.5;
// from a time t, this finds where in the camera path you are.
// It uses Catmull-Rom splines
vec4 CamPos(float t)
{
t = mod(t, 14.0); // repeat after 14 time units
float bigTime = floor(t);
float smallTime = fract(t);
// Can't do arrays right, so write this all out.
if (bigTime == 0.0) return CatmullRom(c00, c01, c02, c03, smallTime);
if (bigTime == 1.0) return CatmullRom(c01, c02, c03, c04, smallTime);
if (bigTime == 2.0) return CatmullRom(c02, c03, c04, c05, smallTime);
if (bigTime == 3.0) return CatmullRom(c03, c04, c05, c06, smallTime);
if (bigTime == 4.0) return CatmullRom(c04, c05, c06, c07, smallTime);
if (bigTime == 5.0) return CatmullRom(c05, c06, c07, c08, smallTime);
if (bigTime == 6.0) return CatmullRom(c06, c07, c08, c09, smallTime);
if (bigTime == 7.0) return CatmullRom(c07, c08, c09, c10, smallTime);
if (bigTime == 8.0) return CatmullRom(c08, c09, c10, c11, smallTime);
if (bigTime == 9.0) return CatmullRom(c09, c10, c11, c12, smallTime);
if (bigTime == 10.0) return CatmullRom(c10, c11, c12, c13, smallTime);
if (bigTime == 11.0) return CatmullRom(c11, c12, c13, c00, smallTime);
if (bigTime == 12.0) return CatmullRom(c12, c13, c00, c01, smallTime);
if (bigTime == 13.0) return CatmullRom(c13, c00, c01, c02, smallTime);
return vec4(0.0);
}
float DistanceToObject(vec3 p)
{
float final = p.y + 4.5;
final -= SpiralNoiseC(p.xyz); // mid-range noise
final += SpiralNoiseC(p.zxy*0.123+100.0)*3.0; // large scale terrain features
final -= SpiralNoise3D(p); // more large scale features, but 3d, so not just a height map.
final -= SpiralNoise3D(p*49.0)*0.0625*0.125; // small scale noise for variation
final = min(final, length(p) - 1.99); // sphere in center
final = min(final, p.y + waterLevel); // water
//final = min(final, length(p-camLookat) - 0.3);
return final;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// ---------------- First, set up the camera rays for ray marching ----------------
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
// Camera up vector.
vec3 camUp=vec3(0,1,0); // vuv
// Camera lookat.
camLookat=vec3(0,0.0,0); // vrp
/* if (iTime == 0.0) // for debugging with manual camera
{
camPos = cXX.xyz;
camLookat = vec3(0.0)*cXX.xyz;
}*/
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0;// + iTime * 0.1;
float my=-iMouse.y/iResolution.y*10.0;// + sin(iTime * 0.3)*0.2+0.2;//*PI/2.01;
camPos += vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*(5.2); // prp
// set time for moving camera along path
float timeLine = iTime*0.2 + camPathOffset;
camFacing = camLookat + camPos;
// without this if condition, the mac doesn't work. mysterious. :(
if (iTime != -1.0)
{
vec4 catmullA = CamPos(timeLine);
// get a smoother derivative even though the spline is not C2 continuous.
// Also look ahead a bit so the camera leads the motion
vec4 catmullB = CamPos(timeLine + 0.3);
#ifdef MOTION_BLUR
vec4 catmullC = CamPos(timeLine + 0.004); // adjust for camera motion blur
vec4 catmullBlur = mix(catmullA, catmullC, Hash2d(uv)); // motion blur along camera path
camPos = catmullBlur.xyz;
// face camera along derivate of motion path
camFacing = normalize(catmullB.xyz - catmullA.xyz);
// rotate camera based on w component of camera path vectors
camFacing = RotateY(camFacing, -catmullBlur.w);
#else
camPos = catmullA.xyz;
// face camera along derivate of motion path
camFacing = normalize(catmullB.xyz - catmullA.xyz);
// rotate camera based on w component of camera path vectors
camFacing = RotateY(camFacing, -catmullA.w);
#endif
camFacing = RotateY(camFacing, -mx);
camLookat = camPos + camFacing;
}
// add randomness to camera for depth-of-field look close up.
//camPos += vec3(Hash2d(uv)*0.91, Hash2d(uv+37.0), Hash2d(uv+47.0))*0.01;
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);//vpn
vec3 sideNorm=normalize(cross(camUp, camVec)); // u
vec3 upNorm=cross(camVec, sideNorm);//v
vec3 worldFacing=(camPos + camVec);//vcv
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;//scrCoord
vec3 relVec = normalize(worldPix - camPos);//scp
// --------------------------------------------------------------------------------
float dist = 0.05;
float t = 0.0;
float inc = 0.02;
float maxDepth = 110.0;
vec3 pos = vec3(0,0,0);
// ray marching time
for (int i = 0; i < 200; i++) // This is the count of the max times the ray actually marches.
{
if ((t > maxDepth) || (abs(dist) < 0.0075)) break;
pos = camPos + relVec * t;
// *******************************************************
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry.
// *******************************************************
dist = DistanceToObject(pos);
t += dist * 0.25; // because deformations mess up distance function.
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
#ifdef MOVING_SUN
vec3 sunDir = normalize(vec3(sin(iTime*0.047-1.5), cos(iTime*0.047-1.5), -0.5));
#else
vec3 sunDir = normalize(vec3(0.93, 1.0, -1.5));
#endif
// This makes the sky fade at sunset
float skyMultiplier = saturate(sunDir.y+0.7);
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
if (abs(dist) < 0.75)
//if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(0.005, 0, 0);
vec3 normal = vec3(dist - DistanceToObject(pos - smallVec.xyy),
dist - DistanceToObject(pos - smallVec.yxy),
dist - DistanceToObject(pos - smallVec.yyx));
/*if (pos.y <= waterLevel-2.995) // water waves?
{
normal += SpiralNoise3D(pos*32.0+vec3(iTime*8.0,0.0,0.0))*0.0001;
normal += SpiralNoise3D(pos*27.0+vec3(0.0,0.0, iTime* 10.333))*0.0001;
normal += SpiralNoiseD(pos*37.0+vec3(0.0,iTime* 14.333,0.0))*0.0002;
}*/
normal = normalize(normal);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff - so the green sphere light source can also have ambient.
float ambientS = 1.0;
//ambient *= saturate(DistanceToObject(pos + normal * 0.1)*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2)*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4)*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8)*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6)*1.25*0.5);
ambient *= saturate(DistanceToObject(pos + normal * 3.2)*1.25*0.25);
ambient *= saturate(DistanceToObject(pos + normal * 6.4)*1.25*0.125);
//ambient = max(0.05, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// Trace a ray toward the sun for sun shadows
float sunShadow = 1.0;
float iter = 0.2;
for (int i = 0; i < 10; i++)
{
float tempDist = DistanceToObject(pos + sunDir * iter);
sunShadow *= saturate(tempDist*10.0);
if (tempDist <= 0.0) break;
iter *= 1.5; // constant is more reliable than distance-based
//iter += max(0.2, tempDist)*1.2;
}
float sunSet = saturate(sunDir.y*4.0); // sunset dims the sun
sunShadow = saturate(sunShadow) * sunSet;
// calculate the reflection vector for highlights
vec3 ref = reflect(relVec, normal);
// pulse the ball light source
vec3 ballGlow = vec3(0.1, 0.97, 0.1) * abs(SpiralNoise3D(vec3(iTime*1.3)));
// ------ Calculate texture color of the rock ------
// basic orange and white blended together with noise
vec3 texColor = mix(vec3(0.95, 1.0, 1.0), vec3(0.9, 0.7, 0.5), pow(abs(SpiralNoise3D(pos*1.0)-1.0), 0.6) );
// make the undersides darker greenish
texColor = mix(vec3(0.2, 0.2, 0.1), texColor, saturate(normal.y));
// fade to reddish/orange closer to the water level
texColor = mix(texColor, vec3(0.64, 0.2, 0.1) , saturate(-0.4-pos.y));
// some more variation to the color vertically
texColor = mix(texColor, vec3(0.2, 0.13, 0.02) , pow(saturate(pos.y*0.125+0.5), 2.0));
// give the rock a stratified, layered look
float rockLayers = abs(cos(pos.y*1.5+ SpiralNoiseD(pos*vec3(1.0, 2.0, 1.0)*4.0)*0.2 ));
texColor += vec3(0.7, 0.4, 0.3)*(1.0-pow(rockLayers, 0.3));
// make the water orange. I'm trying for that "nickel tailings" look.
texColor = mix(texColor, vec3(1.4, 0.15, 0.05) + SpiralNoise3D(pos)*0.025, saturate((-pos.y-1.45)*17.0));
// make the sphere white
if (length(pos) <= 2.01) texColor = vec3(1.0);
// don't let it get too saturated or dark
texColor = max(texColor, 0.05);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(1.0, 0.75, 0.75) * saturate(dot(sunDir, normal)) * sunShadow*1.5;
// sky color, hemisphere light equation approximation, anbient occlusion, sunset multiplier
lightColor += vec3(1.0,0.3,0.6) * ( dot(sunDir, normal) * 0.5 + 0.5 ) * ambient * 0.25 * skyMultiplier;
// Make the ball cast light. Distance to the 4th light falloff looked best. Use local ambient occlusion.
float lp = length(pos) - 1.0;
lightColor += ambientS*(ballGlow*1.2 * saturate(dot(normal, -pos)*0.5+0.5) / (lp*lp*lp*lp));
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// Make the water reflect the sun (leaving out sky reflection for no good reason)
vec3 refColor = GetSunColorReflection(ref, sunDir)*0.68;
finalColor += refColor * sunShadow * saturate(normal.y*normal.y) * saturate(-(pos.y+1.35)*16.0);
// make the ball itself glow
finalColor += pow(saturate(1.0 - length(pos)*0.4925), 0.65) * ballGlow*6.1;
// fog that fades to reddish plus the sun color so that fog is brightest towards sun
finalColor = mix(vec3(1.0, 0.41, 0.41)*skyMultiplier + min(vec3(0.25),GetSunColorSmall(relVec, sunDir))*2.0*sunSet, finalColor, exp(-t*0.03));
}
else
{
// Our ray trace hit nothing, so draw sky.
// fade the sky color, multiply sunset dimming
finalColor = mix(vec3(1.0, 0.5, 0.5), vec3(0.40, 0.25, 0.91), saturate(relVec.y))*skyMultiplier;
// add the sun
finalColor += GetSunColorSmall(relVec, sunDir);// + vec3(0.1, 0.1, 0.1);
}
//finalColor = vec3(Hash2d(uv)*0.91, Hash2d(uv+47.0)*0.91, 0.0);
// vignette?
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
finalColor *= 1.3;
// output the final color with sqrt for "gamma correction"
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
2076,
2262,
2316,
2316,
2619
] | [
[
997,
997,
1020,
1020,
1097
],
[
1098,
1098,
1121,
1121,
1213
],
[
1237,
1237,
1260,
1260,
1289
],
[
1290,
1290,
1313,
1313,
1342
],
[
1343,
1343,
1368,
1368,
1397
],
[
1399,
1399,
1432,
1432,
1646
],
[
1647,
1647,
1680,
1680,
1894
],
[
1895,
1895,
1928,
1928,
2073
],
[
2076,
2262,
2316,
2316,
2619
],
[
2620,
2620,
2669,
2669,
2923
],
[
2925,
2970,
3032,
3032,
3240
],
[
3242,
3713,
3741,
3741,
4290
],
[
4291,
4291,
4319,
4319,
4665
],
[
4666,
4666,
4695,
4695,
5016
],
[
6229,
6323,
6345,
6345,
7577
],
[
7579,
7579,
7611,
7611,
8131
],
[
8133,
8133,
8190,
8275,
17740
]
] | // This function basically is a procedural environment map that makes the sun
vec3 sunCol = vec3(258.0, 208.0, 100.0) / 4255.0;//unfortunately, i seem to have 2 different sun colors. :(
| vec3 GetSunColorReflection(vec3 rayDir, vec3 sunDir)
{ |
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.015 / dist;
sunIntensity = pow(sunIntensity, 0.3)*100.0;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.0425;
} | // This function basically is a procedural environment map that makes the sun
vec3 sunCol = vec3(258.0, 208.0, 100.0) / 4255.0;//unfortunately, i seem to have 2 different sun colors. :(
vec3 GetSunColorReflection(vec3 rayDir, vec3 sunDir)
{ | 2 | 8 |
ld2SzK | otaviogood | 2014-10-27T05:24:30 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
-Otavio Good
*/
// The noise function in this was inspired by IQ's "Terrain Tubes" shader. I never really figured out
// his function completely, so I'm not sure of the exact similarities. It's nice though because it
// works the same on all computers (I think). It's not based on a hash that changes from computer to
// computer. That means I can finally rely on the terrain being the same and make a camera path. :)
// It's also a much faster noise function, although it can look a bit repetitive.
#define MOTION_BLUR
#define MOVING_SUN
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 47.0;
return fract(cos(f*3.333)*100003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(cos(f*3.333)*100003.9);
}
float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
//else return new float3(x, cos * y - sin * z, sin * y + cos * z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
//else return new float3(cos * x + sin * z, y, -sin * x + cos * z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
// This function basically is a procedural environment map that makes the sun
vec3 sunCol = vec3(258.0, 208.0, 100.0) / 4255.0;//unfortunately, i seem to have 2 different sun colors. :(
vec3 GetSunColorReflection(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.015 / dist;
sunIntensity = pow(sunIntensity, 0.3)*100.0;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.0425;
}
vec3 GetSunColorSmall(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.05 / dist;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.025;
}
// This is a spline used for the camera path
vec4 CatmullRom(vec4 p0, vec4 p1, vec4 p2, vec4 p3, float t)
{
float t2 = t*t;
float t3 = t*t*t;
return 0.5 *((2.0 * p1) +
(-p0 + p2) * t +
(2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 +
(-p0 + 3.0 * p1- 3.0 * p2 + p3) * t3);
}
// This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.739513; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
float SpiralNoiseC(vec3 p)
{
float n = 0.0; // noise amount
float iter = 1.0;
for (int i = 0; i < 8; i++)
{
// add sin and cos scaled inverse with the frequency
n += -abs(sin(p.y*iter) + cos(p.x*iter)) / iter; // abs for a ridged look
// rotate by adding perpendicular and scaling down
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
// rotate on other axis
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
// increase the frequency
iter *= 1.733733;
}
return n;
}
float SpiralNoiseD(vec3 p)
{
float n = 0.0;
float iter = 1.0;
for (int i = 0; i < 6; i++)
{
n += abs(sin(p.y*iter) + cos(p.x*iter)) / iter; // abs for a ridged look
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.733733;
}
return n;
}
float SpiralNoise3D(vec3 p)
{
float n = 0.0;
float iter = 1.0;
for (int i = 0; i < 5; i++)
{
n += (sin(p.y*iter) + cos(p.x*iter)) / iter;
//p.xy += vec2(p.y, -p.x) * nudge;
//p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.33733;
}
return n;
}
// These are the xyz camera positions and a left/right facing angle relative to the path line
// I think webgl glsl can only access arrays using a constant, so I'm writing all these out.
// Someone please tell me if I'm wrong.
vec4 c00 = vec4(3.5, 2.0, 13.1, 0.0); // start point
vec4 c01 = vec4(12.5, 2.2, 17.0, 0.0); // run up to canyon 2 before hole in large rock face
vec4 c02 = vec4(21.5, 4.0, 8.1, 0.0); // canyon 2 before hole in large rock face
vec4 c03 = vec4(21.0, 5.0, 1.1, -0.5); // before hole in large rock face
vec4 c04 = vec4(17.8, 5.4, -0.2, 0.0); // hole in large rock face
vec4 c05 = vec4(14.7, 2.5, 1.4, 0.0); // after hole in large rock face
vec4 c06 = vec4(7.9, 2.3, -2.1, 0.0);
vec4 c07 = vec4(0.5, -0.7, -3.5, 1.0);
vec4 c08 = vec4(-3.0, -1.0, -3.5, 1.3);
vec4 c09 = vec4(-3.5, -1.0, 4.0, 1.3);
vec4 c10 = vec4(3.0, -0.7, 3.3, 0.8);
vec4 c11 = vec4(3.5, -1.0, -4.75, 0.0);
vec4 c12 = vec4(-6.0, -0.2, 1.0, 3.14);
vec4 c13 = vec4(-6.0, -1.0, 5.5, 0.0);
vec4 cXX = vec4(0.0, 3.0, 0.0, 0.0);
float camPathOffset = 0.0; // where to start on the camera path - parametric t var for catmull-rom spline
vec3 camPos = vec3(0.0), camFacing;
vec3 camLookat=vec3(0,0.0,0);
float waterLevel = 1.5;
// from a time t, this finds where in the camera path you are.
// It uses Catmull-Rom splines
vec4 CamPos(float t)
{
t = mod(t, 14.0); // repeat after 14 time units
float bigTime = floor(t);
float smallTime = fract(t);
// Can't do arrays right, so write this all out.
if (bigTime == 0.0) return CatmullRom(c00, c01, c02, c03, smallTime);
if (bigTime == 1.0) return CatmullRom(c01, c02, c03, c04, smallTime);
if (bigTime == 2.0) return CatmullRom(c02, c03, c04, c05, smallTime);
if (bigTime == 3.0) return CatmullRom(c03, c04, c05, c06, smallTime);
if (bigTime == 4.0) return CatmullRom(c04, c05, c06, c07, smallTime);
if (bigTime == 5.0) return CatmullRom(c05, c06, c07, c08, smallTime);
if (bigTime == 6.0) return CatmullRom(c06, c07, c08, c09, smallTime);
if (bigTime == 7.0) return CatmullRom(c07, c08, c09, c10, smallTime);
if (bigTime == 8.0) return CatmullRom(c08, c09, c10, c11, smallTime);
if (bigTime == 9.0) return CatmullRom(c09, c10, c11, c12, smallTime);
if (bigTime == 10.0) return CatmullRom(c10, c11, c12, c13, smallTime);
if (bigTime == 11.0) return CatmullRom(c11, c12, c13, c00, smallTime);
if (bigTime == 12.0) return CatmullRom(c12, c13, c00, c01, smallTime);
if (bigTime == 13.0) return CatmullRom(c13, c00, c01, c02, smallTime);
return vec4(0.0);
}
float DistanceToObject(vec3 p)
{
float final = p.y + 4.5;
final -= SpiralNoiseC(p.xyz); // mid-range noise
final += SpiralNoiseC(p.zxy*0.123+100.0)*3.0; // large scale terrain features
final -= SpiralNoise3D(p); // more large scale features, but 3d, so not just a height map.
final -= SpiralNoise3D(p*49.0)*0.0625*0.125; // small scale noise for variation
final = min(final, length(p) - 1.99); // sphere in center
final = min(final, p.y + waterLevel); // water
//final = min(final, length(p-camLookat) - 0.3);
return final;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// ---------------- First, set up the camera rays for ray marching ----------------
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
// Camera up vector.
vec3 camUp=vec3(0,1,0); // vuv
// Camera lookat.
camLookat=vec3(0,0.0,0); // vrp
/* if (iTime == 0.0) // for debugging with manual camera
{
camPos = cXX.xyz;
camLookat = vec3(0.0)*cXX.xyz;
}*/
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0;// + iTime * 0.1;
float my=-iMouse.y/iResolution.y*10.0;// + sin(iTime * 0.3)*0.2+0.2;//*PI/2.01;
camPos += vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*(5.2); // prp
// set time for moving camera along path
float timeLine = iTime*0.2 + camPathOffset;
camFacing = camLookat + camPos;
// without this if condition, the mac doesn't work. mysterious. :(
if (iTime != -1.0)
{
vec4 catmullA = CamPos(timeLine);
// get a smoother derivative even though the spline is not C2 continuous.
// Also look ahead a bit so the camera leads the motion
vec4 catmullB = CamPos(timeLine + 0.3);
#ifdef MOTION_BLUR
vec4 catmullC = CamPos(timeLine + 0.004); // adjust for camera motion blur
vec4 catmullBlur = mix(catmullA, catmullC, Hash2d(uv)); // motion blur along camera path
camPos = catmullBlur.xyz;
// face camera along derivate of motion path
camFacing = normalize(catmullB.xyz - catmullA.xyz);
// rotate camera based on w component of camera path vectors
camFacing = RotateY(camFacing, -catmullBlur.w);
#else
camPos = catmullA.xyz;
// face camera along derivate of motion path
camFacing = normalize(catmullB.xyz - catmullA.xyz);
// rotate camera based on w component of camera path vectors
camFacing = RotateY(camFacing, -catmullA.w);
#endif
camFacing = RotateY(camFacing, -mx);
camLookat = camPos + camFacing;
}
// add randomness to camera for depth-of-field look close up.
//camPos += vec3(Hash2d(uv)*0.91, Hash2d(uv+37.0), Hash2d(uv+47.0))*0.01;
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);//vpn
vec3 sideNorm=normalize(cross(camUp, camVec)); // u
vec3 upNorm=cross(camVec, sideNorm);//v
vec3 worldFacing=(camPos + camVec);//vcv
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;//scrCoord
vec3 relVec = normalize(worldPix - camPos);//scp
// --------------------------------------------------------------------------------
float dist = 0.05;
float t = 0.0;
float inc = 0.02;
float maxDepth = 110.0;
vec3 pos = vec3(0,0,0);
// ray marching time
for (int i = 0; i < 200; i++) // This is the count of the max times the ray actually marches.
{
if ((t > maxDepth) || (abs(dist) < 0.0075)) break;
pos = camPos + relVec * t;
// *******************************************************
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry.
// *******************************************************
dist = DistanceToObject(pos);
t += dist * 0.25; // because deformations mess up distance function.
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
#ifdef MOVING_SUN
vec3 sunDir = normalize(vec3(sin(iTime*0.047-1.5), cos(iTime*0.047-1.5), -0.5));
#else
vec3 sunDir = normalize(vec3(0.93, 1.0, -1.5));
#endif
// This makes the sky fade at sunset
float skyMultiplier = saturate(sunDir.y+0.7);
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
if (abs(dist) < 0.75)
//if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(0.005, 0, 0);
vec3 normal = vec3(dist - DistanceToObject(pos - smallVec.xyy),
dist - DistanceToObject(pos - smallVec.yxy),
dist - DistanceToObject(pos - smallVec.yyx));
/*if (pos.y <= waterLevel-2.995) // water waves?
{
normal += SpiralNoise3D(pos*32.0+vec3(iTime*8.0,0.0,0.0))*0.0001;
normal += SpiralNoise3D(pos*27.0+vec3(0.0,0.0, iTime* 10.333))*0.0001;
normal += SpiralNoiseD(pos*37.0+vec3(0.0,iTime* 14.333,0.0))*0.0002;
}*/
normal = normalize(normal);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff - so the green sphere light source can also have ambient.
float ambientS = 1.0;
//ambient *= saturate(DistanceToObject(pos + normal * 0.1)*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2)*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4)*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8)*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6)*1.25*0.5);
ambient *= saturate(DistanceToObject(pos + normal * 3.2)*1.25*0.25);
ambient *= saturate(DistanceToObject(pos + normal * 6.4)*1.25*0.125);
//ambient = max(0.05, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// Trace a ray toward the sun for sun shadows
float sunShadow = 1.0;
float iter = 0.2;
for (int i = 0; i < 10; i++)
{
float tempDist = DistanceToObject(pos + sunDir * iter);
sunShadow *= saturate(tempDist*10.0);
if (tempDist <= 0.0) break;
iter *= 1.5; // constant is more reliable than distance-based
//iter += max(0.2, tempDist)*1.2;
}
float sunSet = saturate(sunDir.y*4.0); // sunset dims the sun
sunShadow = saturate(sunShadow) * sunSet;
// calculate the reflection vector for highlights
vec3 ref = reflect(relVec, normal);
// pulse the ball light source
vec3 ballGlow = vec3(0.1, 0.97, 0.1) * abs(SpiralNoise3D(vec3(iTime*1.3)));
// ------ Calculate texture color of the rock ------
// basic orange and white blended together with noise
vec3 texColor = mix(vec3(0.95, 1.0, 1.0), vec3(0.9, 0.7, 0.5), pow(abs(SpiralNoise3D(pos*1.0)-1.0), 0.6) );
// make the undersides darker greenish
texColor = mix(vec3(0.2, 0.2, 0.1), texColor, saturate(normal.y));
// fade to reddish/orange closer to the water level
texColor = mix(texColor, vec3(0.64, 0.2, 0.1) , saturate(-0.4-pos.y));
// some more variation to the color vertically
texColor = mix(texColor, vec3(0.2, 0.13, 0.02) , pow(saturate(pos.y*0.125+0.5), 2.0));
// give the rock a stratified, layered look
float rockLayers = abs(cos(pos.y*1.5+ SpiralNoiseD(pos*vec3(1.0, 2.0, 1.0)*4.0)*0.2 ));
texColor += vec3(0.7, 0.4, 0.3)*(1.0-pow(rockLayers, 0.3));
// make the water orange. I'm trying for that "nickel tailings" look.
texColor = mix(texColor, vec3(1.4, 0.15, 0.05) + SpiralNoise3D(pos)*0.025, saturate((-pos.y-1.45)*17.0));
// make the sphere white
if (length(pos) <= 2.01) texColor = vec3(1.0);
// don't let it get too saturated or dark
texColor = max(texColor, 0.05);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(1.0, 0.75, 0.75) * saturate(dot(sunDir, normal)) * sunShadow*1.5;
// sky color, hemisphere light equation approximation, anbient occlusion, sunset multiplier
lightColor += vec3(1.0,0.3,0.6) * ( dot(sunDir, normal) * 0.5 + 0.5 ) * ambient * 0.25 * skyMultiplier;
// Make the ball cast light. Distance to the 4th light falloff looked best. Use local ambient occlusion.
float lp = length(pos) - 1.0;
lightColor += ambientS*(ballGlow*1.2 * saturate(dot(normal, -pos)*0.5+0.5) / (lp*lp*lp*lp));
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// Make the water reflect the sun (leaving out sky reflection for no good reason)
vec3 refColor = GetSunColorReflection(ref, sunDir)*0.68;
finalColor += refColor * sunShadow * saturate(normal.y*normal.y) * saturate(-(pos.y+1.35)*16.0);
// make the ball itself glow
finalColor += pow(saturate(1.0 - length(pos)*0.4925), 0.65) * ballGlow*6.1;
// fog that fades to reddish plus the sun color so that fog is brightest towards sun
finalColor = mix(vec3(1.0, 0.41, 0.41)*skyMultiplier + min(vec3(0.25),GetSunColorSmall(relVec, sunDir))*2.0*sunSet, finalColor, exp(-t*0.03));
}
else
{
// Our ray trace hit nothing, so draw sky.
// fade the sky color, multiply sunset dimming
finalColor = mix(vec3(1.0, 0.5, 0.5), vec3(0.40, 0.25, 0.91), saturate(relVec.y))*skyMultiplier;
// add the sun
finalColor += GetSunColorSmall(relVec, sunDir);// + vec3(0.1, 0.1, 0.1);
}
//finalColor = vec3(Hash2d(uv)*0.91, Hash2d(uv+47.0)*0.91, 0.0);
// vignette?
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
finalColor *= 1.3;
// output the final color with sqrt for "gamma correction"
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
2925,
2970,
3032,
3032,
3240
] | [
[
997,
997,
1020,
1020,
1097
],
[
1098,
1098,
1121,
1121,
1213
],
[
1237,
1237,
1260,
1260,
1289
],
[
1290,
1290,
1313,
1313,
1342
],
[
1343,
1343,
1368,
1368,
1397
],
[
1399,
1399,
1432,
1432,
1646
],
[
1647,
1647,
1680,
1680,
1894
],
[
1895,
1895,
1928,
1928,
2073
],
[
2076,
2262,
2316,
2316,
2619
],
[
2620,
2620,
2669,
2669,
2923
],
[
2925,
2970,
3032,
3032,
3240
],
[
3242,
3713,
3741,
3741,
4290
],
[
4291,
4291,
4319,
4319,
4665
],
[
4666,
4666,
4695,
4695,
5016
],
[
6229,
6323,
6345,
6345,
7577
],
[
7579,
7579,
7611,
7611,
8131
],
[
8133,
8133,
8190,
8275,
17740
]
] | // This is a spline used for the camera path
| vec4 CatmullRom(vec4 p0, vec4 p1, vec4 p2, vec4 p3, float t)
{ |
float t2 = t*t;
float t3 = t*t*t;
return 0.5 *((2.0 * p1) +
(-p0 + p2) * t +
(2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 +
(-p0 + 3.0 * p1- 3.0 * p2 + p3) * t3);
} | // This is a spline used for the camera path
vec4 CatmullRom(vec4 p0, vec4 p1, vec4 p2, vec4 p3, float t)
{ | 1 | 1 |
ld2SzK | otaviogood | 2014-10-27T05:24:30 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
-Otavio Good
*/
// The noise function in this was inspired by IQ's "Terrain Tubes" shader. I never really figured out
// his function completely, so I'm not sure of the exact similarities. It's nice though because it
// works the same on all computers (I think). It's not based on a hash that changes from computer to
// computer. That means I can finally rely on the terrain being the same and make a camera path. :)
// It's also a much faster noise function, although it can look a bit repetitive.
#define MOTION_BLUR
#define MOVING_SUN
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 47.0;
return fract(cos(f*3.333)*100003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(cos(f*3.333)*100003.9);
}
float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
//else return new float3(x, cos * y - sin * z, sin * y + cos * z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
//else return new float3(cos * x + sin * z, y, -sin * x + cos * z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
// This function basically is a procedural environment map that makes the sun
vec3 sunCol = vec3(258.0, 208.0, 100.0) / 4255.0;//unfortunately, i seem to have 2 different sun colors. :(
vec3 GetSunColorReflection(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.015 / dist;
sunIntensity = pow(sunIntensity, 0.3)*100.0;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.0425;
}
vec3 GetSunColorSmall(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.05 / dist;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.025;
}
// This is a spline used for the camera path
vec4 CatmullRom(vec4 p0, vec4 p1, vec4 p2, vec4 p3, float t)
{
float t2 = t*t;
float t3 = t*t*t;
return 0.5 *((2.0 * p1) +
(-p0 + p2) * t +
(2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 +
(-p0 + 3.0 * p1- 3.0 * p2 + p3) * t3);
}
// This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.739513; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
float SpiralNoiseC(vec3 p)
{
float n = 0.0; // noise amount
float iter = 1.0;
for (int i = 0; i < 8; i++)
{
// add sin and cos scaled inverse with the frequency
n += -abs(sin(p.y*iter) + cos(p.x*iter)) / iter; // abs for a ridged look
// rotate by adding perpendicular and scaling down
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
// rotate on other axis
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
// increase the frequency
iter *= 1.733733;
}
return n;
}
float SpiralNoiseD(vec3 p)
{
float n = 0.0;
float iter = 1.0;
for (int i = 0; i < 6; i++)
{
n += abs(sin(p.y*iter) + cos(p.x*iter)) / iter; // abs for a ridged look
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.733733;
}
return n;
}
float SpiralNoise3D(vec3 p)
{
float n = 0.0;
float iter = 1.0;
for (int i = 0; i < 5; i++)
{
n += (sin(p.y*iter) + cos(p.x*iter)) / iter;
//p.xy += vec2(p.y, -p.x) * nudge;
//p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.33733;
}
return n;
}
// These are the xyz camera positions and a left/right facing angle relative to the path line
// I think webgl glsl can only access arrays using a constant, so I'm writing all these out.
// Someone please tell me if I'm wrong.
vec4 c00 = vec4(3.5, 2.0, 13.1, 0.0); // start point
vec4 c01 = vec4(12.5, 2.2, 17.0, 0.0); // run up to canyon 2 before hole in large rock face
vec4 c02 = vec4(21.5, 4.0, 8.1, 0.0); // canyon 2 before hole in large rock face
vec4 c03 = vec4(21.0, 5.0, 1.1, -0.5); // before hole in large rock face
vec4 c04 = vec4(17.8, 5.4, -0.2, 0.0); // hole in large rock face
vec4 c05 = vec4(14.7, 2.5, 1.4, 0.0); // after hole in large rock face
vec4 c06 = vec4(7.9, 2.3, -2.1, 0.0);
vec4 c07 = vec4(0.5, -0.7, -3.5, 1.0);
vec4 c08 = vec4(-3.0, -1.0, -3.5, 1.3);
vec4 c09 = vec4(-3.5, -1.0, 4.0, 1.3);
vec4 c10 = vec4(3.0, -0.7, 3.3, 0.8);
vec4 c11 = vec4(3.5, -1.0, -4.75, 0.0);
vec4 c12 = vec4(-6.0, -0.2, 1.0, 3.14);
vec4 c13 = vec4(-6.0, -1.0, 5.5, 0.0);
vec4 cXX = vec4(0.0, 3.0, 0.0, 0.0);
float camPathOffset = 0.0; // where to start on the camera path - parametric t var for catmull-rom spline
vec3 camPos = vec3(0.0), camFacing;
vec3 camLookat=vec3(0,0.0,0);
float waterLevel = 1.5;
// from a time t, this finds where in the camera path you are.
// It uses Catmull-Rom splines
vec4 CamPos(float t)
{
t = mod(t, 14.0); // repeat after 14 time units
float bigTime = floor(t);
float smallTime = fract(t);
// Can't do arrays right, so write this all out.
if (bigTime == 0.0) return CatmullRom(c00, c01, c02, c03, smallTime);
if (bigTime == 1.0) return CatmullRom(c01, c02, c03, c04, smallTime);
if (bigTime == 2.0) return CatmullRom(c02, c03, c04, c05, smallTime);
if (bigTime == 3.0) return CatmullRom(c03, c04, c05, c06, smallTime);
if (bigTime == 4.0) return CatmullRom(c04, c05, c06, c07, smallTime);
if (bigTime == 5.0) return CatmullRom(c05, c06, c07, c08, smallTime);
if (bigTime == 6.0) return CatmullRom(c06, c07, c08, c09, smallTime);
if (bigTime == 7.0) return CatmullRom(c07, c08, c09, c10, smallTime);
if (bigTime == 8.0) return CatmullRom(c08, c09, c10, c11, smallTime);
if (bigTime == 9.0) return CatmullRom(c09, c10, c11, c12, smallTime);
if (bigTime == 10.0) return CatmullRom(c10, c11, c12, c13, smallTime);
if (bigTime == 11.0) return CatmullRom(c11, c12, c13, c00, smallTime);
if (bigTime == 12.0) return CatmullRom(c12, c13, c00, c01, smallTime);
if (bigTime == 13.0) return CatmullRom(c13, c00, c01, c02, smallTime);
return vec4(0.0);
}
float DistanceToObject(vec3 p)
{
float final = p.y + 4.5;
final -= SpiralNoiseC(p.xyz); // mid-range noise
final += SpiralNoiseC(p.zxy*0.123+100.0)*3.0; // large scale terrain features
final -= SpiralNoise3D(p); // more large scale features, but 3d, so not just a height map.
final -= SpiralNoise3D(p*49.0)*0.0625*0.125; // small scale noise for variation
final = min(final, length(p) - 1.99); // sphere in center
final = min(final, p.y + waterLevel); // water
//final = min(final, length(p-camLookat) - 0.3);
return final;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// ---------------- First, set up the camera rays for ray marching ----------------
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
// Camera up vector.
vec3 camUp=vec3(0,1,0); // vuv
// Camera lookat.
camLookat=vec3(0,0.0,0); // vrp
/* if (iTime == 0.0) // for debugging with manual camera
{
camPos = cXX.xyz;
camLookat = vec3(0.0)*cXX.xyz;
}*/
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0;// + iTime * 0.1;
float my=-iMouse.y/iResolution.y*10.0;// + sin(iTime * 0.3)*0.2+0.2;//*PI/2.01;
camPos += vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*(5.2); // prp
// set time for moving camera along path
float timeLine = iTime*0.2 + camPathOffset;
camFacing = camLookat + camPos;
// without this if condition, the mac doesn't work. mysterious. :(
if (iTime != -1.0)
{
vec4 catmullA = CamPos(timeLine);
// get a smoother derivative even though the spline is not C2 continuous.
// Also look ahead a bit so the camera leads the motion
vec4 catmullB = CamPos(timeLine + 0.3);
#ifdef MOTION_BLUR
vec4 catmullC = CamPos(timeLine + 0.004); // adjust for camera motion blur
vec4 catmullBlur = mix(catmullA, catmullC, Hash2d(uv)); // motion blur along camera path
camPos = catmullBlur.xyz;
// face camera along derivate of motion path
camFacing = normalize(catmullB.xyz - catmullA.xyz);
// rotate camera based on w component of camera path vectors
camFacing = RotateY(camFacing, -catmullBlur.w);
#else
camPos = catmullA.xyz;
// face camera along derivate of motion path
camFacing = normalize(catmullB.xyz - catmullA.xyz);
// rotate camera based on w component of camera path vectors
camFacing = RotateY(camFacing, -catmullA.w);
#endif
camFacing = RotateY(camFacing, -mx);
camLookat = camPos + camFacing;
}
// add randomness to camera for depth-of-field look close up.
//camPos += vec3(Hash2d(uv)*0.91, Hash2d(uv+37.0), Hash2d(uv+47.0))*0.01;
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);//vpn
vec3 sideNorm=normalize(cross(camUp, camVec)); // u
vec3 upNorm=cross(camVec, sideNorm);//v
vec3 worldFacing=(camPos + camVec);//vcv
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;//scrCoord
vec3 relVec = normalize(worldPix - camPos);//scp
// --------------------------------------------------------------------------------
float dist = 0.05;
float t = 0.0;
float inc = 0.02;
float maxDepth = 110.0;
vec3 pos = vec3(0,0,0);
// ray marching time
for (int i = 0; i < 200; i++) // This is the count of the max times the ray actually marches.
{
if ((t > maxDepth) || (abs(dist) < 0.0075)) break;
pos = camPos + relVec * t;
// *******************************************************
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry.
// *******************************************************
dist = DistanceToObject(pos);
t += dist * 0.25; // because deformations mess up distance function.
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
#ifdef MOVING_SUN
vec3 sunDir = normalize(vec3(sin(iTime*0.047-1.5), cos(iTime*0.047-1.5), -0.5));
#else
vec3 sunDir = normalize(vec3(0.93, 1.0, -1.5));
#endif
// This makes the sky fade at sunset
float skyMultiplier = saturate(sunDir.y+0.7);
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
if (abs(dist) < 0.75)
//if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(0.005, 0, 0);
vec3 normal = vec3(dist - DistanceToObject(pos - smallVec.xyy),
dist - DistanceToObject(pos - smallVec.yxy),
dist - DistanceToObject(pos - smallVec.yyx));
/*if (pos.y <= waterLevel-2.995) // water waves?
{
normal += SpiralNoise3D(pos*32.0+vec3(iTime*8.0,0.0,0.0))*0.0001;
normal += SpiralNoise3D(pos*27.0+vec3(0.0,0.0, iTime* 10.333))*0.0001;
normal += SpiralNoiseD(pos*37.0+vec3(0.0,iTime* 14.333,0.0))*0.0002;
}*/
normal = normalize(normal);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff - so the green sphere light source can also have ambient.
float ambientS = 1.0;
//ambient *= saturate(DistanceToObject(pos + normal * 0.1)*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2)*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4)*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8)*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6)*1.25*0.5);
ambient *= saturate(DistanceToObject(pos + normal * 3.2)*1.25*0.25);
ambient *= saturate(DistanceToObject(pos + normal * 6.4)*1.25*0.125);
//ambient = max(0.05, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// Trace a ray toward the sun for sun shadows
float sunShadow = 1.0;
float iter = 0.2;
for (int i = 0; i < 10; i++)
{
float tempDist = DistanceToObject(pos + sunDir * iter);
sunShadow *= saturate(tempDist*10.0);
if (tempDist <= 0.0) break;
iter *= 1.5; // constant is more reliable than distance-based
//iter += max(0.2, tempDist)*1.2;
}
float sunSet = saturate(sunDir.y*4.0); // sunset dims the sun
sunShadow = saturate(sunShadow) * sunSet;
// calculate the reflection vector for highlights
vec3 ref = reflect(relVec, normal);
// pulse the ball light source
vec3 ballGlow = vec3(0.1, 0.97, 0.1) * abs(SpiralNoise3D(vec3(iTime*1.3)));
// ------ Calculate texture color of the rock ------
// basic orange and white blended together with noise
vec3 texColor = mix(vec3(0.95, 1.0, 1.0), vec3(0.9, 0.7, 0.5), pow(abs(SpiralNoise3D(pos*1.0)-1.0), 0.6) );
// make the undersides darker greenish
texColor = mix(vec3(0.2, 0.2, 0.1), texColor, saturate(normal.y));
// fade to reddish/orange closer to the water level
texColor = mix(texColor, vec3(0.64, 0.2, 0.1) , saturate(-0.4-pos.y));
// some more variation to the color vertically
texColor = mix(texColor, vec3(0.2, 0.13, 0.02) , pow(saturate(pos.y*0.125+0.5), 2.0));
// give the rock a stratified, layered look
float rockLayers = abs(cos(pos.y*1.5+ SpiralNoiseD(pos*vec3(1.0, 2.0, 1.0)*4.0)*0.2 ));
texColor += vec3(0.7, 0.4, 0.3)*(1.0-pow(rockLayers, 0.3));
// make the water orange. I'm trying for that "nickel tailings" look.
texColor = mix(texColor, vec3(1.4, 0.15, 0.05) + SpiralNoise3D(pos)*0.025, saturate((-pos.y-1.45)*17.0));
// make the sphere white
if (length(pos) <= 2.01) texColor = vec3(1.0);
// don't let it get too saturated or dark
texColor = max(texColor, 0.05);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(1.0, 0.75, 0.75) * saturate(dot(sunDir, normal)) * sunShadow*1.5;
// sky color, hemisphere light equation approximation, anbient occlusion, sunset multiplier
lightColor += vec3(1.0,0.3,0.6) * ( dot(sunDir, normal) * 0.5 + 0.5 ) * ambient * 0.25 * skyMultiplier;
// Make the ball cast light. Distance to the 4th light falloff looked best. Use local ambient occlusion.
float lp = length(pos) - 1.0;
lightColor += ambientS*(ballGlow*1.2 * saturate(dot(normal, -pos)*0.5+0.5) / (lp*lp*lp*lp));
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// Make the water reflect the sun (leaving out sky reflection for no good reason)
vec3 refColor = GetSunColorReflection(ref, sunDir)*0.68;
finalColor += refColor * sunShadow * saturate(normal.y*normal.y) * saturate(-(pos.y+1.35)*16.0);
// make the ball itself glow
finalColor += pow(saturate(1.0 - length(pos)*0.4925), 0.65) * ballGlow*6.1;
// fog that fades to reddish plus the sun color so that fog is brightest towards sun
finalColor = mix(vec3(1.0, 0.41, 0.41)*skyMultiplier + min(vec3(0.25),GetSunColorSmall(relVec, sunDir))*2.0*sunSet, finalColor, exp(-t*0.03));
}
else
{
// Our ray trace hit nothing, so draw sky.
// fade the sky color, multiply sunset dimming
finalColor = mix(vec3(1.0, 0.5, 0.5), vec3(0.40, 0.25, 0.91), saturate(relVec.y))*skyMultiplier;
// add the sun
finalColor += GetSunColorSmall(relVec, sunDir);// + vec3(0.1, 0.1, 0.1);
}
//finalColor = vec3(Hash2d(uv)*0.91, Hash2d(uv+47.0)*0.91, 0.0);
// vignette?
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
finalColor *= 1.3;
// output the final color with sqrt for "gamma correction"
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
3242,
3713,
3741,
3741,
4290
] | [
[
997,
997,
1020,
1020,
1097
],
[
1098,
1098,
1121,
1121,
1213
],
[
1237,
1237,
1260,
1260,
1289
],
[
1290,
1290,
1313,
1313,
1342
],
[
1343,
1343,
1368,
1368,
1397
],
[
1399,
1399,
1432,
1432,
1646
],
[
1647,
1647,
1680,
1680,
1894
],
[
1895,
1895,
1928,
1928,
2073
],
[
2076,
2262,
2316,
2316,
2619
],
[
2620,
2620,
2669,
2669,
2923
],
[
2925,
2970,
3032,
3032,
3240
],
[
3242,
3713,
3741,
3741,
4290
],
[
4291,
4291,
4319,
4319,
4665
],
[
4666,
4666,
4695,
4695,
5016
],
[
6229,
6323,
6345,
6345,
7577
],
[
7579,
7579,
7611,
7611,
8131
],
[
8133,
8133,
8190,
8275,
17740
]
] | // This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.739513; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
| float SpiralNoiseC(vec3 p)
{ |
float n = 0.0; // noise amount
float iter = 1.0;
for (int i = 0; i < 8; i++)
{
// add sin and cos scaled inverse with the frequency
n += -abs(sin(p.y*iter) + cos(p.x*iter)) / iter; // abs for a ridged look
// rotate by adding perpendicular and scaling down
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
// rotate on other axis
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
// increase the frequency
iter *= 1.733733;
}
return n;
} | // This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.739513; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
float SpiralNoiseC(vec3 p)
{ | 7 | 17 |
ld2SzK | otaviogood | 2014-10-27T05:24:30 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
-Otavio Good
*/
// The noise function in this was inspired by IQ's "Terrain Tubes" shader. I never really figured out
// his function completely, so I'm not sure of the exact similarities. It's nice though because it
// works the same on all computers (I think). It's not based on a hash that changes from computer to
// computer. That means I can finally rely on the terrain being the same and make a camera path. :)
// It's also a much faster noise function, although it can look a bit repetitive.
#define MOTION_BLUR
#define MOVING_SUN
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 47.0;
return fract(cos(f*3.333)*100003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(cos(f*3.333)*100003.9);
}
float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
//else return new float3(x, cos * y - sin * z, sin * y + cos * z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
//else return new float3(cos * x + sin * z, y, -sin * x + cos * z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
// This function basically is a procedural environment map that makes the sun
vec3 sunCol = vec3(258.0, 208.0, 100.0) / 4255.0;//unfortunately, i seem to have 2 different sun colors. :(
vec3 GetSunColorReflection(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.015 / dist;
sunIntensity = pow(sunIntensity, 0.3)*100.0;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.0425;
}
vec3 GetSunColorSmall(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.05 / dist;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.025;
}
// This is a spline used for the camera path
vec4 CatmullRom(vec4 p0, vec4 p1, vec4 p2, vec4 p3, float t)
{
float t2 = t*t;
float t3 = t*t*t;
return 0.5 *((2.0 * p1) +
(-p0 + p2) * t +
(2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 +
(-p0 + 3.0 * p1- 3.0 * p2 + p3) * t3);
}
// This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.739513; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
float SpiralNoiseC(vec3 p)
{
float n = 0.0; // noise amount
float iter = 1.0;
for (int i = 0; i < 8; i++)
{
// add sin and cos scaled inverse with the frequency
n += -abs(sin(p.y*iter) + cos(p.x*iter)) / iter; // abs for a ridged look
// rotate by adding perpendicular and scaling down
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
// rotate on other axis
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
// increase the frequency
iter *= 1.733733;
}
return n;
}
float SpiralNoiseD(vec3 p)
{
float n = 0.0;
float iter = 1.0;
for (int i = 0; i < 6; i++)
{
n += abs(sin(p.y*iter) + cos(p.x*iter)) / iter; // abs for a ridged look
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.733733;
}
return n;
}
float SpiralNoise3D(vec3 p)
{
float n = 0.0;
float iter = 1.0;
for (int i = 0; i < 5; i++)
{
n += (sin(p.y*iter) + cos(p.x*iter)) / iter;
//p.xy += vec2(p.y, -p.x) * nudge;
//p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.33733;
}
return n;
}
// These are the xyz camera positions and a left/right facing angle relative to the path line
// I think webgl glsl can only access arrays using a constant, so I'm writing all these out.
// Someone please tell me if I'm wrong.
vec4 c00 = vec4(3.5, 2.0, 13.1, 0.0); // start point
vec4 c01 = vec4(12.5, 2.2, 17.0, 0.0); // run up to canyon 2 before hole in large rock face
vec4 c02 = vec4(21.5, 4.0, 8.1, 0.0); // canyon 2 before hole in large rock face
vec4 c03 = vec4(21.0, 5.0, 1.1, -0.5); // before hole in large rock face
vec4 c04 = vec4(17.8, 5.4, -0.2, 0.0); // hole in large rock face
vec4 c05 = vec4(14.7, 2.5, 1.4, 0.0); // after hole in large rock face
vec4 c06 = vec4(7.9, 2.3, -2.1, 0.0);
vec4 c07 = vec4(0.5, -0.7, -3.5, 1.0);
vec4 c08 = vec4(-3.0, -1.0, -3.5, 1.3);
vec4 c09 = vec4(-3.5, -1.0, 4.0, 1.3);
vec4 c10 = vec4(3.0, -0.7, 3.3, 0.8);
vec4 c11 = vec4(3.5, -1.0, -4.75, 0.0);
vec4 c12 = vec4(-6.0, -0.2, 1.0, 3.14);
vec4 c13 = vec4(-6.0, -1.0, 5.5, 0.0);
vec4 cXX = vec4(0.0, 3.0, 0.0, 0.0);
float camPathOffset = 0.0; // where to start on the camera path - parametric t var for catmull-rom spline
vec3 camPos = vec3(0.0), camFacing;
vec3 camLookat=vec3(0,0.0,0);
float waterLevel = 1.5;
// from a time t, this finds where in the camera path you are.
// It uses Catmull-Rom splines
vec4 CamPos(float t)
{
t = mod(t, 14.0); // repeat after 14 time units
float bigTime = floor(t);
float smallTime = fract(t);
// Can't do arrays right, so write this all out.
if (bigTime == 0.0) return CatmullRom(c00, c01, c02, c03, smallTime);
if (bigTime == 1.0) return CatmullRom(c01, c02, c03, c04, smallTime);
if (bigTime == 2.0) return CatmullRom(c02, c03, c04, c05, smallTime);
if (bigTime == 3.0) return CatmullRom(c03, c04, c05, c06, smallTime);
if (bigTime == 4.0) return CatmullRom(c04, c05, c06, c07, smallTime);
if (bigTime == 5.0) return CatmullRom(c05, c06, c07, c08, smallTime);
if (bigTime == 6.0) return CatmullRom(c06, c07, c08, c09, smallTime);
if (bigTime == 7.0) return CatmullRom(c07, c08, c09, c10, smallTime);
if (bigTime == 8.0) return CatmullRom(c08, c09, c10, c11, smallTime);
if (bigTime == 9.0) return CatmullRom(c09, c10, c11, c12, smallTime);
if (bigTime == 10.0) return CatmullRom(c10, c11, c12, c13, smallTime);
if (bigTime == 11.0) return CatmullRom(c11, c12, c13, c00, smallTime);
if (bigTime == 12.0) return CatmullRom(c12, c13, c00, c01, smallTime);
if (bigTime == 13.0) return CatmullRom(c13, c00, c01, c02, smallTime);
return vec4(0.0);
}
float DistanceToObject(vec3 p)
{
float final = p.y + 4.5;
final -= SpiralNoiseC(p.xyz); // mid-range noise
final += SpiralNoiseC(p.zxy*0.123+100.0)*3.0; // large scale terrain features
final -= SpiralNoise3D(p); // more large scale features, but 3d, so not just a height map.
final -= SpiralNoise3D(p*49.0)*0.0625*0.125; // small scale noise for variation
final = min(final, length(p) - 1.99); // sphere in center
final = min(final, p.y + waterLevel); // water
//final = min(final, length(p-camLookat) - 0.3);
return final;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// ---------------- First, set up the camera rays for ray marching ----------------
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
// Camera up vector.
vec3 camUp=vec3(0,1,0); // vuv
// Camera lookat.
camLookat=vec3(0,0.0,0); // vrp
/* if (iTime == 0.0) // for debugging with manual camera
{
camPos = cXX.xyz;
camLookat = vec3(0.0)*cXX.xyz;
}*/
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0;// + iTime * 0.1;
float my=-iMouse.y/iResolution.y*10.0;// + sin(iTime * 0.3)*0.2+0.2;//*PI/2.01;
camPos += vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*(5.2); // prp
// set time for moving camera along path
float timeLine = iTime*0.2 + camPathOffset;
camFacing = camLookat + camPos;
// without this if condition, the mac doesn't work. mysterious. :(
if (iTime != -1.0)
{
vec4 catmullA = CamPos(timeLine);
// get a smoother derivative even though the spline is not C2 continuous.
// Also look ahead a bit so the camera leads the motion
vec4 catmullB = CamPos(timeLine + 0.3);
#ifdef MOTION_BLUR
vec4 catmullC = CamPos(timeLine + 0.004); // adjust for camera motion blur
vec4 catmullBlur = mix(catmullA, catmullC, Hash2d(uv)); // motion blur along camera path
camPos = catmullBlur.xyz;
// face camera along derivate of motion path
camFacing = normalize(catmullB.xyz - catmullA.xyz);
// rotate camera based on w component of camera path vectors
camFacing = RotateY(camFacing, -catmullBlur.w);
#else
camPos = catmullA.xyz;
// face camera along derivate of motion path
camFacing = normalize(catmullB.xyz - catmullA.xyz);
// rotate camera based on w component of camera path vectors
camFacing = RotateY(camFacing, -catmullA.w);
#endif
camFacing = RotateY(camFacing, -mx);
camLookat = camPos + camFacing;
}
// add randomness to camera for depth-of-field look close up.
//camPos += vec3(Hash2d(uv)*0.91, Hash2d(uv+37.0), Hash2d(uv+47.0))*0.01;
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);//vpn
vec3 sideNorm=normalize(cross(camUp, camVec)); // u
vec3 upNorm=cross(camVec, sideNorm);//v
vec3 worldFacing=(camPos + camVec);//vcv
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;//scrCoord
vec3 relVec = normalize(worldPix - camPos);//scp
// --------------------------------------------------------------------------------
float dist = 0.05;
float t = 0.0;
float inc = 0.02;
float maxDepth = 110.0;
vec3 pos = vec3(0,0,0);
// ray marching time
for (int i = 0; i < 200; i++) // This is the count of the max times the ray actually marches.
{
if ((t > maxDepth) || (abs(dist) < 0.0075)) break;
pos = camPos + relVec * t;
// *******************************************************
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry.
// *******************************************************
dist = DistanceToObject(pos);
t += dist * 0.25; // because deformations mess up distance function.
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
#ifdef MOVING_SUN
vec3 sunDir = normalize(vec3(sin(iTime*0.047-1.5), cos(iTime*0.047-1.5), -0.5));
#else
vec3 sunDir = normalize(vec3(0.93, 1.0, -1.5));
#endif
// This makes the sky fade at sunset
float skyMultiplier = saturate(sunDir.y+0.7);
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
if (abs(dist) < 0.75)
//if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(0.005, 0, 0);
vec3 normal = vec3(dist - DistanceToObject(pos - smallVec.xyy),
dist - DistanceToObject(pos - smallVec.yxy),
dist - DistanceToObject(pos - smallVec.yyx));
/*if (pos.y <= waterLevel-2.995) // water waves?
{
normal += SpiralNoise3D(pos*32.0+vec3(iTime*8.0,0.0,0.0))*0.0001;
normal += SpiralNoise3D(pos*27.0+vec3(0.0,0.0, iTime* 10.333))*0.0001;
normal += SpiralNoiseD(pos*37.0+vec3(0.0,iTime* 14.333,0.0))*0.0002;
}*/
normal = normalize(normal);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff - so the green sphere light source can also have ambient.
float ambientS = 1.0;
//ambient *= saturate(DistanceToObject(pos + normal * 0.1)*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2)*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4)*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8)*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6)*1.25*0.5);
ambient *= saturate(DistanceToObject(pos + normal * 3.2)*1.25*0.25);
ambient *= saturate(DistanceToObject(pos + normal * 6.4)*1.25*0.125);
//ambient = max(0.05, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// Trace a ray toward the sun for sun shadows
float sunShadow = 1.0;
float iter = 0.2;
for (int i = 0; i < 10; i++)
{
float tempDist = DistanceToObject(pos + sunDir * iter);
sunShadow *= saturate(tempDist*10.0);
if (tempDist <= 0.0) break;
iter *= 1.5; // constant is more reliable than distance-based
//iter += max(0.2, tempDist)*1.2;
}
float sunSet = saturate(sunDir.y*4.0); // sunset dims the sun
sunShadow = saturate(sunShadow) * sunSet;
// calculate the reflection vector for highlights
vec3 ref = reflect(relVec, normal);
// pulse the ball light source
vec3 ballGlow = vec3(0.1, 0.97, 0.1) * abs(SpiralNoise3D(vec3(iTime*1.3)));
// ------ Calculate texture color of the rock ------
// basic orange and white blended together with noise
vec3 texColor = mix(vec3(0.95, 1.0, 1.0), vec3(0.9, 0.7, 0.5), pow(abs(SpiralNoise3D(pos*1.0)-1.0), 0.6) );
// make the undersides darker greenish
texColor = mix(vec3(0.2, 0.2, 0.1), texColor, saturate(normal.y));
// fade to reddish/orange closer to the water level
texColor = mix(texColor, vec3(0.64, 0.2, 0.1) , saturate(-0.4-pos.y));
// some more variation to the color vertically
texColor = mix(texColor, vec3(0.2, 0.13, 0.02) , pow(saturate(pos.y*0.125+0.5), 2.0));
// give the rock a stratified, layered look
float rockLayers = abs(cos(pos.y*1.5+ SpiralNoiseD(pos*vec3(1.0, 2.0, 1.0)*4.0)*0.2 ));
texColor += vec3(0.7, 0.4, 0.3)*(1.0-pow(rockLayers, 0.3));
// make the water orange. I'm trying for that "nickel tailings" look.
texColor = mix(texColor, vec3(1.4, 0.15, 0.05) + SpiralNoise3D(pos)*0.025, saturate((-pos.y-1.45)*17.0));
// make the sphere white
if (length(pos) <= 2.01) texColor = vec3(1.0);
// don't let it get too saturated or dark
texColor = max(texColor, 0.05);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(1.0, 0.75, 0.75) * saturate(dot(sunDir, normal)) * sunShadow*1.5;
// sky color, hemisphere light equation approximation, anbient occlusion, sunset multiplier
lightColor += vec3(1.0,0.3,0.6) * ( dot(sunDir, normal) * 0.5 + 0.5 ) * ambient * 0.25 * skyMultiplier;
// Make the ball cast light. Distance to the 4th light falloff looked best. Use local ambient occlusion.
float lp = length(pos) - 1.0;
lightColor += ambientS*(ballGlow*1.2 * saturate(dot(normal, -pos)*0.5+0.5) / (lp*lp*lp*lp));
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// Make the water reflect the sun (leaving out sky reflection for no good reason)
vec3 refColor = GetSunColorReflection(ref, sunDir)*0.68;
finalColor += refColor * sunShadow * saturate(normal.y*normal.y) * saturate(-(pos.y+1.35)*16.0);
// make the ball itself glow
finalColor += pow(saturate(1.0 - length(pos)*0.4925), 0.65) * ballGlow*6.1;
// fog that fades to reddish plus the sun color so that fog is brightest towards sun
finalColor = mix(vec3(1.0, 0.41, 0.41)*skyMultiplier + min(vec3(0.25),GetSunColorSmall(relVec, sunDir))*2.0*sunSet, finalColor, exp(-t*0.03));
}
else
{
// Our ray trace hit nothing, so draw sky.
// fade the sky color, multiply sunset dimming
finalColor = mix(vec3(1.0, 0.5, 0.5), vec3(0.40, 0.25, 0.91), saturate(relVec.y))*skyMultiplier;
// add the sun
finalColor += GetSunColorSmall(relVec, sunDir);// + vec3(0.1, 0.1, 0.1);
}
//finalColor = vec3(Hash2d(uv)*0.91, Hash2d(uv+47.0)*0.91, 0.0);
// vignette?
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
finalColor *= 1.3;
// output the final color with sqrt for "gamma correction"
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
6229,
6323,
6345,
6345,
7577
] | [
[
997,
997,
1020,
1020,
1097
],
[
1098,
1098,
1121,
1121,
1213
],
[
1237,
1237,
1260,
1260,
1289
],
[
1290,
1290,
1313,
1313,
1342
],
[
1343,
1343,
1368,
1368,
1397
],
[
1399,
1399,
1432,
1432,
1646
],
[
1647,
1647,
1680,
1680,
1894
],
[
1895,
1895,
1928,
1928,
2073
],
[
2076,
2262,
2316,
2316,
2619
],
[
2620,
2620,
2669,
2669,
2923
],
[
2925,
2970,
3032,
3032,
3240
],
[
3242,
3713,
3741,
3741,
4290
],
[
4291,
4291,
4319,
4319,
4665
],
[
4666,
4666,
4695,
4695,
5016
],
[
6229,
6323,
6345,
6345,
7577
],
[
7579,
7579,
7611,
7611,
8131
],
[
8133,
8133,
8190,
8275,
17740
]
] | // from a time t, this finds where in the camera path you are.
// It uses Catmull-Rom splines
| vec4 CamPos(float t)
{ |
t = mod(t, 14.0); // repeat after 14 time units
float bigTime = floor(t);
float smallTime = fract(t);
// Can't do arrays right, so write this all out.
if (bigTime == 0.0) return CatmullRom(c00, c01, c02, c03, smallTime);
if (bigTime == 1.0) return CatmullRom(c01, c02, c03, c04, smallTime);
if (bigTime == 2.0) return CatmullRom(c02, c03, c04, c05, smallTime);
if (bigTime == 3.0) return CatmullRom(c03, c04, c05, c06, smallTime);
if (bigTime == 4.0) return CatmullRom(c04, c05, c06, c07, smallTime);
if (bigTime == 5.0) return CatmullRom(c05, c06, c07, c08, smallTime);
if (bigTime == 6.0) return CatmullRom(c06, c07, c08, c09, smallTime);
if (bigTime == 7.0) return CatmullRom(c07, c08, c09, c10, smallTime);
if (bigTime == 8.0) return CatmullRom(c08, c09, c10, c11, smallTime);
if (bigTime == 9.0) return CatmullRom(c09, c10, c11, c12, smallTime);
if (bigTime == 10.0) return CatmullRom(c10, c11, c12, c13, smallTime);
if (bigTime == 11.0) return CatmullRom(c11, c12, c13, c00, smallTime);
if (bigTime == 12.0) return CatmullRom(c12, c13, c00, c01, smallTime);
if (bigTime == 13.0) return CatmullRom(c13, c00, c01, c02, smallTime);
return vec4(0.0);
} | // from a time t, this finds where in the camera path you are.
// It uses Catmull-Rom splines
vec4 CamPos(float t)
{ | 1 | 1 |
4dSXDd | otaviogood | 2014-11-27T22:26:38 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// This will lower the framerate, but looks kinda cool
//#define TOO_MUCH_FRACTAL
//#define MOVING_SUN
float outerSphereRad = 3.5;
// noise functions
float Hash1d(float u)
{
return fract(sin(u)*143.9); // scale this down to kill the jitters
}
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(sin(f)*110003.9);
}
float mixP(float f0, float f1, float a)
{
return mix(f0, f1, a*a*(3.0-2.0*a));
}
const vec2 zeroOne = vec2(0.0, 1.0);
float noise2d(vec2 uv)
{
vec2 fr = fract(uv.xy);
vec2 fl = floor(uv.xy);
float h00 = Hash2d(fl);
float h10 = Hash2d(fl + zeroOne.yx);
float h01 = Hash2d(fl + zeroOne);
float h11 = Hash2d(fl + zeroOne.yy);
return mixP(mixP(h00, h10, fr.x), mixP(h01, h11, fr.x), fr.y);
}
float noise(vec3 uv)
{
vec3 fr = fract(uv.xyz);
vec3 fl = floor(uv.xyz);
float h000 = Hash3d(fl);
float h100 = Hash3d(fl + zeroOne.yxx);
float h010 = Hash3d(fl + zeroOne.xyx);
float h110 = Hash3d(fl + zeroOne.yyx);
float h001 = Hash3d(fl + zeroOne.xxy);
float h101 = Hash3d(fl + zeroOne.yxy);
float h011 = Hash3d(fl + zeroOne.xyy);
float h111 = Hash3d(fl + zeroOne.yyy);
return mixP(
mixP(mixP(h000, h100, fr.x),
mixP(h010, h110, fr.x), fr.y),
mixP(mixP(h001, h101, fr.x),
mixP(h011, h111, fr.x), fr.y)
, fr.z);
}
float PI=3.14159265;
// Variables for animating and rotating the sides of the object
float chunkAnim = 0.0;
mat3 rotMat;
vec3 rotDir;
float rotAmount;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
// This function basically is a procedural environment map that makes the sun
vec3 sunCol = vec3(258.0, 208.0, 100.0) / 4255.0;
vec3 GetSunColorReflection(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.015 / dist;
sunIntensity = pow(sunIntensity, 0.3)*100.0;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.0425;
}
vec3 GetSunColorSmall(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.05 / dist;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.025;
}
// This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.71; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
// Total hack of the spiral noise function to get a rust look
float RustNoise3D(vec3 p)
{
float n = 0.0;
float iter = 1.0;
float pn = noise(p*0.125);
pn += noise(p*0.25)*0.5;
pn += noise(p*0.5)*0.25;
pn += noise(p*1.0)*0.125;
for (int i = 0; i < 7; i++)
{
//n += (sin(p.y*iter) + cos(p.x*iter)) / iter;
float wave = saturate(cos(p.y*0.25 + pn) - 0.998);
// wave *= noise(p * 0.125)*1016.0;
n += wave;
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.4733;
}
return n*500.0;
}
vec3 camPos = vec3(0.0), camFacing;
vec3 camLookat=vec3(0,0.0,0);
// This is the big money function that makes the crazy fractally shape
float DistanceToObject(vec3 p)
{
//p += (1.0/p.y)*0.6;
// Rotate, but only the part that is on the side of rotDir
if (dot(p, rotDir) > 1.0) p *= rotMat;
// Repeat our position so we can carve out many cylindrical-like things from our solid
vec3 rep = fract(p)-0.5;
//final = max(final, -(length(rep.xz*rep.xz)*1.0 - 0.0326));
float final = -(length(rep.xy*rep.xz) - 0.109);
final = max(final, -(length(rep.zy) - 0.33));
//final = max(final, -(length(rep.xz*rep.xz) - 0.03));
//final = max(final, -(length(rep.yz*rep.yz) - 0.03));
//final = max(final, -(length(rep.xy*rep.xy) - 0.030266));
// Repeat the process of carving things out for smaller scales
vec3 rep2 = fract(rep*2.0)-0.5;
final = max(final, -(length(rep2.xz)*0.5 - 0.125));
final = max(final, -(length(rep2.xy)*0.5 - 0.125));
final = max(final, -(length(rep2.zy)*0.5 - 0.125));
vec3 rep3 = fract(rep2*3.0)-0.5;
final = max(final, -(length(rep3.xz)*0.1667 - 0.25*0.1667));
final = max(final, -(length(rep3.xy)*0.1667 - 0.25*0.1667));
final = max(final, -(length(rep3.zy)*0.1667 - 0.25*0.1667));
#ifdef TOO_MUCH_FRACTAL
vec3 rep4 = fract(rep3*3.0)-0.5;
final = max(final, -(length(rep4.xz)*0.0555 - 0.25*0.0555));
final = max(final, -(length(rep4.xy)*0.0555 - 0.25*0.0555));
final = max(final, -(length(rep4.yz)*0.0555 - 0.25*0.0555));
vec3 rep5 = fract(rep4*3.0)-0.5;
final = max(final, -(length(rep5.xz)*0.0185 - 0.25*0.0185));
final = max(final, -(length(rep5.xy)*0.0185 - 0.25*0.0185));
final = max(final, -(length(rep5.yz)*0.0185 - 0.25*0.0185));
#endif
// Cut out stuff outside of outer sphere
final = max(final, (length(p) - outerSphereRad));
// Carve out inner sphere
final = max(final, -(length(p) - 2.8));
//final = max(final, abs(p.x) - 2.0); // for that space station look
//final = (length(p) - outerSphereRad); // for debugging texture and lighting
// Slice the object in a 3d grid so it can rotate like a rubik's cube
float slice = 0.02;
vec3 grid = -abs(fract(p.xyz)) + slice;
final = max(final, grid.x);
final = max(final, grid.y);
final = max(final, grid.z);
//final = min(final, abs(p.y));
return final;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// ---------------- First, set up the camera rays for ray marching ----------------
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
// Camera up vector.
vec3 camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0,0.0,0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0 + iTime * 0.166;
float my=-iMouse.y/iResolution.y*10.0 + sin(iTime * 0.3)*0.8+0.1;//*PI/2.01;
// move camera in and out of the sphere
float smallTime = iTime*0.2;
float inOut = pow(abs(-cos(smallTime)), 0.6)* sign(-cos(smallTime));
camPos += vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*(3.35+inOut*2.0);
// add randomness to camera for depth-of-field look close up.
//camPos += vec3(Hash2d(uv)*0.91, Hash2d(uv+37.0), Hash2d(uv+47.0))*0.01;
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 relVec = normalize(worldPix - camPos);
// -------------------------------- animate ---------------------------------------
float localTime = iTime*0.5;
float floorTime = floor(localTime);
float zeroToOne = max(0.0,fract(localTime)*1.0-0.0);// *4.0-3.0);
// This is the 0..1 for the rotation
chunkAnim = smoothstep(0.0, 1.0, zeroToOne);
// This is for brightening the outer sphere when a rotation happens
float pulse = saturate(-log(zeroToOne*30.0)+2.0);
//float mft = mod(floorTime, 6.0);
// Let's make it rotate a random part every time
float mft = Hash1d(floorTime * 2.34567);
mft = floor(mft * 5.9999); // get a random [0..6) integer
// randomize where the rotation slice is
float uglyRand = Hash1d(floorTime*1.234567);
uglyRand = floor(uglyRand*2.999); // get a random [0..3) integer
uglyRand = 1.0 / (uglyRand + 1.0);
// Check which axis we should rotate on and make a matrix for it.
if (mft <= 1.0)
{
rotAmount = PI;
float cos = cos(chunkAnim * rotAmount);
float sin = sin(chunkAnim * rotAmount);
rotMat = mat3(1.0, 0.0, 0.0,
0.0, cos, sin,
0.0, -sin, cos);
rotDir = vec3(uglyRand, 0.0, 0.0);
}
else if (mft <= 3.0)
{
rotAmount = PI;
float cos = cos(chunkAnim * rotAmount);
float sin = sin(chunkAnim * rotAmount);
rotMat = mat3(cos, 0.0, -sin,
0.0, 1.0, 0.0,
sin, 0.0, cos);
rotDir = vec3(0.0, uglyRand, 0.0);
}
else
{
rotAmount = PI;
float cos = cos(chunkAnim * rotAmount);
float sin = sin(chunkAnim * rotAmount);
rotMat = mat3(cos, sin, 0.0,
-sin, cos, 0.0,
0.0, 0.0, 1.0);
rotDir = vec3(0.0, 0.0, uglyRand);
}
if (mod(floorTime, 2.0) == 0.0) rotDir = -rotDir;
// --------------------------------------------------------------------------------
float dist = 0.15;
float t = 0.2 + Hash2d(uv)*0.1; // fade things close to the camera
float inc = 0.02;
float maxDepth = 11.0;
vec3 pos = vec3(0,0,0);
float glow = 0.0;
// ray marching time
for (int i = 0; i < 110; i++) // This is the count of the max times the ray actually marches.
{
if ((t > maxDepth) || (abs(dist) < 0.001)) break;
pos = camPos + relVec * t;
// *******************************************************
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry.
// *******************************************************
dist = DistanceToObject(pos);
// Do some tricks for marching so that we can march the inner glow sphere
float lp = length(pos);
//if (lp > outerSphereRad + 0.9) break;
float inv = max(0.0, 0.1*dist / lp - 0.1);
dist = min(max(0.15,lp*0.6 - 0.1), dist);
glow += inv;//0.001
glow += 0.0025;
// no deformations messing up the distance function this time. Hurray for getting the math right!
t += dist;//*0.9995; // because deformations mess up distance function.
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
#ifdef MOVING_SUN
vec3 sunDir = normalize(vec3(sin(iTime*0.047-1.5), cos(iTime*0.047-1.5), -0.5));
#else
vec3 sunDir = normalize(vec3(0.93, 1.0, -1.5));
#endif
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
if (abs(dist) < 0.75)
//if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(0.0025, 0, 0);
vec3 normalU = vec3(dist - DistanceToObject(pos - smallVec.xyy),
dist - DistanceToObject(pos - smallVec.yxy),
dist - DistanceToObject(pos - smallVec.yyx));
vec3 normal = normalize(normalU);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff
float ambientS = 1.0;
//ambientS *= saturate(DistanceToObject(pos + normal * 0.1)*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2)*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4)*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8)*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6)*1.25*0.5);
ambient *= saturate(DistanceToObject(pos + normal * 3.2)*1.25*0.25);
ambient *= saturate(DistanceToObject(pos + normal * 6.4)*1.25*0.125);
//ambient = max(0.05, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// Trace a ray toward the sun for sun shadows
float sunShadow = 1.0;
float iter = 0.05;
for (int i = 0; i < 30; i++)
{
vec3 tempPos = pos + sunDir * iter;
//if (dot(tempPos, tempPos) > outerSphereRad*outerSphereRad+0.8) break;
if (iter > outerSphereRad + outerSphereRad) break;
float tempDist = DistanceToObject(tempPos);
sunShadow *= saturate(tempDist*50.0);
if (tempDist <= 0.0) break;
//iter *= 1.5; // constant is more reliable than distance-based???
iter += max(0.01, tempDist)*1.0;
}
sunShadow = saturate(sunShadow);
// calculate the reflection vector for highlights
vec3 ref = reflect(relVec, normal);
// make sure the texture gets rotated along with the geometry.
vec3 posTex = pos;
if (dot(pos, rotDir) > 1.0) posTex = pos * rotMat;
posTex = abs(posTex); // make texture symetric so it doesn't pop after rotation
// make a few frequencies of noise to give it some texture
float n =0.0;
n += noise(posTex*32.0);
n += noise(posTex*64.0);
n += noise(posTex*128.0);
n += noise(posTex*256.0);
n += noise(posTex*512.0);
n *= 0.8;
normal = normalize(normal + n*0.1);
// ------ Calculate texture color ------
vec3 texColor = vec3(0.95, 1.0, 1.0);
vec3 rust = vec3(0.65, 0.25, 0.1) - noise(posTex*128.0);
texColor *= smoothstep(texColor, rust, vec3(saturate(RustNoise3D(posTex*8.0))-0.2));
// make outer edge a little brighter
texColor += (1.0 - vec3(19.0, 5.0, 2.0) * length(normalU))*ambientS;
// apply noise
texColor *= vec3(1.0)*n*0.05;
texColor *= 0.7;
texColor = saturate(texColor);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(0.6) * saturate(dot(sunDir, normal)) * sunShadow;
// weighted average the near ambient occlusion with the far for just the right look
float ambientAvg = (ambient*3.0 + ambientS) * 0.25;
// a red and blue light coming from different directions
lightColor += (vec3(1.0, 0.2, 0.4) * saturate(-normal.z *0.5+0.5))*pow(ambientAvg, 0.5);
lightColor += (vec3(0.1, 0.5, 0.99) * saturate(normal.y *0.5+0.5))*pow(ambientAvg, 0.5);
// blue glow light coming from the glow in the middle of the sphere
lightColor += vec3(0.3, 0.5, 0.9) * saturate(dot(-pos, normal))*pow(ambientS, 0.3);
// lightColor *= ambient;
lightColor *= 4.0;
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// sun reflection to make it look metal
finalColor += vec3(1.0)*pow(n,4.0)* GetSunColorSmall(ref, sunDir) * sunShadow;// * ambientS;
// fog that fades to reddish plus the sun color so that fog is brightest towards sun
//finalColor = mix(vec3(1.0, 0.41, 0.41)*skyMultiplier + min(vec3(0.25),GetSunColorSmall(relVec, sunDir))*2.0*sunSet, finalColor, exp(-t*0.003));
// pulse the outer edge color when something is about to rotate
if (dot(pos, rotDir) > 1.0) finalColor += vec3(0.2, 1.4, 0.8)*pulse*saturate(0.000001 / pow(abs(length(pos)-outerSphereRad), 2.0))*2.0;
}
else
{
// Our ray trace hit nothing, so draw sky.
//finalColor = saturate(GetSunColorSmall(relVec, sunDir)*0.95-0.01);
}
// add the ray marching glow
finalColor += vec3(0.3, 0.5, 0.9) * glow;
// vignette?
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
finalColor *= 1.3;
// output the final color with sqrt for "gamma correction"
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
695,
714,
737,
737,
810
] | [
[
695,
714,
737,
737,
810
],
[
811,
811,
834,
834,
905
],
[
906,
906,
929,
929,
1015
],
[
1016,
1016,
1057,
1057,
1100
],
[
1138,
1138,
1162,
1162,
1435
],
[
1436,
1436,
1458,
1458,
2043
],
[
2198,
2198,
2221,
2221,
2250
],
[
2251,
2251,
2274,
2274,
2303
],
[
2304,
2304,
2329,
2329,
2358
],
[
2489,
2489,
2543,
2543,
2846
],
[
2847,
2847,
2896,
2896,
3150
],
[
3152,
3681,
3708,
3708,
4272
],
[
4341,
4412,
4444,
4534,
6672
],
[
6674,
6674,
6731,
6816,
16639
]
] | // noise functions
| float Hash1d(float u)
{ |
return fract(sin(u)*143.9); // scale this down to kill the jitters
} | // noise functions
float Hash1d(float u)
{ | 6 | 6 |
4dSXDd | otaviogood | 2014-11-27T22:26:38 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// This will lower the framerate, but looks kinda cool
//#define TOO_MUCH_FRACTAL
//#define MOVING_SUN
float outerSphereRad = 3.5;
// noise functions
float Hash1d(float u)
{
return fract(sin(u)*143.9); // scale this down to kill the jitters
}
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(sin(f)*110003.9);
}
float mixP(float f0, float f1, float a)
{
return mix(f0, f1, a*a*(3.0-2.0*a));
}
const vec2 zeroOne = vec2(0.0, 1.0);
float noise2d(vec2 uv)
{
vec2 fr = fract(uv.xy);
vec2 fl = floor(uv.xy);
float h00 = Hash2d(fl);
float h10 = Hash2d(fl + zeroOne.yx);
float h01 = Hash2d(fl + zeroOne);
float h11 = Hash2d(fl + zeroOne.yy);
return mixP(mixP(h00, h10, fr.x), mixP(h01, h11, fr.x), fr.y);
}
float noise(vec3 uv)
{
vec3 fr = fract(uv.xyz);
vec3 fl = floor(uv.xyz);
float h000 = Hash3d(fl);
float h100 = Hash3d(fl + zeroOne.yxx);
float h010 = Hash3d(fl + zeroOne.xyx);
float h110 = Hash3d(fl + zeroOne.yyx);
float h001 = Hash3d(fl + zeroOne.xxy);
float h101 = Hash3d(fl + zeroOne.yxy);
float h011 = Hash3d(fl + zeroOne.xyy);
float h111 = Hash3d(fl + zeroOne.yyy);
return mixP(
mixP(mixP(h000, h100, fr.x),
mixP(h010, h110, fr.x), fr.y),
mixP(mixP(h001, h101, fr.x),
mixP(h011, h111, fr.x), fr.y)
, fr.z);
}
float PI=3.14159265;
// Variables for animating and rotating the sides of the object
float chunkAnim = 0.0;
mat3 rotMat;
vec3 rotDir;
float rotAmount;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
// This function basically is a procedural environment map that makes the sun
vec3 sunCol = vec3(258.0, 208.0, 100.0) / 4255.0;
vec3 GetSunColorReflection(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.015 / dist;
sunIntensity = pow(sunIntensity, 0.3)*100.0;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.0425;
}
vec3 GetSunColorSmall(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.05 / dist;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.025;
}
// This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.71; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
// Total hack of the spiral noise function to get a rust look
float RustNoise3D(vec3 p)
{
float n = 0.0;
float iter = 1.0;
float pn = noise(p*0.125);
pn += noise(p*0.25)*0.5;
pn += noise(p*0.5)*0.25;
pn += noise(p*1.0)*0.125;
for (int i = 0; i < 7; i++)
{
//n += (sin(p.y*iter) + cos(p.x*iter)) / iter;
float wave = saturate(cos(p.y*0.25 + pn) - 0.998);
// wave *= noise(p * 0.125)*1016.0;
n += wave;
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.4733;
}
return n*500.0;
}
vec3 camPos = vec3(0.0), camFacing;
vec3 camLookat=vec3(0,0.0,0);
// This is the big money function that makes the crazy fractally shape
float DistanceToObject(vec3 p)
{
//p += (1.0/p.y)*0.6;
// Rotate, but only the part that is on the side of rotDir
if (dot(p, rotDir) > 1.0) p *= rotMat;
// Repeat our position so we can carve out many cylindrical-like things from our solid
vec3 rep = fract(p)-0.5;
//final = max(final, -(length(rep.xz*rep.xz)*1.0 - 0.0326));
float final = -(length(rep.xy*rep.xz) - 0.109);
final = max(final, -(length(rep.zy) - 0.33));
//final = max(final, -(length(rep.xz*rep.xz) - 0.03));
//final = max(final, -(length(rep.yz*rep.yz) - 0.03));
//final = max(final, -(length(rep.xy*rep.xy) - 0.030266));
// Repeat the process of carving things out for smaller scales
vec3 rep2 = fract(rep*2.0)-0.5;
final = max(final, -(length(rep2.xz)*0.5 - 0.125));
final = max(final, -(length(rep2.xy)*0.5 - 0.125));
final = max(final, -(length(rep2.zy)*0.5 - 0.125));
vec3 rep3 = fract(rep2*3.0)-0.5;
final = max(final, -(length(rep3.xz)*0.1667 - 0.25*0.1667));
final = max(final, -(length(rep3.xy)*0.1667 - 0.25*0.1667));
final = max(final, -(length(rep3.zy)*0.1667 - 0.25*0.1667));
#ifdef TOO_MUCH_FRACTAL
vec3 rep4 = fract(rep3*3.0)-0.5;
final = max(final, -(length(rep4.xz)*0.0555 - 0.25*0.0555));
final = max(final, -(length(rep4.xy)*0.0555 - 0.25*0.0555));
final = max(final, -(length(rep4.yz)*0.0555 - 0.25*0.0555));
vec3 rep5 = fract(rep4*3.0)-0.5;
final = max(final, -(length(rep5.xz)*0.0185 - 0.25*0.0185));
final = max(final, -(length(rep5.xy)*0.0185 - 0.25*0.0185));
final = max(final, -(length(rep5.yz)*0.0185 - 0.25*0.0185));
#endif
// Cut out stuff outside of outer sphere
final = max(final, (length(p) - outerSphereRad));
// Carve out inner sphere
final = max(final, -(length(p) - 2.8));
//final = max(final, abs(p.x) - 2.0); // for that space station look
//final = (length(p) - outerSphereRad); // for debugging texture and lighting
// Slice the object in a 3d grid so it can rotate like a rubik's cube
float slice = 0.02;
vec3 grid = -abs(fract(p.xyz)) + slice;
final = max(final, grid.x);
final = max(final, grid.y);
final = max(final, grid.z);
//final = min(final, abs(p.y));
return final;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// ---------------- First, set up the camera rays for ray marching ----------------
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
// Camera up vector.
vec3 camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0,0.0,0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0 + iTime * 0.166;
float my=-iMouse.y/iResolution.y*10.0 + sin(iTime * 0.3)*0.8+0.1;//*PI/2.01;
// move camera in and out of the sphere
float smallTime = iTime*0.2;
float inOut = pow(abs(-cos(smallTime)), 0.6)* sign(-cos(smallTime));
camPos += vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*(3.35+inOut*2.0);
// add randomness to camera for depth-of-field look close up.
//camPos += vec3(Hash2d(uv)*0.91, Hash2d(uv+37.0), Hash2d(uv+47.0))*0.01;
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 relVec = normalize(worldPix - camPos);
// -------------------------------- animate ---------------------------------------
float localTime = iTime*0.5;
float floorTime = floor(localTime);
float zeroToOne = max(0.0,fract(localTime)*1.0-0.0);// *4.0-3.0);
// This is the 0..1 for the rotation
chunkAnim = smoothstep(0.0, 1.0, zeroToOne);
// This is for brightening the outer sphere when a rotation happens
float pulse = saturate(-log(zeroToOne*30.0)+2.0);
//float mft = mod(floorTime, 6.0);
// Let's make it rotate a random part every time
float mft = Hash1d(floorTime * 2.34567);
mft = floor(mft * 5.9999); // get a random [0..6) integer
// randomize where the rotation slice is
float uglyRand = Hash1d(floorTime*1.234567);
uglyRand = floor(uglyRand*2.999); // get a random [0..3) integer
uglyRand = 1.0 / (uglyRand + 1.0);
// Check which axis we should rotate on and make a matrix for it.
if (mft <= 1.0)
{
rotAmount = PI;
float cos = cos(chunkAnim * rotAmount);
float sin = sin(chunkAnim * rotAmount);
rotMat = mat3(1.0, 0.0, 0.0,
0.0, cos, sin,
0.0, -sin, cos);
rotDir = vec3(uglyRand, 0.0, 0.0);
}
else if (mft <= 3.0)
{
rotAmount = PI;
float cos = cos(chunkAnim * rotAmount);
float sin = sin(chunkAnim * rotAmount);
rotMat = mat3(cos, 0.0, -sin,
0.0, 1.0, 0.0,
sin, 0.0, cos);
rotDir = vec3(0.0, uglyRand, 0.0);
}
else
{
rotAmount = PI;
float cos = cos(chunkAnim * rotAmount);
float sin = sin(chunkAnim * rotAmount);
rotMat = mat3(cos, sin, 0.0,
-sin, cos, 0.0,
0.0, 0.0, 1.0);
rotDir = vec3(0.0, 0.0, uglyRand);
}
if (mod(floorTime, 2.0) == 0.0) rotDir = -rotDir;
// --------------------------------------------------------------------------------
float dist = 0.15;
float t = 0.2 + Hash2d(uv)*0.1; // fade things close to the camera
float inc = 0.02;
float maxDepth = 11.0;
vec3 pos = vec3(0,0,0);
float glow = 0.0;
// ray marching time
for (int i = 0; i < 110; i++) // This is the count of the max times the ray actually marches.
{
if ((t > maxDepth) || (abs(dist) < 0.001)) break;
pos = camPos + relVec * t;
// *******************************************************
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry.
// *******************************************************
dist = DistanceToObject(pos);
// Do some tricks for marching so that we can march the inner glow sphere
float lp = length(pos);
//if (lp > outerSphereRad + 0.9) break;
float inv = max(0.0, 0.1*dist / lp - 0.1);
dist = min(max(0.15,lp*0.6 - 0.1), dist);
glow += inv;//0.001
glow += 0.0025;
// no deformations messing up the distance function this time. Hurray for getting the math right!
t += dist;//*0.9995; // because deformations mess up distance function.
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
#ifdef MOVING_SUN
vec3 sunDir = normalize(vec3(sin(iTime*0.047-1.5), cos(iTime*0.047-1.5), -0.5));
#else
vec3 sunDir = normalize(vec3(0.93, 1.0, -1.5));
#endif
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
if (abs(dist) < 0.75)
//if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(0.0025, 0, 0);
vec3 normalU = vec3(dist - DistanceToObject(pos - smallVec.xyy),
dist - DistanceToObject(pos - smallVec.yxy),
dist - DistanceToObject(pos - smallVec.yyx));
vec3 normal = normalize(normalU);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff
float ambientS = 1.0;
//ambientS *= saturate(DistanceToObject(pos + normal * 0.1)*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2)*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4)*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8)*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6)*1.25*0.5);
ambient *= saturate(DistanceToObject(pos + normal * 3.2)*1.25*0.25);
ambient *= saturate(DistanceToObject(pos + normal * 6.4)*1.25*0.125);
//ambient = max(0.05, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// Trace a ray toward the sun for sun shadows
float sunShadow = 1.0;
float iter = 0.05;
for (int i = 0; i < 30; i++)
{
vec3 tempPos = pos + sunDir * iter;
//if (dot(tempPos, tempPos) > outerSphereRad*outerSphereRad+0.8) break;
if (iter > outerSphereRad + outerSphereRad) break;
float tempDist = DistanceToObject(tempPos);
sunShadow *= saturate(tempDist*50.0);
if (tempDist <= 0.0) break;
//iter *= 1.5; // constant is more reliable than distance-based???
iter += max(0.01, tempDist)*1.0;
}
sunShadow = saturate(sunShadow);
// calculate the reflection vector for highlights
vec3 ref = reflect(relVec, normal);
// make sure the texture gets rotated along with the geometry.
vec3 posTex = pos;
if (dot(pos, rotDir) > 1.0) posTex = pos * rotMat;
posTex = abs(posTex); // make texture symetric so it doesn't pop after rotation
// make a few frequencies of noise to give it some texture
float n =0.0;
n += noise(posTex*32.0);
n += noise(posTex*64.0);
n += noise(posTex*128.0);
n += noise(posTex*256.0);
n += noise(posTex*512.0);
n *= 0.8;
normal = normalize(normal + n*0.1);
// ------ Calculate texture color ------
vec3 texColor = vec3(0.95, 1.0, 1.0);
vec3 rust = vec3(0.65, 0.25, 0.1) - noise(posTex*128.0);
texColor *= smoothstep(texColor, rust, vec3(saturate(RustNoise3D(posTex*8.0))-0.2));
// make outer edge a little brighter
texColor += (1.0 - vec3(19.0, 5.0, 2.0) * length(normalU))*ambientS;
// apply noise
texColor *= vec3(1.0)*n*0.05;
texColor *= 0.7;
texColor = saturate(texColor);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(0.6) * saturate(dot(sunDir, normal)) * sunShadow;
// weighted average the near ambient occlusion with the far for just the right look
float ambientAvg = (ambient*3.0 + ambientS) * 0.25;
// a red and blue light coming from different directions
lightColor += (vec3(1.0, 0.2, 0.4) * saturate(-normal.z *0.5+0.5))*pow(ambientAvg, 0.5);
lightColor += (vec3(0.1, 0.5, 0.99) * saturate(normal.y *0.5+0.5))*pow(ambientAvg, 0.5);
// blue glow light coming from the glow in the middle of the sphere
lightColor += vec3(0.3, 0.5, 0.9) * saturate(dot(-pos, normal))*pow(ambientS, 0.3);
// lightColor *= ambient;
lightColor *= 4.0;
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// sun reflection to make it look metal
finalColor += vec3(1.0)*pow(n,4.0)* GetSunColorSmall(ref, sunDir) * sunShadow;// * ambientS;
// fog that fades to reddish plus the sun color so that fog is brightest towards sun
//finalColor = mix(vec3(1.0, 0.41, 0.41)*skyMultiplier + min(vec3(0.25),GetSunColorSmall(relVec, sunDir))*2.0*sunSet, finalColor, exp(-t*0.003));
// pulse the outer edge color when something is about to rotate
if (dot(pos, rotDir) > 1.0) finalColor += vec3(0.2, 1.4, 0.8)*pulse*saturate(0.000001 / pow(abs(length(pos)-outerSphereRad), 2.0))*2.0;
}
else
{
// Our ray trace hit nothing, so draw sky.
//finalColor = saturate(GetSunColorSmall(relVec, sunDir)*0.95-0.01);
}
// add the ray marching glow
finalColor += vec3(0.3, 0.5, 0.9) * glow;
// vignette?
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
finalColor *= 1.3;
// output the final color with sqrt for "gamma correction"
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
3152,
3681,
3708,
3708,
4272
] | [
[
695,
714,
737,
737,
810
],
[
811,
811,
834,
834,
905
],
[
906,
906,
929,
929,
1015
],
[
1016,
1016,
1057,
1057,
1100
],
[
1138,
1138,
1162,
1162,
1435
],
[
1436,
1436,
1458,
1458,
2043
],
[
2198,
2198,
2221,
2221,
2250
],
[
2251,
2251,
2274,
2274,
2303
],
[
2304,
2304,
2329,
2329,
2358
],
[
2489,
2489,
2543,
2543,
2846
],
[
2847,
2847,
2896,
2896,
3150
],
[
3152,
3681,
3708,
3708,
4272
],
[
4341,
4412,
4444,
4534,
6672
],
[
6674,
6674,
6731,
6816,
16639
]
] | // This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.71; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
// Total hack of the spiral noise function to get a rust look
| float RustNoise3D(vec3 p)
{ |
float n = 0.0;
float iter = 1.0;
float pn = noise(p*0.125);
pn += noise(p*0.25)*0.5;
pn += noise(p*0.5)*0.25;
pn += noise(p*1.0)*0.125;
for (int i = 0; i < 7; i++)
{
//n += (sin(p.y*iter) + cos(p.x*iter)) / iter;
float wave = saturate(cos(p.y*0.25 + pn) - 0.998);
// wave *= noise(p * 0.125)*1016.0;
n += wave;
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.4733;
}
return n*500.0;
} | // This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.71; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
// Total hack of the spiral noise function to get a rust look
float RustNoise3D(vec3 p)
{ | 1 | 2 |
4dSXDd | otaviogood | 2014-11-27T22:26:38 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// This will lower the framerate, but looks kinda cool
//#define TOO_MUCH_FRACTAL
//#define MOVING_SUN
float outerSphereRad = 3.5;
// noise functions
float Hash1d(float u)
{
return fract(sin(u)*143.9); // scale this down to kill the jitters
}
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(sin(f)*110003.9);
}
float mixP(float f0, float f1, float a)
{
return mix(f0, f1, a*a*(3.0-2.0*a));
}
const vec2 zeroOne = vec2(0.0, 1.0);
float noise2d(vec2 uv)
{
vec2 fr = fract(uv.xy);
vec2 fl = floor(uv.xy);
float h00 = Hash2d(fl);
float h10 = Hash2d(fl + zeroOne.yx);
float h01 = Hash2d(fl + zeroOne);
float h11 = Hash2d(fl + zeroOne.yy);
return mixP(mixP(h00, h10, fr.x), mixP(h01, h11, fr.x), fr.y);
}
float noise(vec3 uv)
{
vec3 fr = fract(uv.xyz);
vec3 fl = floor(uv.xyz);
float h000 = Hash3d(fl);
float h100 = Hash3d(fl + zeroOne.yxx);
float h010 = Hash3d(fl + zeroOne.xyx);
float h110 = Hash3d(fl + zeroOne.yyx);
float h001 = Hash3d(fl + zeroOne.xxy);
float h101 = Hash3d(fl + zeroOne.yxy);
float h011 = Hash3d(fl + zeroOne.xyy);
float h111 = Hash3d(fl + zeroOne.yyy);
return mixP(
mixP(mixP(h000, h100, fr.x),
mixP(h010, h110, fr.x), fr.y),
mixP(mixP(h001, h101, fr.x),
mixP(h011, h111, fr.x), fr.y)
, fr.z);
}
float PI=3.14159265;
// Variables for animating and rotating the sides of the object
float chunkAnim = 0.0;
mat3 rotMat;
vec3 rotDir;
float rotAmount;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
// This function basically is a procedural environment map that makes the sun
vec3 sunCol = vec3(258.0, 208.0, 100.0) / 4255.0;
vec3 GetSunColorReflection(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.015 / dist;
sunIntensity = pow(sunIntensity, 0.3)*100.0;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.0425;
}
vec3 GetSunColorSmall(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.05 / dist;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.025;
}
// This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.71; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
// Total hack of the spiral noise function to get a rust look
float RustNoise3D(vec3 p)
{
float n = 0.0;
float iter = 1.0;
float pn = noise(p*0.125);
pn += noise(p*0.25)*0.5;
pn += noise(p*0.5)*0.25;
pn += noise(p*1.0)*0.125;
for (int i = 0; i < 7; i++)
{
//n += (sin(p.y*iter) + cos(p.x*iter)) / iter;
float wave = saturate(cos(p.y*0.25 + pn) - 0.998);
// wave *= noise(p * 0.125)*1016.0;
n += wave;
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.4733;
}
return n*500.0;
}
vec3 camPos = vec3(0.0), camFacing;
vec3 camLookat=vec3(0,0.0,0);
// This is the big money function that makes the crazy fractally shape
float DistanceToObject(vec3 p)
{
//p += (1.0/p.y)*0.6;
// Rotate, but only the part that is on the side of rotDir
if (dot(p, rotDir) > 1.0) p *= rotMat;
// Repeat our position so we can carve out many cylindrical-like things from our solid
vec3 rep = fract(p)-0.5;
//final = max(final, -(length(rep.xz*rep.xz)*1.0 - 0.0326));
float final = -(length(rep.xy*rep.xz) - 0.109);
final = max(final, -(length(rep.zy) - 0.33));
//final = max(final, -(length(rep.xz*rep.xz) - 0.03));
//final = max(final, -(length(rep.yz*rep.yz) - 0.03));
//final = max(final, -(length(rep.xy*rep.xy) - 0.030266));
// Repeat the process of carving things out for smaller scales
vec3 rep2 = fract(rep*2.0)-0.5;
final = max(final, -(length(rep2.xz)*0.5 - 0.125));
final = max(final, -(length(rep2.xy)*0.5 - 0.125));
final = max(final, -(length(rep2.zy)*0.5 - 0.125));
vec3 rep3 = fract(rep2*3.0)-0.5;
final = max(final, -(length(rep3.xz)*0.1667 - 0.25*0.1667));
final = max(final, -(length(rep3.xy)*0.1667 - 0.25*0.1667));
final = max(final, -(length(rep3.zy)*0.1667 - 0.25*0.1667));
#ifdef TOO_MUCH_FRACTAL
vec3 rep4 = fract(rep3*3.0)-0.5;
final = max(final, -(length(rep4.xz)*0.0555 - 0.25*0.0555));
final = max(final, -(length(rep4.xy)*0.0555 - 0.25*0.0555));
final = max(final, -(length(rep4.yz)*0.0555 - 0.25*0.0555));
vec3 rep5 = fract(rep4*3.0)-0.5;
final = max(final, -(length(rep5.xz)*0.0185 - 0.25*0.0185));
final = max(final, -(length(rep5.xy)*0.0185 - 0.25*0.0185));
final = max(final, -(length(rep5.yz)*0.0185 - 0.25*0.0185));
#endif
// Cut out stuff outside of outer sphere
final = max(final, (length(p) - outerSphereRad));
// Carve out inner sphere
final = max(final, -(length(p) - 2.8));
//final = max(final, abs(p.x) - 2.0); // for that space station look
//final = (length(p) - outerSphereRad); // for debugging texture and lighting
// Slice the object in a 3d grid so it can rotate like a rubik's cube
float slice = 0.02;
vec3 grid = -abs(fract(p.xyz)) + slice;
final = max(final, grid.x);
final = max(final, grid.y);
final = max(final, grid.z);
//final = min(final, abs(p.y));
return final;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// ---------------- First, set up the camera rays for ray marching ----------------
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
// Camera up vector.
vec3 camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0,0.0,0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0 + iTime * 0.166;
float my=-iMouse.y/iResolution.y*10.0 + sin(iTime * 0.3)*0.8+0.1;//*PI/2.01;
// move camera in and out of the sphere
float smallTime = iTime*0.2;
float inOut = pow(abs(-cos(smallTime)), 0.6)* sign(-cos(smallTime));
camPos += vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*(3.35+inOut*2.0);
// add randomness to camera for depth-of-field look close up.
//camPos += vec3(Hash2d(uv)*0.91, Hash2d(uv+37.0), Hash2d(uv+47.0))*0.01;
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 relVec = normalize(worldPix - camPos);
// -------------------------------- animate ---------------------------------------
float localTime = iTime*0.5;
float floorTime = floor(localTime);
float zeroToOne = max(0.0,fract(localTime)*1.0-0.0);// *4.0-3.0);
// This is the 0..1 for the rotation
chunkAnim = smoothstep(0.0, 1.0, zeroToOne);
// This is for brightening the outer sphere when a rotation happens
float pulse = saturate(-log(zeroToOne*30.0)+2.0);
//float mft = mod(floorTime, 6.0);
// Let's make it rotate a random part every time
float mft = Hash1d(floorTime * 2.34567);
mft = floor(mft * 5.9999); // get a random [0..6) integer
// randomize where the rotation slice is
float uglyRand = Hash1d(floorTime*1.234567);
uglyRand = floor(uglyRand*2.999); // get a random [0..3) integer
uglyRand = 1.0 / (uglyRand + 1.0);
// Check which axis we should rotate on and make a matrix for it.
if (mft <= 1.0)
{
rotAmount = PI;
float cos = cos(chunkAnim * rotAmount);
float sin = sin(chunkAnim * rotAmount);
rotMat = mat3(1.0, 0.0, 0.0,
0.0, cos, sin,
0.0, -sin, cos);
rotDir = vec3(uglyRand, 0.0, 0.0);
}
else if (mft <= 3.0)
{
rotAmount = PI;
float cos = cos(chunkAnim * rotAmount);
float sin = sin(chunkAnim * rotAmount);
rotMat = mat3(cos, 0.0, -sin,
0.0, 1.0, 0.0,
sin, 0.0, cos);
rotDir = vec3(0.0, uglyRand, 0.0);
}
else
{
rotAmount = PI;
float cos = cos(chunkAnim * rotAmount);
float sin = sin(chunkAnim * rotAmount);
rotMat = mat3(cos, sin, 0.0,
-sin, cos, 0.0,
0.0, 0.0, 1.0);
rotDir = vec3(0.0, 0.0, uglyRand);
}
if (mod(floorTime, 2.0) == 0.0) rotDir = -rotDir;
// --------------------------------------------------------------------------------
float dist = 0.15;
float t = 0.2 + Hash2d(uv)*0.1; // fade things close to the camera
float inc = 0.02;
float maxDepth = 11.0;
vec3 pos = vec3(0,0,0);
float glow = 0.0;
// ray marching time
for (int i = 0; i < 110; i++) // This is the count of the max times the ray actually marches.
{
if ((t > maxDepth) || (abs(dist) < 0.001)) break;
pos = camPos + relVec * t;
// *******************************************************
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry.
// *******************************************************
dist = DistanceToObject(pos);
// Do some tricks for marching so that we can march the inner glow sphere
float lp = length(pos);
//if (lp > outerSphereRad + 0.9) break;
float inv = max(0.0, 0.1*dist / lp - 0.1);
dist = min(max(0.15,lp*0.6 - 0.1), dist);
glow += inv;//0.001
glow += 0.0025;
// no deformations messing up the distance function this time. Hurray for getting the math right!
t += dist;//*0.9995; // because deformations mess up distance function.
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
#ifdef MOVING_SUN
vec3 sunDir = normalize(vec3(sin(iTime*0.047-1.5), cos(iTime*0.047-1.5), -0.5));
#else
vec3 sunDir = normalize(vec3(0.93, 1.0, -1.5));
#endif
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
if (abs(dist) < 0.75)
//if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(0.0025, 0, 0);
vec3 normalU = vec3(dist - DistanceToObject(pos - smallVec.xyy),
dist - DistanceToObject(pos - smallVec.yxy),
dist - DistanceToObject(pos - smallVec.yyx));
vec3 normal = normalize(normalU);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff
float ambientS = 1.0;
//ambientS *= saturate(DistanceToObject(pos + normal * 0.1)*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2)*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4)*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8)*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6)*1.25*0.5);
ambient *= saturate(DistanceToObject(pos + normal * 3.2)*1.25*0.25);
ambient *= saturate(DistanceToObject(pos + normal * 6.4)*1.25*0.125);
//ambient = max(0.05, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// Trace a ray toward the sun for sun shadows
float sunShadow = 1.0;
float iter = 0.05;
for (int i = 0; i < 30; i++)
{
vec3 tempPos = pos + sunDir * iter;
//if (dot(tempPos, tempPos) > outerSphereRad*outerSphereRad+0.8) break;
if (iter > outerSphereRad + outerSphereRad) break;
float tempDist = DistanceToObject(tempPos);
sunShadow *= saturate(tempDist*50.0);
if (tempDist <= 0.0) break;
//iter *= 1.5; // constant is more reliable than distance-based???
iter += max(0.01, tempDist)*1.0;
}
sunShadow = saturate(sunShadow);
// calculate the reflection vector for highlights
vec3 ref = reflect(relVec, normal);
// make sure the texture gets rotated along with the geometry.
vec3 posTex = pos;
if (dot(pos, rotDir) > 1.0) posTex = pos * rotMat;
posTex = abs(posTex); // make texture symetric so it doesn't pop after rotation
// make a few frequencies of noise to give it some texture
float n =0.0;
n += noise(posTex*32.0);
n += noise(posTex*64.0);
n += noise(posTex*128.0);
n += noise(posTex*256.0);
n += noise(posTex*512.0);
n *= 0.8;
normal = normalize(normal + n*0.1);
// ------ Calculate texture color ------
vec3 texColor = vec3(0.95, 1.0, 1.0);
vec3 rust = vec3(0.65, 0.25, 0.1) - noise(posTex*128.0);
texColor *= smoothstep(texColor, rust, vec3(saturate(RustNoise3D(posTex*8.0))-0.2));
// make outer edge a little brighter
texColor += (1.0 - vec3(19.0, 5.0, 2.0) * length(normalU))*ambientS;
// apply noise
texColor *= vec3(1.0)*n*0.05;
texColor *= 0.7;
texColor = saturate(texColor);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(0.6) * saturate(dot(sunDir, normal)) * sunShadow;
// weighted average the near ambient occlusion with the far for just the right look
float ambientAvg = (ambient*3.0 + ambientS) * 0.25;
// a red and blue light coming from different directions
lightColor += (vec3(1.0, 0.2, 0.4) * saturate(-normal.z *0.5+0.5))*pow(ambientAvg, 0.5);
lightColor += (vec3(0.1, 0.5, 0.99) * saturate(normal.y *0.5+0.5))*pow(ambientAvg, 0.5);
// blue glow light coming from the glow in the middle of the sphere
lightColor += vec3(0.3, 0.5, 0.9) * saturate(dot(-pos, normal))*pow(ambientS, 0.3);
// lightColor *= ambient;
lightColor *= 4.0;
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// sun reflection to make it look metal
finalColor += vec3(1.0)*pow(n,4.0)* GetSunColorSmall(ref, sunDir) * sunShadow;// * ambientS;
// fog that fades to reddish plus the sun color so that fog is brightest towards sun
//finalColor = mix(vec3(1.0, 0.41, 0.41)*skyMultiplier + min(vec3(0.25),GetSunColorSmall(relVec, sunDir))*2.0*sunSet, finalColor, exp(-t*0.003));
// pulse the outer edge color when something is about to rotate
if (dot(pos, rotDir) > 1.0) finalColor += vec3(0.2, 1.4, 0.8)*pulse*saturate(0.000001 / pow(abs(length(pos)-outerSphereRad), 2.0))*2.0;
}
else
{
// Our ray trace hit nothing, so draw sky.
//finalColor = saturate(GetSunColorSmall(relVec, sunDir)*0.95-0.01);
}
// add the ray marching glow
finalColor += vec3(0.3, 0.5, 0.9) * glow;
// vignette?
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
finalColor *= 1.3;
// output the final color with sqrt for "gamma correction"
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
4341,
4412,
4444,
4534,
6672
] | [
[
695,
714,
737,
737,
810
],
[
811,
811,
834,
834,
905
],
[
906,
906,
929,
929,
1015
],
[
1016,
1016,
1057,
1057,
1100
],
[
1138,
1138,
1162,
1162,
1435
],
[
1436,
1436,
1458,
1458,
2043
],
[
2198,
2198,
2221,
2221,
2250
],
[
2251,
2251,
2274,
2274,
2303
],
[
2304,
2304,
2329,
2329,
2358
],
[
2489,
2489,
2543,
2543,
2846
],
[
2847,
2847,
2896,
2896,
3150
],
[
3152,
3681,
3708,
3708,
4272
],
[
4341,
4412,
4444,
4534,
6672
],
[
6674,
6674,
6731,
6816,
16639
]
] | // This is the big money function that makes the crazy fractally shape
| float DistanceToObject(vec3 p)
{ |
if (dot(p, rotDir) > 1.0) p *= rotMat;
// Repeat our position so we can carve out many cylindrical-like things from our solid
vec3 rep = fract(p)-0.5;
//final = max(final, -(length(rep.xz*rep.xz)*1.0 - 0.0326));
float final = -(length(rep.xy*rep.xz) - 0.109);
final = max(final, -(length(rep.zy) - 0.33));
//final = max(final, -(length(rep.xz*rep.xz) - 0.03));
//final = max(final, -(length(rep.yz*rep.yz) - 0.03));
//final = max(final, -(length(rep.xy*rep.xy) - 0.030266));
// Repeat the process of carving things out for smaller scales
vec3 rep2 = fract(rep*2.0)-0.5;
final = max(final, -(length(rep2.xz)*0.5 - 0.125));
final = max(final, -(length(rep2.xy)*0.5 - 0.125));
final = max(final, -(length(rep2.zy)*0.5 - 0.125));
vec3 rep3 = fract(rep2*3.0)-0.5;
final = max(final, -(length(rep3.xz)*0.1667 - 0.25*0.1667));
final = max(final, -(length(rep3.xy)*0.1667 - 0.25*0.1667));
final = max(final, -(length(rep3.zy)*0.1667 - 0.25*0.1667));
#ifdef TOO_MUCH_FRACTAL
vec3 rep4 = fract(rep3*3.0)-0.5;
final = max(final, -(length(rep4.xz)*0.0555 - 0.25*0.0555));
final = max(final, -(length(rep4.xy)*0.0555 - 0.25*0.0555));
final = max(final, -(length(rep4.yz)*0.0555 - 0.25*0.0555));
vec3 rep5 = fract(rep4*3.0)-0.5;
final = max(final, -(length(rep5.xz)*0.0185 - 0.25*0.0185));
final = max(final, -(length(rep5.xy)*0.0185 - 0.25*0.0185));
final = max(final, -(length(rep5.yz)*0.0185 - 0.25*0.0185));
#endif
// Cut out stuff outside of outer sphere
final = max(final, (length(p) - outerSphereRad));
// Carve out inner sphere
final = max(final, -(length(p) - 2.8));
//final = max(final, abs(p.x) - 2.0); // for that space station look
//final = (length(p) - outerSphereRad); // for debugging texture and lighting
// Slice the object in a 3d grid so it can rotate like a rubik's cube
float slice = 0.02;
vec3 grid = -abs(fract(p.xyz)) + slice;
final = max(final, grid.x);
final = max(final, grid.y);
final = max(final, grid.z);
//final = min(final, abs(p.y));
return final;
} | // This is the big money function that makes the crazy fractally shape
float DistanceToObject(vec3 p)
{ | 1 | 6 |
Mlf3R4 | otaviogood | 2014-12-20T22:43:30 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^This means do anything you want with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// Set this to change detail level. [1 - 10] is a good range.
const int NUM_SIN_REPS = 9;
const int MAX_MARCH_REPS = 250;
const float MARCH_DISTANCE_MULTIPLIER = 0.1;
float localTime = 0.0;
// some noise functions
float Hash(float f)
{
return fract(cos(f)*7561.0);
}
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 521.0; // repeats after this value
float rand = fract(cos(f)*104729.0);
return rand;
}
vec2 Hash2(vec2 v)
{
return fract(cos(v*3.333)*vec2(100003.9, 37049.7));
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(sin(f)*110003.9);
}
float mixS(float f0, float f1, float a)
{
if (a < 0.5) return f0;
return f1;
}
float mixC(float f0, float f1, float a)
{
return mix(f1, f0, cos(a*3.1415926) *0.5+0.5);
}
float mixP(float f0, float f1, float a)
{
return mix(f0, f1, a*a*(3.0-2.0*a));
}
vec2 mixP2(vec2 v0, vec2 v1, float a)
{
return mix(v0, v1, a*a*(3.0-2.0*a));
}
float mixSS(float f0, float f1, float a)
{
return mix(f0, f1, smoothstep(0.0, 1.0, a));
}
const vec2 zeroOne = vec2(0.0, 1.0);
float noise2dVec(vec2 uv)
{
vec2 fr = fract(uv);
vec2 fl = floor(uv);
vec2 h0 = vec2(Hash2d(fl), Hash2d(fl + zeroOne));
vec2 h1 = vec2(Hash2d(fl + zeroOne.yx), Hash2d(fl + zeroOne.yy));
vec2 xMix = mixP2(h0, h1, fr.x);
return mixC(xMix.x, xMix.y, fr.y);
}
float noise2d(vec2 uv)
{
vec2 fr = fract(uv);
vec2 fl = floor(uv);
float h00 = Hash2d(fl);
float h10 = Hash2d(fl + zeroOne.yx);
float h01 = Hash2d(fl + zeroOne);
float h11 = Hash2d(fl + zeroOne.yy);
return mixP(mixP(h00, h10, fr.x), mixP(h01, h11, fr.x), fr.y);
}
float noise(vec3 uv)
{
vec3 fr = fract(uv.xyz);
vec3 fl = floor(uv.xyz);
float h000 = Hash3d(fl);
float h100 = Hash3d(fl + zeroOne.yxx);
float h010 = Hash3d(fl + zeroOne.xyx);
float h110 = Hash3d(fl + zeroOne.yyx);
float h001 = Hash3d(fl + zeroOne.xxy);
float h101 = Hash3d(fl + zeroOne.yxy);
float h011 = Hash3d(fl + zeroOne.xyy);
float h111 = Hash3d(fl + zeroOne.yyy);
return mixP(
mixP(mixP(h000, h100, fr.x),
mixP(h010, h110, fr.x), fr.y),
mixP(mixP(h001, h101, fr.x),
mixP(h011, h111, fr.x), fr.y)
, fr.z);
}
float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
//else return new float3(x, cos * y - sin * z, sin * y + cos * z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
//else return new float3(cos * x + sin * z, y, -sin * x + cos * z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
//if (RIGHT_HANDED_COORD)
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
// This function basically is a procedural environment map that makes the sun
vec3 sunCol = vec3(258.0, 228.0, 170.0) / 3555.0;//unfortunately, i seem to have 2 different sun colors. :(
vec3 GetSunColorReflection(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.015 / dist;
sunIntensity = pow(sunIntensity, 0.3)*100.0;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
//vec3 skyColor = mix(vec3(1.0, 0.95, 0.85), vec3(0.2,0.3,0.95), pow(saturate(rayDir.y), 0.7))*skyMultiplier*0.95;
return sunCol * sunIntensity*0.0425;
}
vec3 GetSunColorSmall(vec3 rayDir, vec3 sunDir)
{
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.05 / dist;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
return sunCol * sunIntensity*0.025;
}
vec4 cXX = vec4(0.0, 3.0, 0.0, 0.0);
vec3 camPos = vec3(0.0), camFacing;
vec3 camLookat=vec3(0,0.0,0);
float SinRep(float a)
{
float h = 0.0;
float mult = 1.0;
for (int i = 0; i < NUM_SIN_REPS; i++)
{
h += (cos(a*mult)/(mult));
mult *= 2.0;
}
return h;
}
vec2 DistanceToObject(vec3 p)
{
float material = 0.0;
float h = 0.0;
p = RotateY(p, p.y*0.4 - cos(localTime)*0.4);
h += SinRep(RotateY(p, p.z*3.14*0.25).x);
h += SinRep(RotateZ(p, p.x*3.14*0.25).y);
h += SinRep(RotateX(p, p.y*3.14*0.25).z);
material = h;
//h += SinRep(RotateX(p, p.y).z);
//h += SinRep(RotateZ(p, sin(h)).y);
//h += SinRep(RotateY(p, h*1.0).x);
//h += SinRep(p.x+h)*0.5;
//h += SinRep(p.y+h)*0.5;
float final = (length(p)-4.0 - h*(0.25 + sin(localTime)*0.35));
return vec2(final, material);
}
float distFromSphere;
float IntersectSphereAndRay(vec3 pos, float radius, vec3 posA, vec3 posB, out vec3 intersectA2, out vec3 intersectB2)
{
// Use dot product along line to find closest point on line
vec3 eyeVec2 = normalize(posB-posA);
float dp = dot(eyeVec2, pos - posA);
vec3 pointOnLine = eyeVec2 * dp + posA;
// Clamp that point to line end points if outside
//if ((dp - radius) < 0) pointOnLine = posA;
//if ((dp + radius) > (posB-posA).Length()) pointOnLine = posB;
// Distance formula from that point to sphere center, compare with radius.
float distance = length(pointOnLine - pos);
float ac = radius*radius - distance*distance;
float rightLen = 0.0;
if (ac >= 0.0) rightLen = sqrt(ac);
intersectA2 = pointOnLine - eyeVec2 * rightLen;
intersectB2 = pointOnLine + eyeVec2 * rightLen;
distFromSphere = distance - radius;
if (distance <= radius) return 1.0;
return 0.0;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
localTime = iTime - 1.6;
// ---------------- First, set up the camera rays for ray marching ----------------
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
// Camera up vector.
vec3 camUp=vec3(0,1,0); // vuv
// Camera lookat.
camLookat=vec3(0,0.0,0); // vrp
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0-0.7 + localTime * 0.123;
float my=-iMouse.y/iResolution.y*10.0 - sin(localTime * 0.31)*0.5;//*PI/2.01;
camPos += vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*(9.2); // prp
// add randomness to camera for depth-of-field look close up.
//camPos += vec3(Hash2d(uv)*0.91, Hash2d(uv+37.0), Hash2d(uv+47.0))*0.01;
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);//vpn
vec3 sideNorm=normalize(cross(camUp, camVec)); // u
vec3 upNorm=cross(camVec, sideNorm);//v
vec3 worldFacing=(camPos + camVec);//vcv
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;//scrCoord
vec3 relVec = normalize(worldPix - camPos);//scp
// --------------------------------------------------------------------------------
// I put a bounding sphere around the whole object. If the ray is outside
// of the bounding sphere, I don't bother ray marching. It's just an optimization.
vec3 iA, iB;
float hit = IntersectSphereAndRay(vec3(0,0,0), 7.6, camPos, camPos+relVec, iA, iB);
// --------------------------------------------------------------------------------
vec2 distAndMat = vec2(0.05, 0.0);
float t = 0.0;
float inc = 0.02;
float maxDepth = 110.0;
vec3 pos = vec3(0,0,0);
// start and end the camera ray at the sphere intersections.
camPos = iA;
maxDepth = distance(iA, iB);
// ray marching time
if (hit > 0.5) // check if inside bounding sphere before wasting time ray marching.
{
for (int i = 0; i < MAX_MARCH_REPS; i++) // This is the count of the max times the ray actually marches.
{
if ((t > maxDepth) || (abs(distAndMat.x) < 0.0075)) break;
pos = camPos + relVec * t;
// *******************************************************
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry.
// *******************************************************
distAndMat = DistanceToObject(pos);
// adjust by constant because deformations mess up distance function.
t += distAndMat.x * MARCH_DISTANCE_MULTIPLIER;
}
}
else
{
t = maxDepth + 1.0;
distAndMat.x = 1.0;
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
vec3 sunDir = normalize(vec3(0.93, 1.0, -1.5));
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
if (abs(distAndMat.x) < 0.75)
//if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(0.005, 0, 0);
vec3 normalU = vec3(distAndMat.x - DistanceToObject(pos - smallVec.xyy).x,
distAndMat.x - DistanceToObject(pos - smallVec.yxy).x,
distAndMat.x - DistanceToObject(pos - smallVec.yyx).x);
vec3 normal = normalize(normalU);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff - so the green sphere light source can also have ambient.
float ambientS = 1.0;
ambientS *= saturate(DistanceToObject(pos + normal * 0.1).x*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2).x*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4).x*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8).x*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6).x*1.25*0.5);
ambient *= saturate(DistanceToObject(pos + normal * 3.2).x*1.25*0.25);
ambient *= saturate(DistanceToObject(pos + normal * 6.4).x*1.25*0.125);
ambient = max(0.15, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// Trace a ray toward the sun for sun shadows
float sunShadow = 1.0;
float iter = 0.2;
for (int i = 0; i < 10; i++)
{
float tempDist = DistanceToObject(pos + sunDir * iter).x;
sunShadow *= saturate(tempDist*10.0);
if (tempDist <= 0.0) break;
iter *= 1.5; // constant is more reliable than distance-based
//iter += max(0.2, tempDist)*1.2;
}
sunShadow = saturate(sunShadow);
// calculate the reflection vector for highlights
vec3 ref = reflect(relVec, normal);
// ------ Calculate texture color of the rock ------
// base texture can be swirled noise.
vec3 rp = RotateY(pos, pos.y*0.4 - cos(localTime)*0.4);
float n = noise(rp*4.0) + noise(rp*8.0) + noise(rp*16.0) + noise(rp*32.0);
n = saturate(n*0.25 * 0.95 + 0.05);
vec3 texColor = vec3(0.2,0.3,0.3)*n;
// fade to reddish texture on outside
texColor += vec3(0.99, 0.21, 0.213) * clamp(length(pos)-4.0, 0.0, 0.4);
// give it green-blue texture that matches the shape using normal length
texColor += vec3(1.0, 21.0, 26.0)*0.6 * saturate(length(normalU)-0.01);
// Give it a reddish-rust color in the middle
texColor -= vec3(0.0, 0.3, 0.5)*saturate(-distAndMat.y*(0.9+sin(localTime+0.5)*0.9));
// make sure it's not too saturated so it looks realistic
texColor = max(vec3(0.02),texColor);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = sunCol * saturate(dot(sunDir, normal)) * sunShadow*14.0;
// sky color, hemisphere light equation approximation, anbient occlusion
lightColor += vec3(0.1,0.35,0.95) * (normal.y * 0.5 + 0.5) * ambient * 0.25;
// ground color - another hemisphere light
lightColor += vec3(1.0) * ((-normal.y) * 0.5 + 0.5) * ambient * 0.2;
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// specular highlights - just a little
vec3 refColor = GetSunColorReflection(ref, sunDir)*0.68;
finalColor += refColor * sunCol * sunShadow * 9.0 * texColor.g;
// fog that fades to sun color so that fog is brightest towards sun
finalColor = mix(vec3(0.98, 0.981, 0.981) + min(vec3(0.25),GetSunColorSmall(relVec, sunDir))*2.0, finalColor, exp(-t*0.007));
//finalColor = vec3(1.0, 21.0, 26.0) * saturate(length(normalU)-0.01);
}
else
{
// Our ray trace hit nothing, so draw sky.
// fade the sky color, multiply sunset dimming
finalColor = mix(vec3(1.0, 0.95, 0.85), vec3(0.2,0.5,0.95), pow(saturate(relVec.y), 0.7))*0.95;
// add the sun
finalColor += GetSunColorSmall(relVec, sunDir);// + vec3(0.1, 0.1, 0.1);
}
// vignette?
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
finalColor *= 1.95;
// output the final color with sqrt for "gamma correction"
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
3698,
3884,
3938,
3938,
4360
] | [
[
753,
777,
798,
798,
833
],
[
834,
834,
857,
857,
980
],
[
981,
981,
1001,
1001,
1059
],
[
1060,
1060,
1083,
1083,
1169
],
[
1171,
1171,
1212,
1212,
1257
],
[
1259,
1259,
1300,
1300,
1353
],
[
1355,
1355,
1396,
1396,
1439
],
[
1440,
1440,
1479,
1479,
1522
],
[
1524,
1524,
1566,
1566,
1617
],
[
1656,
1656,
1683,
1683,
1935
],
[
1936,
1936,
1960,
1960,
2227
],
[
2228,
2228,
2250,
2250,
2835
],
[
2859,
2859,
2882,
2882,
2911
],
[
2912,
2912,
2935,
2935,
2964
],
[
2965,
2965,
2990,
2990,
3019
],
[
3021,
3021,
3054,
3054,
3268
],
[
3269,
3269,
3302,
3302,
3516
],
[
3517,
3517,
3550,
3550,
3695
],
[
3698,
3884,
3938,
3938,
4360
],
[
4361,
4361,
4410,
4410,
4664
],
[
4771,
4771,
4794,
4794,
4962
],
[
4964,
4964,
4995,
4995,
5529
],
[
5553,
5553,
5672,
5733,
6427
],
[
6430,
6430,
6487,
6487,
13965
]
] | // This function basically is a procedural environment map that makes the sun
vec3 sunCol = vec3(258.0, 228.0, 170.0) / 3555.0;//unfortunately, i seem to have 2 different sun colors. :(
| vec3 GetSunColorReflection(vec3 rayDir, vec3 sunDir)
{ |
vec3 localRay = normalize(rayDir);
float dist = 1.0 - (dot(localRay, sunDir) * 0.5 + 0.5);
float sunIntensity = 0.015 / dist;
sunIntensity = pow(sunIntensity, 0.3)*100.0;
sunIntensity += exp(-dist*12.0)*300.0;
sunIntensity = min(sunIntensity, 40000.0);
//vec3 skyColor = mix(vec3(1.0, 0.95, 0.85), vec3(0.2,0.3,0.95), pow(saturate(rayDir.y), 0.7))*skyMultiplier*0.95;
return sunCol * sunIntensity*0.0425;
} | // This function basically is a procedural environment map that makes the sun
vec3 sunCol = vec3(258.0, 228.0, 170.0) / 3555.0;//unfortunately, i seem to have 2 different sun colors. :(
vec3 GetSunColorReflection(vec3 rayDir, vec3 sunDir)
{ | 2 | 8 |
XljGDz | otaviogood | 2015-04-07T03:58:40 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^This means do anything you want with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// Number of times the fractal repeats
#define RECURSION_LEVELS 4
// Animation splits the sphere in different directions
// This ended up running a significantly slower fps and not looking very different. :(
//#define SPLIT_ANIM
float localTime = 0.0;
float marchCount;
float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
/*vec3 GetEnvColor(vec3 rayDir, vec3 sunDir)
{
vec3 tex = texture(iChannel0, rayDir).xyz;
tex = tex * tex; // gamma correct
return tex;
}*/
// This is a procedural environment map with a giant overhead softbox,
// 4 lights in a horizontal circle, and a bottom-to-top fade.
vec3 GetEnvColor2(vec3 rayDir, vec3 sunDir)
{
// fade bottom to top so it looks like the softbox is casting light on a floor
// and it's bouncing back
vec3 final = vec3(1.0) * dot(-rayDir, sunDir) * 0.5 + 0.5;
final *= 0.125;
// overhead softbox, stretched to a rectangle
if ((rayDir.y > abs(rayDir.x)*1.0) && (rayDir.y > abs(rayDir.z*0.25))) final = vec3(2.0)*rayDir.y;
// fade the softbox at the edges with a rounded rectangle.
float roundBox = length(max(abs(rayDir.xz/max(0.0,rayDir.y))-vec2(0.9, 4.0),0.0))-0.1;
final += vec3(0.8)* pow(saturate(1.0 - roundBox*0.5), 6.0);
// purple lights from side
final += vec3(8.0,6.0,7.0) * saturate(0.001/(1.0 - abs(rayDir.x)));
// yellow lights from side
final += vec3(8.0,7.0,6.0) * saturate(0.001/(1.0 - abs(rayDir.z)));
return vec3(final);
}
/*vec3 GetEnvColorReflection(vec3 rayDir, vec3 sunDir, float ambient)
{
vec3 tex = texture(iChannel0, rayDir).xyz;
tex = tex * tex;
vec3 texBack = texture(iChannel0, rayDir).xyz;
vec3 texDark = pow(texBack, vec3(50.0)).zzz; // fake hdr texture
texBack += texDark*0.5 * ambient;
return texBack*texBack*texBack;
}*/
vec3 camPos = vec3(0.0), camFacing;
vec3 camLookat=vec3(0,0.0,0);
// polynomial smooth min (k = 0.1);
float smin( float a, float b, float k )
{
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
vec2 matMin(vec2 a, vec2 b)
{
if (a.x < b.x) return a;
else return b;
}
float spinTime;
vec3 diagN = normalize(vec3(-1.0));
float cut = 0.77;
float inner = 0.333;
float outness = 1.414;
float finWidth;
float teeth;
float globalTeeth;
vec2 sphereIter(vec3 p, float radius, float subA)
{
finWidth = 0.1;
teeth = globalTeeth;
float blender = 0.25;
vec2 final = vec2(1000000.0, 0.0);
for (int i = 0; i < RECURSION_LEVELS; i++)
{
#ifdef SPLIT_ANIM
// rotate top and bottom of sphere opposite directions
p = RotateY(p, spinTime*sign(p.y)*0.05/blender);
#endif
// main sphere
float d = length(p) - radius*outness;
#ifdef SPLIT_ANIM
// subtract out disc at the place where rotation happens so we don't have artifacts
d = max(d, -(max(length(p) - radius*outness + 0.1, abs(p.y) - finWidth*0.25)));
#endif
// calc new position at 8 vertices of cube, scaled
vec3 corners = abs(p) + diagN * radius;
float lenCorners = length(corners);
// subtract out main sphere hole, mirrored on all axises
float subtracter = lenCorners - radius * subA;
// make mirrored fins that go through all vertices of the cube
vec3 ap = abs(-p) * 0.7071; // 1/sqrt(2) to keep distance field normalized
subtracter = max(subtracter, -(abs(ap.x-ap.y) - finWidth));
subtracter = max(subtracter, -(abs(ap.y-ap.z) - finWidth));
subtracter = max(subtracter, -(abs(ap.z-ap.x) - finWidth));
// subtract sphere from fins so they don't intersect the inner spheres.
// also animate them so they are like teeth
subtracter = min(subtracter, lenCorners - radius * subA + teeth);
// smoothly subtract out that whole complex shape
d = -smin(-d, subtracter, blender);
//vec2 sphereDist = sphereB(abs(p) + diagN * radius, radius * inner, cut); // recurse
// do a material-min with the last iteration
final = matMin(final, vec2(d, float(i)));
#ifndef SPLIT_ANIM
corners = RotateY(corners, spinTime*0.25/blender);
#endif
// Simple rotate 90 degrees on X axis to keep things fresh
p = vec3(corners.x, corners.z, -corners.y);
// Scale things for the next iteration / recursion-like-thing
radius *= inner;
teeth *= inner;
finWidth *= inner;
blender *= inner;
}
// Bring in the final smallest-sized sphere
float d = length(p) - radius*outness;
final = matMin(final, vec2(d, 6.0));
return final;
}
vec2 DistanceToObject(vec3 p)
{
vec2 distMat = sphereIter(p, 5.2 / outness, cut);
return distMat;
}
// dirVec MUST BE NORMALIZED FIRST!!!!
float SphereIntersect(vec3 pos, vec3 dirVecPLZNormalizeMeFirst, vec3 spherePos, float rad)
{
vec3 radialVec = pos - spherePos;
float b = dot(radialVec, dirVecPLZNormalizeMeFirst);
float c = dot(radialVec, radialVec) - rad * rad;
float h = b * b - c;
if (h < 0.0) return -1.0;
return -b - sqrt(h);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
localTime = iTime - 0.0;
// ---------------- First, set up the camera rays for ray marching ----------------
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
float zoom = 1.7;
uv /= zoom;
// Camera up vector.
vec3 camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0,0.0,0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0-0.7 + localTime*3.1415 * 0.0625*0.666;
float my=-iMouse.y/iResolution.y*10.0 - sin(localTime * 0.31)*0.5;//*PI/2.01;
camPos += vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*(12.2);
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 rayVec = normalize(worldPix - camPos);
// ----------------------------------- Animate ------------------------------------
localTime = iTime*0.5;
// This is a wave function like a triangle wave, but with flat tops and bottoms.
// period is 1.0
float rampStep = min(3.0,max(1.0, abs((fract(localTime)-0.5)*1.0)*8.0))*0.5-0.5;
rampStep = smoothstep(0.0, 1.0, rampStep);
// lopsided triangle wave - goes up for 3 time units, down for 1.
float step31 = (max(0.0, (fract(localTime+0.125)-0.25)) - min(0.0,(fract(localTime+0.125)-0.25))*3.0)*0.333;
spinTime = step31 + localTime;
//globalTeeth = 0.0 + max(0.0, sin(localTime*3.0))*0.9;
globalTeeth = rampStep*0.99;
cut = max(0.48, min(0.77, localTime));
// --------------------------------------------------------------------------------
vec2 distAndMat = vec2(0.5, 0.0);
float t = 0.0;
//float inc = 0.02;
float maxDepth = 24.0;
vec3 pos = vec3(0,0,0);
marchCount = 0.0;
// intersect with sphere first as optimization so we don't ray march more than is needed.
float hit = SphereIntersect(camPos, rayVec, vec3(0.0), 5.6);
if (hit >= 0.0)
{
t = hit;
// ray marching time
for (int i = 0; i < 290; i++) // This is the count of the max times the ray actually marches.
{
pos = camPos + rayVec * t;
// *******************************************************
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry.
// *******************************************************
distAndMat = DistanceToObject(pos);
// adjust by constant because deformations mess up distance function.
t += distAndMat.x * 0.7;
//if (t > maxDepth) break;
if ((t > maxDepth) || (abs(distAndMat.x) < 0.0025)) break;
marchCount+= 1.0;
}
}
else
{
t = maxDepth + 1.0;
distAndMat.x = 1000000.0;
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
vec3 sunDir = normalize(vec3(3.93, 10.82, -1.5));
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
//if (abs(distAndMat.x) < 0.75)
if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(0.005, 0, 0);
vec3 normalU = vec3(distAndMat.x - DistanceToObject(pos - smallVec.xyy).x,
distAndMat.x - DistanceToObject(pos - smallVec.yxy).x,
distAndMat.x - DistanceToObject(pos - smallVec.yyx).x);
vec3 normal = normalize(normalU);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff
float ambientS = 1.0;
ambientS *= saturate(DistanceToObject(pos + normal * 0.1).x*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2).x*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4).x*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8).x*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6).x*1.25*0.5);
ambient *= saturate(DistanceToObject(pos + normal * 3.2).x*1.25*0.25);
ambient *= saturate(DistanceToObject(pos + normal * 6.4).x*1.25*0.125);
ambient = max(0.035, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// calculate the reflection vector for highlights
vec3 ref = reflect(rayVec, normal);
ref = normalize(ref);
// Trace a ray for the reflection
float sunShadow = 1.0;
float iter = 0.1;
vec3 nudgePos = pos + normal*0.02; // don't start tracing too close or inside the object
for (int i = 0; i < 40; i++)
{
float tempDist = DistanceToObject(nudgePos + ref * iter).x;
sunShadow *= saturate(tempDist*50.0);
if (tempDist <= 0.0) break;
//iter *= 1.5; // constant is more reliable than distance-based
iter += max(0.00, tempDist)*1.0;
if (iter > 4.2) break;
}
sunShadow = saturate(sunShadow);
// ------ Calculate texture color ------
vec3 texColor;
texColor = vec3(1.0);// vec3(0.65, 0.5, 0.4)*0.1;
texColor = vec3(0.85, 0.945 - distAndMat.y * 0.15, 0.93 + distAndMat.y * 0.35)*0.951;
if (distAndMat.y == 6.0) texColor = vec3(0.91, 0.1, 0.41)*10.5;
//texColor *= mix(vec3(0.3), vec3(1.0), tex3d(pos*0.5, normal).xxx);
texColor = max(texColor, vec3(0.0));
texColor *= 0.25;
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(0.0);// sunCol * saturate(dot(sunDir, normal)) * sunShadow*14.0;
// sky color, hemisphere light equation approximation, ambient occlusion
lightColor += vec3(0.1,0.35,0.95) * (normal.y * 0.5 + 0.5) * ambient * 0.2;
// ground color - another hemisphere light
lightColor += vec3(1.0) * ((-normal.y) * 0.5 + 0.5) * ambient * 0.2;
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
//if (distAndMat.y == ceil(mod(localTime, 4.0))) finalColor += vec3(0.0, 0.41, 0.72)*0.925;
// reflection environment map - this is most of the light
vec3 refColor = GetEnvColor2(ref, sunDir)*sunShadow;
finalColor += refColor * 0.35 * ambient;// * sunCol * sunShadow * 9.0 * texColor.g;
// fog
finalColor = mix(vec3(1.0, 0.41, 0.41) + vec3(1.0), finalColor, exp(-t*0.0007));
// visualize length of gradient of distance field to check distance field correctness
//finalColor = vec3(0.5) * (length(normalU) / smallVec.x);
}
else
{
finalColor = GetEnvColor2(rayVec, sunDir);// + vec3(0.1, 0.1, 0.1);
}
//finalColor += marchCount * vec3(1.0, 0.3, 0.91) * 0.001;
// vignette?
//finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
//finalColor *= 1.95;
// output the final color with sqrt for "gamma correction"
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
1619,
1752,
1797,
1910,
2596
] | [
[
856,
856,
879,
879,
908
],
[
909,
909,
932,
932,
961
],
[
962,
962,
987,
987,
1016
],
[
1018,
1018,
1051,
1051,
1168
],
[
1169,
1169,
1202,
1202,
1318
],
[
1319,
1319,
1352,
1352,
1469
],
[
1619,
1752,
1797,
1910,
2596
],
[
2998,
3034,
3075,
3075,
3168
],
[
3170,
3170,
3199,
3199,
3243
],
[
3408,
3408,
3459,
3459,
5710
],
[
5712,
5712,
5743,
5743,
5819
],
[
5821,
5860,
5952,
5952,
6182
],
[
6184,
6184,
6241,
6241,
13613
]
] | // This is a procedural environment map with a giant overhead softbox,
// 4 lights in a horizontal circle, and a bottom-to-top fade.
| vec3 GetEnvColor2(vec3 rayDir, vec3 sunDir)
{ |
vec3 final = vec3(1.0) * dot(-rayDir, sunDir) * 0.5 + 0.5;
final *= 0.125;
// overhead softbox, stretched to a rectangle
if ((rayDir.y > abs(rayDir.x)*1.0) && (rayDir.y > abs(rayDir.z*0.25))) final = vec3(2.0)*rayDir.y;
// fade the softbox at the edges with a rounded rectangle.
float roundBox = length(max(abs(rayDir.xz/max(0.0,rayDir.y))-vec2(0.9, 4.0),0.0))-0.1;
final += vec3(0.8)* pow(saturate(1.0 - roundBox*0.5), 6.0);
// purple lights from side
final += vec3(8.0,6.0,7.0) * saturate(0.001/(1.0 - abs(rayDir.x)));
// yellow lights from side
final += vec3(8.0,7.0,6.0) * saturate(0.001/(1.0 - abs(rayDir.z)));
return vec3(final);
} | // This is a procedural environment map with a giant overhead softbox,
// 4 lights in a horizontal circle, and a bottom-to-top fade.
vec3 GetEnvColor2(vec3 rayDir, vec3 sunDir)
{ | 2 | 2 |
XljGDz | otaviogood | 2015-04-07T03:58:40 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^This means do anything you want with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// Number of times the fractal repeats
#define RECURSION_LEVELS 4
// Animation splits the sphere in different directions
// This ended up running a significantly slower fps and not looking very different. :(
//#define SPLIT_ANIM
float localTime = 0.0;
float marchCount;
float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
/*vec3 GetEnvColor(vec3 rayDir, vec3 sunDir)
{
vec3 tex = texture(iChannel0, rayDir).xyz;
tex = tex * tex; // gamma correct
return tex;
}*/
// This is a procedural environment map with a giant overhead softbox,
// 4 lights in a horizontal circle, and a bottom-to-top fade.
vec3 GetEnvColor2(vec3 rayDir, vec3 sunDir)
{
// fade bottom to top so it looks like the softbox is casting light on a floor
// and it's bouncing back
vec3 final = vec3(1.0) * dot(-rayDir, sunDir) * 0.5 + 0.5;
final *= 0.125;
// overhead softbox, stretched to a rectangle
if ((rayDir.y > abs(rayDir.x)*1.0) && (rayDir.y > abs(rayDir.z*0.25))) final = vec3(2.0)*rayDir.y;
// fade the softbox at the edges with a rounded rectangle.
float roundBox = length(max(abs(rayDir.xz/max(0.0,rayDir.y))-vec2(0.9, 4.0),0.0))-0.1;
final += vec3(0.8)* pow(saturate(1.0 - roundBox*0.5), 6.0);
// purple lights from side
final += vec3(8.0,6.0,7.0) * saturate(0.001/(1.0 - abs(rayDir.x)));
// yellow lights from side
final += vec3(8.0,7.0,6.0) * saturate(0.001/(1.0 - abs(rayDir.z)));
return vec3(final);
}
/*vec3 GetEnvColorReflection(vec3 rayDir, vec3 sunDir, float ambient)
{
vec3 tex = texture(iChannel0, rayDir).xyz;
tex = tex * tex;
vec3 texBack = texture(iChannel0, rayDir).xyz;
vec3 texDark = pow(texBack, vec3(50.0)).zzz; // fake hdr texture
texBack += texDark*0.5 * ambient;
return texBack*texBack*texBack;
}*/
vec3 camPos = vec3(0.0), camFacing;
vec3 camLookat=vec3(0,0.0,0);
// polynomial smooth min (k = 0.1);
float smin( float a, float b, float k )
{
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
vec2 matMin(vec2 a, vec2 b)
{
if (a.x < b.x) return a;
else return b;
}
float spinTime;
vec3 diagN = normalize(vec3(-1.0));
float cut = 0.77;
float inner = 0.333;
float outness = 1.414;
float finWidth;
float teeth;
float globalTeeth;
vec2 sphereIter(vec3 p, float radius, float subA)
{
finWidth = 0.1;
teeth = globalTeeth;
float blender = 0.25;
vec2 final = vec2(1000000.0, 0.0);
for (int i = 0; i < RECURSION_LEVELS; i++)
{
#ifdef SPLIT_ANIM
// rotate top and bottom of sphere opposite directions
p = RotateY(p, spinTime*sign(p.y)*0.05/blender);
#endif
// main sphere
float d = length(p) - radius*outness;
#ifdef SPLIT_ANIM
// subtract out disc at the place where rotation happens so we don't have artifacts
d = max(d, -(max(length(p) - radius*outness + 0.1, abs(p.y) - finWidth*0.25)));
#endif
// calc new position at 8 vertices of cube, scaled
vec3 corners = abs(p) + diagN * radius;
float lenCorners = length(corners);
// subtract out main sphere hole, mirrored on all axises
float subtracter = lenCorners - radius * subA;
// make mirrored fins that go through all vertices of the cube
vec3 ap = abs(-p) * 0.7071; // 1/sqrt(2) to keep distance field normalized
subtracter = max(subtracter, -(abs(ap.x-ap.y) - finWidth));
subtracter = max(subtracter, -(abs(ap.y-ap.z) - finWidth));
subtracter = max(subtracter, -(abs(ap.z-ap.x) - finWidth));
// subtract sphere from fins so they don't intersect the inner spheres.
// also animate them so they are like teeth
subtracter = min(subtracter, lenCorners - radius * subA + teeth);
// smoothly subtract out that whole complex shape
d = -smin(-d, subtracter, blender);
//vec2 sphereDist = sphereB(abs(p) + diagN * radius, radius * inner, cut); // recurse
// do a material-min with the last iteration
final = matMin(final, vec2(d, float(i)));
#ifndef SPLIT_ANIM
corners = RotateY(corners, spinTime*0.25/blender);
#endif
// Simple rotate 90 degrees on X axis to keep things fresh
p = vec3(corners.x, corners.z, -corners.y);
// Scale things for the next iteration / recursion-like-thing
radius *= inner;
teeth *= inner;
finWidth *= inner;
blender *= inner;
}
// Bring in the final smallest-sized sphere
float d = length(p) - radius*outness;
final = matMin(final, vec2(d, 6.0));
return final;
}
vec2 DistanceToObject(vec3 p)
{
vec2 distMat = sphereIter(p, 5.2 / outness, cut);
return distMat;
}
// dirVec MUST BE NORMALIZED FIRST!!!!
float SphereIntersect(vec3 pos, vec3 dirVecPLZNormalizeMeFirst, vec3 spherePos, float rad)
{
vec3 radialVec = pos - spherePos;
float b = dot(radialVec, dirVecPLZNormalizeMeFirst);
float c = dot(radialVec, radialVec) - rad * rad;
float h = b * b - c;
if (h < 0.0) return -1.0;
return -b - sqrt(h);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
localTime = iTime - 0.0;
// ---------------- First, set up the camera rays for ray marching ----------------
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
float zoom = 1.7;
uv /= zoom;
// Camera up vector.
vec3 camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0,0.0,0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0-0.7 + localTime*3.1415 * 0.0625*0.666;
float my=-iMouse.y/iResolution.y*10.0 - sin(localTime * 0.31)*0.5;//*PI/2.01;
camPos += vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*(12.2);
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 rayVec = normalize(worldPix - camPos);
// ----------------------------------- Animate ------------------------------------
localTime = iTime*0.5;
// This is a wave function like a triangle wave, but with flat tops and bottoms.
// period is 1.0
float rampStep = min(3.0,max(1.0, abs((fract(localTime)-0.5)*1.0)*8.0))*0.5-0.5;
rampStep = smoothstep(0.0, 1.0, rampStep);
// lopsided triangle wave - goes up for 3 time units, down for 1.
float step31 = (max(0.0, (fract(localTime+0.125)-0.25)) - min(0.0,(fract(localTime+0.125)-0.25))*3.0)*0.333;
spinTime = step31 + localTime;
//globalTeeth = 0.0 + max(0.0, sin(localTime*3.0))*0.9;
globalTeeth = rampStep*0.99;
cut = max(0.48, min(0.77, localTime));
// --------------------------------------------------------------------------------
vec2 distAndMat = vec2(0.5, 0.0);
float t = 0.0;
//float inc = 0.02;
float maxDepth = 24.0;
vec3 pos = vec3(0,0,0);
marchCount = 0.0;
// intersect with sphere first as optimization so we don't ray march more than is needed.
float hit = SphereIntersect(camPos, rayVec, vec3(0.0), 5.6);
if (hit >= 0.0)
{
t = hit;
// ray marching time
for (int i = 0; i < 290; i++) // This is the count of the max times the ray actually marches.
{
pos = camPos + rayVec * t;
// *******************************************************
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry.
// *******************************************************
distAndMat = DistanceToObject(pos);
// adjust by constant because deformations mess up distance function.
t += distAndMat.x * 0.7;
//if (t > maxDepth) break;
if ((t > maxDepth) || (abs(distAndMat.x) < 0.0025)) break;
marchCount+= 1.0;
}
}
else
{
t = maxDepth + 1.0;
distAndMat.x = 1000000.0;
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
vec3 sunDir = normalize(vec3(3.93, 10.82, -1.5));
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
//if (abs(distAndMat.x) < 0.75)
if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(0.005, 0, 0);
vec3 normalU = vec3(distAndMat.x - DistanceToObject(pos - smallVec.xyy).x,
distAndMat.x - DistanceToObject(pos - smallVec.yxy).x,
distAndMat.x - DistanceToObject(pos - smallVec.yyx).x);
vec3 normal = normalize(normalU);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff
float ambientS = 1.0;
ambientS *= saturate(DistanceToObject(pos + normal * 0.1).x*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2).x*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4).x*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8).x*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6).x*1.25*0.5);
ambient *= saturate(DistanceToObject(pos + normal * 3.2).x*1.25*0.25);
ambient *= saturate(DistanceToObject(pos + normal * 6.4).x*1.25*0.125);
ambient = max(0.035, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// calculate the reflection vector for highlights
vec3 ref = reflect(rayVec, normal);
ref = normalize(ref);
// Trace a ray for the reflection
float sunShadow = 1.0;
float iter = 0.1;
vec3 nudgePos = pos + normal*0.02; // don't start tracing too close or inside the object
for (int i = 0; i < 40; i++)
{
float tempDist = DistanceToObject(nudgePos + ref * iter).x;
sunShadow *= saturate(tempDist*50.0);
if (tempDist <= 0.0) break;
//iter *= 1.5; // constant is more reliable than distance-based
iter += max(0.00, tempDist)*1.0;
if (iter > 4.2) break;
}
sunShadow = saturate(sunShadow);
// ------ Calculate texture color ------
vec3 texColor;
texColor = vec3(1.0);// vec3(0.65, 0.5, 0.4)*0.1;
texColor = vec3(0.85, 0.945 - distAndMat.y * 0.15, 0.93 + distAndMat.y * 0.35)*0.951;
if (distAndMat.y == 6.0) texColor = vec3(0.91, 0.1, 0.41)*10.5;
//texColor *= mix(vec3(0.3), vec3(1.0), tex3d(pos*0.5, normal).xxx);
texColor = max(texColor, vec3(0.0));
texColor *= 0.25;
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(0.0);// sunCol * saturate(dot(sunDir, normal)) * sunShadow*14.0;
// sky color, hemisphere light equation approximation, ambient occlusion
lightColor += vec3(0.1,0.35,0.95) * (normal.y * 0.5 + 0.5) * ambient * 0.2;
// ground color - another hemisphere light
lightColor += vec3(1.0) * ((-normal.y) * 0.5 + 0.5) * ambient * 0.2;
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
//if (distAndMat.y == ceil(mod(localTime, 4.0))) finalColor += vec3(0.0, 0.41, 0.72)*0.925;
// reflection environment map - this is most of the light
vec3 refColor = GetEnvColor2(ref, sunDir)*sunShadow;
finalColor += refColor * 0.35 * ambient;// * sunCol * sunShadow * 9.0 * texColor.g;
// fog
finalColor = mix(vec3(1.0, 0.41, 0.41) + vec3(1.0), finalColor, exp(-t*0.0007));
// visualize length of gradient of distance field to check distance field correctness
//finalColor = vec3(0.5) * (length(normalU) / smallVec.x);
}
else
{
finalColor = GetEnvColor2(rayVec, sunDir);// + vec3(0.1, 0.1, 0.1);
}
//finalColor += marchCount * vec3(1.0, 0.3, 0.91) * 0.001;
// vignette?
//finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
//finalColor *= 1.95;
// output the final color with sqrt for "gamma correction"
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
2998,
3034,
3075,
3075,
3168
] | [
[
856,
856,
879,
879,
908
],
[
909,
909,
932,
932,
961
],
[
962,
962,
987,
987,
1016
],
[
1018,
1018,
1051,
1051,
1168
],
[
1169,
1169,
1202,
1202,
1318
],
[
1319,
1319,
1352,
1352,
1469
],
[
1619,
1752,
1797,
1910,
2596
],
[
2998,
3034,
3075,
3075,
3168
],
[
3170,
3170,
3199,
3199,
3243
],
[
3408,
3408,
3459,
3459,
5710
],
[
5712,
5712,
5743,
5743,
5819
],
[
5821,
5860,
5952,
5952,
6182
],
[
6184,
6184,
6241,
6241,
13613
]
] | // polynomial smooth min (k = 0.1);
| float smin( float a, float b, float k )
{ |
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
} | // polynomial smooth min (k = 0.1);
float smin( float a, float b, float k )
{ | 176 | 382 |
XljGDz | otaviogood | 2015-04-07T03:58:40 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^This means do anything you want with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// Number of times the fractal repeats
#define RECURSION_LEVELS 4
// Animation splits the sphere in different directions
// This ended up running a significantly slower fps and not looking very different. :(
//#define SPLIT_ANIM
float localTime = 0.0;
float marchCount;
float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
/*vec3 GetEnvColor(vec3 rayDir, vec3 sunDir)
{
vec3 tex = texture(iChannel0, rayDir).xyz;
tex = tex * tex; // gamma correct
return tex;
}*/
// This is a procedural environment map with a giant overhead softbox,
// 4 lights in a horizontal circle, and a bottom-to-top fade.
vec3 GetEnvColor2(vec3 rayDir, vec3 sunDir)
{
// fade bottom to top so it looks like the softbox is casting light on a floor
// and it's bouncing back
vec3 final = vec3(1.0) * dot(-rayDir, sunDir) * 0.5 + 0.5;
final *= 0.125;
// overhead softbox, stretched to a rectangle
if ((rayDir.y > abs(rayDir.x)*1.0) && (rayDir.y > abs(rayDir.z*0.25))) final = vec3(2.0)*rayDir.y;
// fade the softbox at the edges with a rounded rectangle.
float roundBox = length(max(abs(rayDir.xz/max(0.0,rayDir.y))-vec2(0.9, 4.0),0.0))-0.1;
final += vec3(0.8)* pow(saturate(1.0 - roundBox*0.5), 6.0);
// purple lights from side
final += vec3(8.0,6.0,7.0) * saturate(0.001/(1.0 - abs(rayDir.x)));
// yellow lights from side
final += vec3(8.0,7.0,6.0) * saturate(0.001/(1.0 - abs(rayDir.z)));
return vec3(final);
}
/*vec3 GetEnvColorReflection(vec3 rayDir, vec3 sunDir, float ambient)
{
vec3 tex = texture(iChannel0, rayDir).xyz;
tex = tex * tex;
vec3 texBack = texture(iChannel0, rayDir).xyz;
vec3 texDark = pow(texBack, vec3(50.0)).zzz; // fake hdr texture
texBack += texDark*0.5 * ambient;
return texBack*texBack*texBack;
}*/
vec3 camPos = vec3(0.0), camFacing;
vec3 camLookat=vec3(0,0.0,0);
// polynomial smooth min (k = 0.1);
float smin( float a, float b, float k )
{
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
vec2 matMin(vec2 a, vec2 b)
{
if (a.x < b.x) return a;
else return b;
}
float spinTime;
vec3 diagN = normalize(vec3(-1.0));
float cut = 0.77;
float inner = 0.333;
float outness = 1.414;
float finWidth;
float teeth;
float globalTeeth;
vec2 sphereIter(vec3 p, float radius, float subA)
{
finWidth = 0.1;
teeth = globalTeeth;
float blender = 0.25;
vec2 final = vec2(1000000.0, 0.0);
for (int i = 0; i < RECURSION_LEVELS; i++)
{
#ifdef SPLIT_ANIM
// rotate top and bottom of sphere opposite directions
p = RotateY(p, spinTime*sign(p.y)*0.05/blender);
#endif
// main sphere
float d = length(p) - radius*outness;
#ifdef SPLIT_ANIM
// subtract out disc at the place where rotation happens so we don't have artifacts
d = max(d, -(max(length(p) - radius*outness + 0.1, abs(p.y) - finWidth*0.25)));
#endif
// calc new position at 8 vertices of cube, scaled
vec3 corners = abs(p) + diagN * radius;
float lenCorners = length(corners);
// subtract out main sphere hole, mirrored on all axises
float subtracter = lenCorners - radius * subA;
// make mirrored fins that go through all vertices of the cube
vec3 ap = abs(-p) * 0.7071; // 1/sqrt(2) to keep distance field normalized
subtracter = max(subtracter, -(abs(ap.x-ap.y) - finWidth));
subtracter = max(subtracter, -(abs(ap.y-ap.z) - finWidth));
subtracter = max(subtracter, -(abs(ap.z-ap.x) - finWidth));
// subtract sphere from fins so they don't intersect the inner spheres.
// also animate them so they are like teeth
subtracter = min(subtracter, lenCorners - radius * subA + teeth);
// smoothly subtract out that whole complex shape
d = -smin(-d, subtracter, blender);
//vec2 sphereDist = sphereB(abs(p) + diagN * radius, radius * inner, cut); // recurse
// do a material-min with the last iteration
final = matMin(final, vec2(d, float(i)));
#ifndef SPLIT_ANIM
corners = RotateY(corners, spinTime*0.25/blender);
#endif
// Simple rotate 90 degrees on X axis to keep things fresh
p = vec3(corners.x, corners.z, -corners.y);
// Scale things for the next iteration / recursion-like-thing
radius *= inner;
teeth *= inner;
finWidth *= inner;
blender *= inner;
}
// Bring in the final smallest-sized sphere
float d = length(p) - radius*outness;
final = matMin(final, vec2(d, 6.0));
return final;
}
vec2 DistanceToObject(vec3 p)
{
vec2 distMat = sphereIter(p, 5.2 / outness, cut);
return distMat;
}
// dirVec MUST BE NORMALIZED FIRST!!!!
float SphereIntersect(vec3 pos, vec3 dirVecPLZNormalizeMeFirst, vec3 spherePos, float rad)
{
vec3 radialVec = pos - spherePos;
float b = dot(radialVec, dirVecPLZNormalizeMeFirst);
float c = dot(radialVec, radialVec) - rad * rad;
float h = b * b - c;
if (h < 0.0) return -1.0;
return -b - sqrt(h);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
localTime = iTime - 0.0;
// ---------------- First, set up the camera rays for ray marching ----------------
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
float zoom = 1.7;
uv /= zoom;
// Camera up vector.
vec3 camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0,0.0,0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0-0.7 + localTime*3.1415 * 0.0625*0.666;
float my=-iMouse.y/iResolution.y*10.0 - sin(localTime * 0.31)*0.5;//*PI/2.01;
camPos += vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*(12.2);
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 rayVec = normalize(worldPix - camPos);
// ----------------------------------- Animate ------------------------------------
localTime = iTime*0.5;
// This is a wave function like a triangle wave, but with flat tops and bottoms.
// period is 1.0
float rampStep = min(3.0,max(1.0, abs((fract(localTime)-0.5)*1.0)*8.0))*0.5-0.5;
rampStep = smoothstep(0.0, 1.0, rampStep);
// lopsided triangle wave - goes up for 3 time units, down for 1.
float step31 = (max(0.0, (fract(localTime+0.125)-0.25)) - min(0.0,(fract(localTime+0.125)-0.25))*3.0)*0.333;
spinTime = step31 + localTime;
//globalTeeth = 0.0 + max(0.0, sin(localTime*3.0))*0.9;
globalTeeth = rampStep*0.99;
cut = max(0.48, min(0.77, localTime));
// --------------------------------------------------------------------------------
vec2 distAndMat = vec2(0.5, 0.0);
float t = 0.0;
//float inc = 0.02;
float maxDepth = 24.0;
vec3 pos = vec3(0,0,0);
marchCount = 0.0;
// intersect with sphere first as optimization so we don't ray march more than is needed.
float hit = SphereIntersect(camPos, rayVec, vec3(0.0), 5.6);
if (hit >= 0.0)
{
t = hit;
// ray marching time
for (int i = 0; i < 290; i++) // This is the count of the max times the ray actually marches.
{
pos = camPos + rayVec * t;
// *******************************************************
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry.
// *******************************************************
distAndMat = DistanceToObject(pos);
// adjust by constant because deformations mess up distance function.
t += distAndMat.x * 0.7;
//if (t > maxDepth) break;
if ((t > maxDepth) || (abs(distAndMat.x) < 0.0025)) break;
marchCount+= 1.0;
}
}
else
{
t = maxDepth + 1.0;
distAndMat.x = 1000000.0;
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
vec3 sunDir = normalize(vec3(3.93, 10.82, -1.5));
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
//if (abs(distAndMat.x) < 0.75)
if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(0.005, 0, 0);
vec3 normalU = vec3(distAndMat.x - DistanceToObject(pos - smallVec.xyy).x,
distAndMat.x - DistanceToObject(pos - smallVec.yxy).x,
distAndMat.x - DistanceToObject(pos - smallVec.yyx).x);
vec3 normal = normalize(normalU);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff
float ambientS = 1.0;
ambientS *= saturate(DistanceToObject(pos + normal * 0.1).x*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2).x*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4).x*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8).x*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6).x*1.25*0.5);
ambient *= saturate(DistanceToObject(pos + normal * 3.2).x*1.25*0.25);
ambient *= saturate(DistanceToObject(pos + normal * 6.4).x*1.25*0.125);
ambient = max(0.035, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// calculate the reflection vector for highlights
vec3 ref = reflect(rayVec, normal);
ref = normalize(ref);
// Trace a ray for the reflection
float sunShadow = 1.0;
float iter = 0.1;
vec3 nudgePos = pos + normal*0.02; // don't start tracing too close or inside the object
for (int i = 0; i < 40; i++)
{
float tempDist = DistanceToObject(nudgePos + ref * iter).x;
sunShadow *= saturate(tempDist*50.0);
if (tempDist <= 0.0) break;
//iter *= 1.5; // constant is more reliable than distance-based
iter += max(0.00, tempDist)*1.0;
if (iter > 4.2) break;
}
sunShadow = saturate(sunShadow);
// ------ Calculate texture color ------
vec3 texColor;
texColor = vec3(1.0);// vec3(0.65, 0.5, 0.4)*0.1;
texColor = vec3(0.85, 0.945 - distAndMat.y * 0.15, 0.93 + distAndMat.y * 0.35)*0.951;
if (distAndMat.y == 6.0) texColor = vec3(0.91, 0.1, 0.41)*10.5;
//texColor *= mix(vec3(0.3), vec3(1.0), tex3d(pos*0.5, normal).xxx);
texColor = max(texColor, vec3(0.0));
texColor *= 0.25;
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(0.0);// sunCol * saturate(dot(sunDir, normal)) * sunShadow*14.0;
// sky color, hemisphere light equation approximation, ambient occlusion
lightColor += vec3(0.1,0.35,0.95) * (normal.y * 0.5 + 0.5) * ambient * 0.2;
// ground color - another hemisphere light
lightColor += vec3(1.0) * ((-normal.y) * 0.5 + 0.5) * ambient * 0.2;
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
//if (distAndMat.y == ceil(mod(localTime, 4.0))) finalColor += vec3(0.0, 0.41, 0.72)*0.925;
// reflection environment map - this is most of the light
vec3 refColor = GetEnvColor2(ref, sunDir)*sunShadow;
finalColor += refColor * 0.35 * ambient;// * sunCol * sunShadow * 9.0 * texColor.g;
// fog
finalColor = mix(vec3(1.0, 0.41, 0.41) + vec3(1.0), finalColor, exp(-t*0.0007));
// visualize length of gradient of distance field to check distance field correctness
//finalColor = vec3(0.5) * (length(normalU) / smallVec.x);
}
else
{
finalColor = GetEnvColor2(rayVec, sunDir);// + vec3(0.1, 0.1, 0.1);
}
//finalColor += marchCount * vec3(1.0, 0.3, 0.91) * 0.001;
// vignette?
//finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
//finalColor *= 1.95;
// output the final color with sqrt for "gamma correction"
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
5821,
5860,
5952,
5952,
6182
] | [
[
856,
856,
879,
879,
908
],
[
909,
909,
932,
932,
961
],
[
962,
962,
987,
987,
1016
],
[
1018,
1018,
1051,
1051,
1168
],
[
1169,
1169,
1202,
1202,
1318
],
[
1319,
1319,
1352,
1352,
1469
],
[
1619,
1752,
1797,
1910,
2596
],
[
2998,
3034,
3075,
3075,
3168
],
[
3170,
3170,
3199,
3199,
3243
],
[
3408,
3408,
3459,
3459,
5710
],
[
5712,
5712,
5743,
5743,
5819
],
[
5821,
5860,
5952,
5952,
6182
],
[
6184,
6184,
6241,
6241,
13613
]
] | // dirVec MUST BE NORMALIZED FIRST!!!!
| float SphereIntersect(vec3 pos, vec3 dirVecPLZNormalizeMeFirst, vec3 spherePos, float rad)
{ |
vec3 radialVec = pos - spherePos;
float b = dot(radialVec, dirVecPLZNormalizeMeFirst);
float c = dot(radialVec, radialVec) - rad * rad;
float h = b * b - c;
if (h < 0.0) return -1.0;
return -b - sqrt(h);
} | // dirVec MUST BE NORMALIZED FIRST!!!!
float SphereIntersect(vec3 pos, vec3 dirVecPLZNormalizeMeFirst, vec3 spherePos, float rad)
{ | 3 | 3 |
llS3zd | otaviogood | 2015-05-13T04:11:09 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^This means do anything you want with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
float localTime = 0.0;
float marchCount;
float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
/*vec3 GetEnvColor(vec3 rayDir, vec3 sunDir)
{
vec3 tex = texture(iChannel0, rayDir).xyz;
tex = tex * tex; // gamma correct
return tex;
}*/
// This is a procedural environment map with a giant overhead softbox,
// 4 lights in a horizontal circle, and a bottom-to-top fade.
vec3 GetEnvColor2(vec3 rayDir, vec3 sunDir)
{
// fade bottom to top so it looks like the softbox is casting light on a floor
// and it's bouncing back
vec3 final = vec3(1.0) * dot(-rayDir, sunDir) * 0.5 + 0.5;
final *= 0.125;
// overhead softbox, stretched to a rectangle
if ((rayDir.y > abs(rayDir.x)*1.0) && (rayDir.y > abs(rayDir.z*0.25))) final = vec3(2.0)*rayDir.y;
// fade the softbox at the edges with a rounded rectangle.
float roundBox = length(max(abs(rayDir.xz/max(0.0,rayDir.y))-vec2(0.9, 4.0),0.0))-0.1;
final += vec3(0.8)* pow(saturate(1.0 - roundBox*0.5), 6.0);
// purple lights from side
final += vec3(8.0,6.0,7.0) * saturate(0.001/(1.0 - abs(rayDir.x)));
// yellow lights from side
final += vec3(8.0,7.0,6.0) * saturate(0.001/(1.0 - abs(rayDir.z)));
return vec3(final);
}
/*vec3 GetEnvColorReflection(vec3 rayDir, vec3 sunDir, float ambient)
{
vec3 tex = texture(iChannel0, rayDir).xyz;
tex = tex * tex;
vec3 texBack = texture(iChannel0, rayDir).xyz;
vec3 texDark = pow(texBack, vec3(50.0)).zzz; // fake hdr texture
texBack += texDark*0.5 * ambient;
return texBack*texBack*texBack;
}*/
vec3 camPos = vec3(0.0), camFacing;
vec3 camLookat=vec3(0,0.0,0);
// polynomial smooth min (k = 0.1);
float smin( float a, float b, float k )
{
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
vec2 matMin(vec2 a, vec2 b)
{
if (a.x < b.x) return a;
else return b;
}
float spinTime;
const float thick = 0.85;
const float spacer = 0.01;
const float thickSpace = thick - spacer;
float Disc(vec3 p, float scale)
{
float len = length(p.xz);
// infinite cylinder
float dist = len - scale;
// cut out the inner disc
dist = max(dist, -(len - thick*scale));
//dist = max(dist, -(length(p.xz + vec2(thick*scale, 0.0)) - thick*scale*0.15));
// cut off half the disc because that looks cool maybe.
dist = max(dist, -p.z);
// make it flat, but with nice rounded edges so reflections look good. (slow)
dist = -smin(-dist, -(abs(p.y)-0.025), 0.015*scale);
//dist = max(dist, abs(p.y)-0.025);
return dist;
}
// Calculate the distance field that defines the object.
vec2 DistanceToObject(vec3 p)
{
float dist = 1000000.0;
float currentThick = 8.0;
float harmonicTime = spinTime*0.125*3.14159*4.0;
// make 15 discs inside each other
for (int i = 0; i < 15; i++)
{
dist = min(dist, Disc(p, currentThick));
p = RotateX(p, harmonicTime);
p = RotateZ(p, harmonicTime);
// scale down a level
currentThick *= thickSpace;
}
vec2 distMat = vec2(dist, 0.0);
// ball in center
distMat = matMin(distMat, vec2(length(p) - 0.45, 6.0));
return distMat;
}
// dirVec MUST BE NORMALIZED FIRST!!!!
float SphereIntersect(vec3 pos, vec3 dirVecPLZNormalizeMeFirst, vec3 spherePos, float rad)
{
vec3 radialVec = pos - spherePos;
float b = dot(radialVec, dirVecPLZNormalizeMeFirst);
float c = dot(radialVec, radialVec) - rad * rad;
float h = b * b - c;
if (h < 0.0) return -1.0;
return -b - sqrt(h);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
localTime = iTime - 0.0;
// ---------------- First, set up the camera rays for ray marching ----------------
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
float zoom = 1.7;
uv /= zoom;
// Camera up vector.
vec3 camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0,0.0,0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0-0.7 + localTime*3.1415 * 0.0625*0.666;
float my=-iMouse.y/iResolution.y*10.0 - sin(localTime * 0.31)*0.5;//*PI/2.01;
camPos += vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*(12.2);
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 rayVec = normalize(worldPix - camPos);
// ----------------------------------- Animate ------------------------------------
localTime = iTime*0.125;
// This is a wave function like a triangle wave, but with flat tops and bottoms.
// period is 1.0
float rampStep = min(3.0,max(1.0, abs((fract(localTime)-0.5)*1.0)*8.0))*0.5-0.5;
rampStep = smoothstep(0.0, 1.0, rampStep);
// lopsided triangle wave - goes up for 3 time units, down for 1.
float step31 = (max(0.0, (fract(localTime+0.125)-0.25)) - min(0.0,(fract(localTime+0.125)-0.25))*3.0)*0.333;
spinTime = step31 + localTime - 0.125;
// --------------------------------------------------------------------------------
vec2 distAndMat = vec2(0.5, 0.0);
float t = 0.0;
//float inc = 0.02;
float maxDepth = 21.0;
vec3 pos = vec3(0,0,0);
marchCount = 0.0;
// intersect with sphere first as optimization so we don't ray march more than is needed.
float hit = SphereIntersect(camPos, rayVec, vec3(0.0), 8.0);
if (hit >= 0.0)
{
t = hit;
// ray marching time
for (int i = 0; i < 120; i++) // This is the count of the max times the ray actually marches.
{
pos = camPos + rayVec * t;
// *******************************************************
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry.
// *******************************************************
distAndMat = DistanceToObject(pos);
// move along the ray
t += distAndMat.x;
if ((t > maxDepth) || (abs(distAndMat.x) < 0.0025)) break;
//marchCount+= 1.0;
}
}
else
{
t = maxDepth + 1.0;
distAndMat.x = 1000000.0;
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
vec3 sunDir = normalize(vec3(3.93, 10.82, -1.5));
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
//if (abs(distAndMat.x) < 0.75)
if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(0.005, 0, 0);
vec3 normalU = vec3(distAndMat.x - DistanceToObject(pos - smallVec.xyy).x,
distAndMat.x - DistanceToObject(pos - smallVec.yxy).x,
distAndMat.x - DistanceToObject(pos - smallVec.yyx).x);
vec3 normal = normalize(normalU);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff
float ambientS = 1.0;
ambientS *= saturate(DistanceToObject(pos + normal * 0.1).x*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2).x*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4).x*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8).x*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6).x*1.25*0.5);
ambient *= saturate(DistanceToObject(pos + normal * 3.2).x*1.25*0.25);
ambient *= saturate(DistanceToObject(pos + normal * 6.4).x*1.25*0.125);
ambient = max(0.035, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// calculate the reflection vector for highlights
vec3 ref = reflect(rayVec, normal);
ref = normalize(ref);
// Trace a ray for the reflection
float sunShadow = 1.0;
float iter = 0.1;
vec3 nudgePos = pos + ref*0.3;// normal*0.02; // don't start tracing too close or inside the object
for (int i = 0; i < 40; i++)
{
float tempDist = DistanceToObject(nudgePos + ref * iter).x;
sunShadow *= saturate(tempDist*50.0);
if (tempDist <= 0.0) break;
//iter *= 1.5; // constant is more reliable than distance-based
iter += max(0.00, tempDist)*1.0;
if (iter > 9.0) break;
}
sunShadow = saturate(sunShadow);
// ------ Calculate texture color ------
vec3 texColor;
texColor = vec3(1.0);// vec3(0.65, 0.5, 0.4)*0.1;
texColor = vec3(0.85, 0.945 - distAndMat.y * 0.15, 0.93 + distAndMat.y * 0.35)*0.951;
if (distAndMat.y == 6.0) texColor = vec3(0.91, 0.1, 0.41)*10.5;
//texColor *= mix(vec3(0.3), vec3(1.0), tex3d(pos*0.5, normal).xxx);
texColor = max(texColor, vec3(0.0));
texColor *= 0.25;
//texColor += vec3(1.0, 0.0, 0.0) * 8.0/length(pos);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(0.0);// sunCol * saturate(dot(sunDir, normal)) * sunShadow*14.0;
// sky color, hemisphere light equation approximation, ambient occlusion
lightColor += vec3(0.1,0.35,0.95) * (normal.y * 0.5 + 0.5) * ambient * 0.2;
// ground color - another hemisphere light
lightColor += vec3(1.0) * ((-normal.y) * 0.5 + 0.5) * ambient * 0.2;
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// if (distAndMat.y == 6.0) finalColor += vec3(0.91, 0.032, 0.01)*0.2;
//if (distAndMat.y == ceil(mod(localTime, 4.0))) finalColor += vec3(0.0, 0.41, 0.72)*0.925;
// reflection environment map - this is most of the light
vec3 refColor = GetEnvColor2(ref, sunDir)*sunShadow;// * (length(normalU)/smallVec.x-0.875)*8.0;
finalColor += refColor * 0.35 * ambient;// * sunCol * sunShadow * 9.0 * texColor.g;
// fog
finalColor = mix(vec3(1.0, 0.41, 0.41) + vec3(1.0), finalColor, exp(-t*0.0007));
// visualize length of gradient of distance field to check distance field correctness
//finalColor = vec3(0.5) * (length(normalU) / smallVec.x);
}
else
{
finalColor = GetEnvColor2(rayVec, sunDir);// + vec3(0.1, 0.1, 0.1);
}
//finalColor += marchCount * vec3(1.0, 0.3, 0.91) * 0.001;
// vignette?
//finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
//finalColor *= 1.2;
// output the final color with sqrt for "gamma correction"
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
3691,
3748,
3779,
3779,
4305
] | [
[
626,
626,
649,
649,
678
],
[
679,
679,
702,
702,
731
],
[
732,
732,
757,
757,
786
],
[
788,
788,
821,
821,
938
],
[
939,
939,
972,
972,
1088
],
[
1089,
1089,
1122,
1122,
1239
],
[
1389,
1522,
1567,
1680,
2366
],
[
2768,
2804,
2845,
2845,
2938
],
[
2940,
2940,
2969,
2969,
3013
],
[
3126,
3126,
3159,
3159,
3689
],
[
3691,
3748,
3779,
3779,
4305
],
[
4307,
4346,
4438,
4438,
4668
],
[
4670,
4670,
4727,
4727,
12075
]
] | // Calculate the distance field that defines the object.
| vec2 DistanceToObject(vec3 p)
{ |
float dist = 1000000.0;
float currentThick = 8.0;
float harmonicTime = spinTime*0.125*3.14159*4.0;
// make 15 discs inside each other
for (int i = 0; i < 15; i++)
{
dist = min(dist, Disc(p, currentThick));
p = RotateX(p, harmonicTime);
p = RotateZ(p, harmonicTime);
// scale down a level
currentThick *= thickSpace;
}
vec2 distMat = vec2(dist, 0.0);
// ball in center
distMat = matMin(distMat, vec2(length(p) - 0.45, 6.0));
return distMat;
} | // Calculate the distance field that defines the object.
vec2 DistanceToObject(vec3 p)
{ | 1 | 8 |
XlfXR4 | iq | 2015-06-18T20:06:02 | // The MIT License
// Copyright © 2015 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// https://www.youtube.com/c/InigoQuilez
// https://iquilezles.org/
//
// Computes the curvature of a parametric curve f(x) as
//
// c(f) = |f'|^3 / | f' x f''|
//
// More info here: https://en.wikipedia.org/wiki/Curvature
//
//----------------------------------------
vec3 a, b, c, m, n;
// curve
vec3 mapD0(float t)
{
return 0.25 + a*cos(t+m)*(b+c*cos(t*7.0+n));
}
// curve derivative (velocity)
vec3 mapD1(float t)
{
return -7.0*a*c*cos(t+m)*sin(7.0*t+n) - a*sin(t+m)*(b+c*cos(7.0*t+n));
}
// curve second derivative (acceleration)
vec3 mapD2(float t)
{
return 14.0*a*c*sin(t+m)*sin(7.0*t+n) - a*cos(t+m)*(b+c*cos(7.0*t+n)) - 49.0*a*c*cos(t+m)*cos(7.0*t+n);
}
//----------------------------------------
float curvature( float t )
{
vec3 r1 = mapD1(t); // first derivative
vec3 r2 = mapD2(t); // second derivative
return pow(length(r1),3.0) / length(cross(r1,r2));
}
//-----------------------------------------
// unsigned squared distance between point and segment
vec2 usqdPointSegment( in vec3 p, in vec3 a, in vec3 b )
{
vec3 pa = p - a;
vec3 ba = b - a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
vec3 q = pa - ba*h;
return vec2( dot(q,q), h );
}
// unsigned squared distance between ray and segment
vec2 usqdLineSegment( vec3 a, vec3 b, vec3 o, vec3 d )
{
#if 1
vec3 oa = a-o;
vec3 ob = b-o;
vec3 va = oa-d*dot(oa,d);
vec3 vb = ob-d*dot(ob,d);
vec3 ba = va-vb;
float h = clamp( dot(va,ba)/dot(ba,ba), 0.0, 1.0 );
vec3 q = va - ba*h;
return vec2( dot(q,q), h );
#else
return usqdPointSegment( vec3(0.0), o+d*dot(a-o,d)-a, o+d*dot(b-o,d)-b );
#endif
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
a = vec3(1.85,1.25,1.85) + 0.1*cos(5.0+0.7*iTime + vec3(0.5,1.0,2.0) );
b = vec3(0.60,0.60,0.60) + 0.1*cos(4.0+0.5*iTime + vec3(2.5,5.0,3.0) );
c = vec3(0.40,0.40,0.40) + 0.1*cos(1.0+0.3*iTime + vec3(6.0,2.0,4.2) );
m = cos( 0.11*iTime + vec3(2.0,0.0,5.0) );
n = cos( 0.17*iTime + vec3(3.0,1.0,4.0) );
vec2 p = (2.0*fragCoord-iResolution.xy)/iResolution.y;
vec3 ro = vec3( 0.0, 0.0, 4.0 );
vec3 rd = normalize( vec3(p.xy, -2.0) );
vec3 col = vec3(0.0);
vec3 gp = vec3(0.0);
float pt = (-1.0-ro.y)/rd.y;
vec3 gc = vec3(0.0);
if( pt>0.0 )
{
gp = ro + pt*rd;
gc = vec3(1.0) * (0.2 + 0.1*smoothstep(-0.01,0.01,sin(4.0*gp.x)*sin(4.0*gp.z)));
col = 0.3*gc*exp(-0.05*pt);
}
const int kNum = 150;
float dt = 6.2831/float(kNum);
float t = 0.0;
vec3 xb = mapD0(t); t += dt;
for( int i=0; i<kNum; i++ )
{
vec3 xc = mapD0(t);
xc.y = max(-1.0,xc.y); // clip to ground
vec2 ds = usqdLineSegment( xb, xc, ro, rd );
// compute curvature
float h = t - dt + dt*ds.y;
float c = curvature( h );
vec3 cc = clamp( 0.25 + 0.75*cos( -clamp(3.0*c,0.0,2.0) + 1.0 + vec3(0.0,1.5,2.0) ), 0.0, 1.0 );
col += 1.0*cc*exp2( -800.0*ds.x );
col += 0.1*cc*exp2( -40.0*ds.x );
// light ground
if( pt > 0.0 )
{
vec2 sd = usqdPointSegment( gp, xb, xc );
col += gc*0.8*cc*exp(-2.0*sd.x)*exp( -0.05*pt );
}
xb = xc; t += dt;
}
fragColor = vec4( col, 1.0 );
} | mit | [
1373,
1382,
1403,
1403,
1454
] | [
[
1373,
1382,
1403,
1403,
1454
],
[
1455,
1486,
1507,
1507,
1584
],
[
1585,
1627,
1648,
1648,
1758
],
[
1804,
1804,
1832,
1832,
1978
],
[
2025,
2080,
2138,
2138,
2282
],
[
2285,
2338,
2394,
2394,
2724
],
[
2726,
2726,
2783,
2783,
4394
]
] | // curve
| vec3 mapD0(float t)
{ |
return 0.25 + a*cos(t+m)*(b+c*cos(t*7.0+n));
} | // curve
vec3 mapD0(float t)
{ | 1 | 1 |
XlfXR4 | iq | 2015-06-18T20:06:02 | // The MIT License
// Copyright © 2015 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// https://www.youtube.com/c/InigoQuilez
// https://iquilezles.org/
//
// Computes the curvature of a parametric curve f(x) as
//
// c(f) = |f'|^3 / | f' x f''|
//
// More info here: https://en.wikipedia.org/wiki/Curvature
//
//----------------------------------------
vec3 a, b, c, m, n;
// curve
vec3 mapD0(float t)
{
return 0.25 + a*cos(t+m)*(b+c*cos(t*7.0+n));
}
// curve derivative (velocity)
vec3 mapD1(float t)
{
return -7.0*a*c*cos(t+m)*sin(7.0*t+n) - a*sin(t+m)*(b+c*cos(7.0*t+n));
}
// curve second derivative (acceleration)
vec3 mapD2(float t)
{
return 14.0*a*c*sin(t+m)*sin(7.0*t+n) - a*cos(t+m)*(b+c*cos(7.0*t+n)) - 49.0*a*c*cos(t+m)*cos(7.0*t+n);
}
//----------------------------------------
float curvature( float t )
{
vec3 r1 = mapD1(t); // first derivative
vec3 r2 = mapD2(t); // second derivative
return pow(length(r1),3.0) / length(cross(r1,r2));
}
//-----------------------------------------
// unsigned squared distance between point and segment
vec2 usqdPointSegment( in vec3 p, in vec3 a, in vec3 b )
{
vec3 pa = p - a;
vec3 ba = b - a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
vec3 q = pa - ba*h;
return vec2( dot(q,q), h );
}
// unsigned squared distance between ray and segment
vec2 usqdLineSegment( vec3 a, vec3 b, vec3 o, vec3 d )
{
#if 1
vec3 oa = a-o;
vec3 ob = b-o;
vec3 va = oa-d*dot(oa,d);
vec3 vb = ob-d*dot(ob,d);
vec3 ba = va-vb;
float h = clamp( dot(va,ba)/dot(ba,ba), 0.0, 1.0 );
vec3 q = va - ba*h;
return vec2( dot(q,q), h );
#else
return usqdPointSegment( vec3(0.0), o+d*dot(a-o,d)-a, o+d*dot(b-o,d)-b );
#endif
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
a = vec3(1.85,1.25,1.85) + 0.1*cos(5.0+0.7*iTime + vec3(0.5,1.0,2.0) );
b = vec3(0.60,0.60,0.60) + 0.1*cos(4.0+0.5*iTime + vec3(2.5,5.0,3.0) );
c = vec3(0.40,0.40,0.40) + 0.1*cos(1.0+0.3*iTime + vec3(6.0,2.0,4.2) );
m = cos( 0.11*iTime + vec3(2.0,0.0,5.0) );
n = cos( 0.17*iTime + vec3(3.0,1.0,4.0) );
vec2 p = (2.0*fragCoord-iResolution.xy)/iResolution.y;
vec3 ro = vec3( 0.0, 0.0, 4.0 );
vec3 rd = normalize( vec3(p.xy, -2.0) );
vec3 col = vec3(0.0);
vec3 gp = vec3(0.0);
float pt = (-1.0-ro.y)/rd.y;
vec3 gc = vec3(0.0);
if( pt>0.0 )
{
gp = ro + pt*rd;
gc = vec3(1.0) * (0.2 + 0.1*smoothstep(-0.01,0.01,sin(4.0*gp.x)*sin(4.0*gp.z)));
col = 0.3*gc*exp(-0.05*pt);
}
const int kNum = 150;
float dt = 6.2831/float(kNum);
float t = 0.0;
vec3 xb = mapD0(t); t += dt;
for( int i=0; i<kNum; i++ )
{
vec3 xc = mapD0(t);
xc.y = max(-1.0,xc.y); // clip to ground
vec2 ds = usqdLineSegment( xb, xc, ro, rd );
// compute curvature
float h = t - dt + dt*ds.y;
float c = curvature( h );
vec3 cc = clamp( 0.25 + 0.75*cos( -clamp(3.0*c,0.0,2.0) + 1.0 + vec3(0.0,1.5,2.0) ), 0.0, 1.0 );
col += 1.0*cc*exp2( -800.0*ds.x );
col += 0.1*cc*exp2( -40.0*ds.x );
// light ground
if( pt > 0.0 )
{
vec2 sd = usqdPointSegment( gp, xb, xc );
col += gc*0.8*cc*exp(-2.0*sd.x)*exp( -0.05*pt );
}
xb = xc; t += dt;
}
fragColor = vec4( col, 1.0 );
} | mit | [
1455,
1486,
1507,
1507,
1584
] | [
[
1373,
1382,
1403,
1403,
1454
],
[
1455,
1486,
1507,
1507,
1584
],
[
1585,
1627,
1648,
1648,
1758
],
[
1804,
1804,
1832,
1832,
1978
],
[
2025,
2080,
2138,
2138,
2282
],
[
2285,
2338,
2394,
2394,
2724
],
[
2726,
2726,
2783,
2783,
4394
]
] | // curve derivative (velocity)
| vec3 mapD1(float t)
{ |
return -7.0*a*c*cos(t+m)*sin(7.0*t+n) - a*sin(t+m)*(b+c*cos(7.0*t+n));
} | // curve derivative (velocity)
vec3 mapD1(float t)
{ | 1 | 1 |
XlfXR4 | iq | 2015-06-18T20:06:02 | // The MIT License
// Copyright © 2015 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// https://www.youtube.com/c/InigoQuilez
// https://iquilezles.org/
//
// Computes the curvature of a parametric curve f(x) as
//
// c(f) = |f'|^3 / | f' x f''|
//
// More info here: https://en.wikipedia.org/wiki/Curvature
//
//----------------------------------------
vec3 a, b, c, m, n;
// curve
vec3 mapD0(float t)
{
return 0.25 + a*cos(t+m)*(b+c*cos(t*7.0+n));
}
// curve derivative (velocity)
vec3 mapD1(float t)
{
return -7.0*a*c*cos(t+m)*sin(7.0*t+n) - a*sin(t+m)*(b+c*cos(7.0*t+n));
}
// curve second derivative (acceleration)
vec3 mapD2(float t)
{
return 14.0*a*c*sin(t+m)*sin(7.0*t+n) - a*cos(t+m)*(b+c*cos(7.0*t+n)) - 49.0*a*c*cos(t+m)*cos(7.0*t+n);
}
//----------------------------------------
float curvature( float t )
{
vec3 r1 = mapD1(t); // first derivative
vec3 r2 = mapD2(t); // second derivative
return pow(length(r1),3.0) / length(cross(r1,r2));
}
//-----------------------------------------
// unsigned squared distance between point and segment
vec2 usqdPointSegment( in vec3 p, in vec3 a, in vec3 b )
{
vec3 pa = p - a;
vec3 ba = b - a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
vec3 q = pa - ba*h;
return vec2( dot(q,q), h );
}
// unsigned squared distance between ray and segment
vec2 usqdLineSegment( vec3 a, vec3 b, vec3 o, vec3 d )
{
#if 1
vec3 oa = a-o;
vec3 ob = b-o;
vec3 va = oa-d*dot(oa,d);
vec3 vb = ob-d*dot(ob,d);
vec3 ba = va-vb;
float h = clamp( dot(va,ba)/dot(ba,ba), 0.0, 1.0 );
vec3 q = va - ba*h;
return vec2( dot(q,q), h );
#else
return usqdPointSegment( vec3(0.0), o+d*dot(a-o,d)-a, o+d*dot(b-o,d)-b );
#endif
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
a = vec3(1.85,1.25,1.85) + 0.1*cos(5.0+0.7*iTime + vec3(0.5,1.0,2.0) );
b = vec3(0.60,0.60,0.60) + 0.1*cos(4.0+0.5*iTime + vec3(2.5,5.0,3.0) );
c = vec3(0.40,0.40,0.40) + 0.1*cos(1.0+0.3*iTime + vec3(6.0,2.0,4.2) );
m = cos( 0.11*iTime + vec3(2.0,0.0,5.0) );
n = cos( 0.17*iTime + vec3(3.0,1.0,4.0) );
vec2 p = (2.0*fragCoord-iResolution.xy)/iResolution.y;
vec3 ro = vec3( 0.0, 0.0, 4.0 );
vec3 rd = normalize( vec3(p.xy, -2.0) );
vec3 col = vec3(0.0);
vec3 gp = vec3(0.0);
float pt = (-1.0-ro.y)/rd.y;
vec3 gc = vec3(0.0);
if( pt>0.0 )
{
gp = ro + pt*rd;
gc = vec3(1.0) * (0.2 + 0.1*smoothstep(-0.01,0.01,sin(4.0*gp.x)*sin(4.0*gp.z)));
col = 0.3*gc*exp(-0.05*pt);
}
const int kNum = 150;
float dt = 6.2831/float(kNum);
float t = 0.0;
vec3 xb = mapD0(t); t += dt;
for( int i=0; i<kNum; i++ )
{
vec3 xc = mapD0(t);
xc.y = max(-1.0,xc.y); // clip to ground
vec2 ds = usqdLineSegment( xb, xc, ro, rd );
// compute curvature
float h = t - dt + dt*ds.y;
float c = curvature( h );
vec3 cc = clamp( 0.25 + 0.75*cos( -clamp(3.0*c,0.0,2.0) + 1.0 + vec3(0.0,1.5,2.0) ), 0.0, 1.0 );
col += 1.0*cc*exp2( -800.0*ds.x );
col += 0.1*cc*exp2( -40.0*ds.x );
// light ground
if( pt > 0.0 )
{
vec2 sd = usqdPointSegment( gp, xb, xc );
col += gc*0.8*cc*exp(-2.0*sd.x)*exp( -0.05*pt );
}
xb = xc; t += dt;
}
fragColor = vec4( col, 1.0 );
} | mit | [
1585,
1627,
1648,
1648,
1758
] | [
[
1373,
1382,
1403,
1403,
1454
],
[
1455,
1486,
1507,
1507,
1584
],
[
1585,
1627,
1648,
1648,
1758
],
[
1804,
1804,
1832,
1832,
1978
],
[
2025,
2080,
2138,
2138,
2282
],
[
2285,
2338,
2394,
2394,
2724
],
[
2726,
2726,
2783,
2783,
4394
]
] | // curve second derivative (acceleration)
| vec3 mapD2(float t)
{ |
return 14.0*a*c*sin(t+m)*sin(7.0*t+n) - a*cos(t+m)*(b+c*cos(7.0*t+n)) - 49.0*a*c*cos(t+m)*cos(7.0*t+n);
} | // curve second derivative (acceleration)
vec3 mapD2(float t)
{ | 1 | 1 |
XlfXR4 | iq | 2015-06-18T20:06:02 | // The MIT License
// Copyright © 2015 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// https://www.youtube.com/c/InigoQuilez
// https://iquilezles.org/
//
// Computes the curvature of a parametric curve f(x) as
//
// c(f) = |f'|^3 / | f' x f''|
//
// More info here: https://en.wikipedia.org/wiki/Curvature
//
//----------------------------------------
vec3 a, b, c, m, n;
// curve
vec3 mapD0(float t)
{
return 0.25 + a*cos(t+m)*(b+c*cos(t*7.0+n));
}
// curve derivative (velocity)
vec3 mapD1(float t)
{
return -7.0*a*c*cos(t+m)*sin(7.0*t+n) - a*sin(t+m)*(b+c*cos(7.0*t+n));
}
// curve second derivative (acceleration)
vec3 mapD2(float t)
{
return 14.0*a*c*sin(t+m)*sin(7.0*t+n) - a*cos(t+m)*(b+c*cos(7.0*t+n)) - 49.0*a*c*cos(t+m)*cos(7.0*t+n);
}
//----------------------------------------
float curvature( float t )
{
vec3 r1 = mapD1(t); // first derivative
vec3 r2 = mapD2(t); // second derivative
return pow(length(r1),3.0) / length(cross(r1,r2));
}
//-----------------------------------------
// unsigned squared distance between point and segment
vec2 usqdPointSegment( in vec3 p, in vec3 a, in vec3 b )
{
vec3 pa = p - a;
vec3 ba = b - a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
vec3 q = pa - ba*h;
return vec2( dot(q,q), h );
}
// unsigned squared distance between ray and segment
vec2 usqdLineSegment( vec3 a, vec3 b, vec3 o, vec3 d )
{
#if 1
vec3 oa = a-o;
vec3 ob = b-o;
vec3 va = oa-d*dot(oa,d);
vec3 vb = ob-d*dot(ob,d);
vec3 ba = va-vb;
float h = clamp( dot(va,ba)/dot(ba,ba), 0.0, 1.0 );
vec3 q = va - ba*h;
return vec2( dot(q,q), h );
#else
return usqdPointSegment( vec3(0.0), o+d*dot(a-o,d)-a, o+d*dot(b-o,d)-b );
#endif
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
a = vec3(1.85,1.25,1.85) + 0.1*cos(5.0+0.7*iTime + vec3(0.5,1.0,2.0) );
b = vec3(0.60,0.60,0.60) + 0.1*cos(4.0+0.5*iTime + vec3(2.5,5.0,3.0) );
c = vec3(0.40,0.40,0.40) + 0.1*cos(1.0+0.3*iTime + vec3(6.0,2.0,4.2) );
m = cos( 0.11*iTime + vec3(2.0,0.0,5.0) );
n = cos( 0.17*iTime + vec3(3.0,1.0,4.0) );
vec2 p = (2.0*fragCoord-iResolution.xy)/iResolution.y;
vec3 ro = vec3( 0.0, 0.0, 4.0 );
vec3 rd = normalize( vec3(p.xy, -2.0) );
vec3 col = vec3(0.0);
vec3 gp = vec3(0.0);
float pt = (-1.0-ro.y)/rd.y;
vec3 gc = vec3(0.0);
if( pt>0.0 )
{
gp = ro + pt*rd;
gc = vec3(1.0) * (0.2 + 0.1*smoothstep(-0.01,0.01,sin(4.0*gp.x)*sin(4.0*gp.z)));
col = 0.3*gc*exp(-0.05*pt);
}
const int kNum = 150;
float dt = 6.2831/float(kNum);
float t = 0.0;
vec3 xb = mapD0(t); t += dt;
for( int i=0; i<kNum; i++ )
{
vec3 xc = mapD0(t);
xc.y = max(-1.0,xc.y); // clip to ground
vec2 ds = usqdLineSegment( xb, xc, ro, rd );
// compute curvature
float h = t - dt + dt*ds.y;
float c = curvature( h );
vec3 cc = clamp( 0.25 + 0.75*cos( -clamp(3.0*c,0.0,2.0) + 1.0 + vec3(0.0,1.5,2.0) ), 0.0, 1.0 );
col += 1.0*cc*exp2( -800.0*ds.x );
col += 0.1*cc*exp2( -40.0*ds.x );
// light ground
if( pt > 0.0 )
{
vec2 sd = usqdPointSegment( gp, xb, xc );
col += gc*0.8*cc*exp(-2.0*sd.x)*exp( -0.05*pt );
}
xb = xc; t += dt;
}
fragColor = vec4( col, 1.0 );
} | mit | [
2025,
2080,
2138,
2138,
2282
] | [
[
1373,
1382,
1403,
1403,
1454
],
[
1455,
1486,
1507,
1507,
1584
],
[
1585,
1627,
1648,
1648,
1758
],
[
1804,
1804,
1832,
1832,
1978
],
[
2025,
2080,
2138,
2138,
2282
],
[
2285,
2338,
2394,
2394,
2724
],
[
2726,
2726,
2783,
2783,
4394
]
] | // unsigned squared distance between point and segment
| vec2 usqdPointSegment( in vec3 p, in vec3 a, in vec3 b )
{ |
vec3 pa = p - a;
vec3 ba = b - a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
vec3 q = pa - ba*h;
return vec2( dot(q,q), h );
} | // unsigned squared distance between point and segment
vec2 usqdPointSegment( in vec3 p, in vec3 a, in vec3 b )
{ | 1 | 1 |
XlfXR4 | iq | 2015-06-18T20:06:02 | // The MIT License
// Copyright © 2015 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// https://www.youtube.com/c/InigoQuilez
// https://iquilezles.org/
//
// Computes the curvature of a parametric curve f(x) as
//
// c(f) = |f'|^3 / | f' x f''|
//
// More info here: https://en.wikipedia.org/wiki/Curvature
//
//----------------------------------------
vec3 a, b, c, m, n;
// curve
vec3 mapD0(float t)
{
return 0.25 + a*cos(t+m)*(b+c*cos(t*7.0+n));
}
// curve derivative (velocity)
vec3 mapD1(float t)
{
return -7.0*a*c*cos(t+m)*sin(7.0*t+n) - a*sin(t+m)*(b+c*cos(7.0*t+n));
}
// curve second derivative (acceleration)
vec3 mapD2(float t)
{
return 14.0*a*c*sin(t+m)*sin(7.0*t+n) - a*cos(t+m)*(b+c*cos(7.0*t+n)) - 49.0*a*c*cos(t+m)*cos(7.0*t+n);
}
//----------------------------------------
float curvature( float t )
{
vec3 r1 = mapD1(t); // first derivative
vec3 r2 = mapD2(t); // second derivative
return pow(length(r1),3.0) / length(cross(r1,r2));
}
//-----------------------------------------
// unsigned squared distance between point and segment
vec2 usqdPointSegment( in vec3 p, in vec3 a, in vec3 b )
{
vec3 pa = p - a;
vec3 ba = b - a;
float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
vec3 q = pa - ba*h;
return vec2( dot(q,q), h );
}
// unsigned squared distance between ray and segment
vec2 usqdLineSegment( vec3 a, vec3 b, vec3 o, vec3 d )
{
#if 1
vec3 oa = a-o;
vec3 ob = b-o;
vec3 va = oa-d*dot(oa,d);
vec3 vb = ob-d*dot(ob,d);
vec3 ba = va-vb;
float h = clamp( dot(va,ba)/dot(ba,ba), 0.0, 1.0 );
vec3 q = va - ba*h;
return vec2( dot(q,q), h );
#else
return usqdPointSegment( vec3(0.0), o+d*dot(a-o,d)-a, o+d*dot(b-o,d)-b );
#endif
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
a = vec3(1.85,1.25,1.85) + 0.1*cos(5.0+0.7*iTime + vec3(0.5,1.0,2.0) );
b = vec3(0.60,0.60,0.60) + 0.1*cos(4.0+0.5*iTime + vec3(2.5,5.0,3.0) );
c = vec3(0.40,0.40,0.40) + 0.1*cos(1.0+0.3*iTime + vec3(6.0,2.0,4.2) );
m = cos( 0.11*iTime + vec3(2.0,0.0,5.0) );
n = cos( 0.17*iTime + vec3(3.0,1.0,4.0) );
vec2 p = (2.0*fragCoord-iResolution.xy)/iResolution.y;
vec3 ro = vec3( 0.0, 0.0, 4.0 );
vec3 rd = normalize( vec3(p.xy, -2.0) );
vec3 col = vec3(0.0);
vec3 gp = vec3(0.0);
float pt = (-1.0-ro.y)/rd.y;
vec3 gc = vec3(0.0);
if( pt>0.0 )
{
gp = ro + pt*rd;
gc = vec3(1.0) * (0.2 + 0.1*smoothstep(-0.01,0.01,sin(4.0*gp.x)*sin(4.0*gp.z)));
col = 0.3*gc*exp(-0.05*pt);
}
const int kNum = 150;
float dt = 6.2831/float(kNum);
float t = 0.0;
vec3 xb = mapD0(t); t += dt;
for( int i=0; i<kNum; i++ )
{
vec3 xc = mapD0(t);
xc.y = max(-1.0,xc.y); // clip to ground
vec2 ds = usqdLineSegment( xb, xc, ro, rd );
// compute curvature
float h = t - dt + dt*ds.y;
float c = curvature( h );
vec3 cc = clamp( 0.25 + 0.75*cos( -clamp(3.0*c,0.0,2.0) + 1.0 + vec3(0.0,1.5,2.0) ), 0.0, 1.0 );
col += 1.0*cc*exp2( -800.0*ds.x );
col += 0.1*cc*exp2( -40.0*ds.x );
// light ground
if( pt > 0.0 )
{
vec2 sd = usqdPointSegment( gp, xb, xc );
col += gc*0.8*cc*exp(-2.0*sd.x)*exp( -0.05*pt );
}
xb = xc; t += dt;
}
fragColor = vec4( col, 1.0 );
} | mit | [
2285,
2338,
2394,
2394,
2724
] | [
[
1373,
1382,
1403,
1403,
1454
],
[
1455,
1486,
1507,
1507,
1584
],
[
1585,
1627,
1648,
1648,
1758
],
[
1804,
1804,
1832,
1832,
1978
],
[
2025,
2080,
2138,
2138,
2282
],
[
2285,
2338,
2394,
2394,
2724
],
[
2726,
2726,
2783,
2783,
4394
]
] | // unsigned squared distance between ray and segment
| vec2 usqdLineSegment( vec3 a, vec3 b, vec3 o, vec3 d )
{ |
#if 1
vec3 oa = a-o;
vec3 ob = b-o;
vec3 va = oa-d*dot(oa,d);
vec3 vb = ob-d*dot(ob,d);
vec3 ba = va-vb;
float h = clamp( dot(va,ba)/dot(ba,ba), 0.0, 1.0 );
vec3 q = va - ba*h;
return vec2( dot(q,q), h );
#else
return usqdPointSegment( vec3(0.0), o+d*dot(a-o,d)-a, o+d*dot(b-o,d)-b );
#endif
} | // unsigned squared distance between ray and segment
vec2 usqdLineSegment( vec3 a, vec3 b, vec3 o, vec3 d )
{ | 1 | 1 |
4llXD7 | iq | 2015-07-18T05:24:14 | // The MIT License
// Copyright © 2015 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// https://www.youtube.com/c/InigoQuilez
// https://iquilezles.org
// Signed distance to a 2D rounded box. Tutorials explaining
// how it works:
//
// https://www.youtube.com/watch?v=62-pRVZuS5c
// https://www.youtube.com/watch?v=s5NGeUV2EyU
// List of some other 2D distances: https://www.shadertoy.com/playlist/MXdSRf
// and www.iquilezles.org/www/articles/distfunctions2d/distfunctions2d.htm
// b.x = width
// b.y = height
// r.x = roundness top-right
// r.y = roundness boottom-right
// r.z = roundness top-left
// r.w = roundness bottom-left
float sdRoundBox( in vec2 p, in vec2 b, in vec4 r )
{
r.xy = (p.x>0.0)?r.xy : r.zw;
r.x = (p.y>0.0)?r.x : r.y;
vec2 q = abs(p)-b+r.x;
return min(max(q.x,q.y),0.0) + length(max(q,0.0)) - r.x;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 p = (2.0*fragCoord-iResolution.xy)/iResolution.y;
vec2 m = (2.0*iMouse.xy-iResolution.xy)/iResolution.y;
vec2 si = vec2(0.9,0.6) + 0.3*cos(iTime+vec2(0,2));
vec4 ra = 0.3 + 0.3*cos( 2.0*iTime + vec4(0,1,2,3) );
ra = min(ra,min(si.x,si.y));
float d = sdRoundBox( p, si, ra );
vec3 col = vec3(1.0) - sign(d)*vec3(0.1,0.4,0.7);
col *= 1.0 - exp(-3.0*abs(d));
col *= 0.8 + 0.2*cos(150.0*d);
col = mix( col, vec3(1.0), 1.0-smoothstep(0.0,0.01,abs(d)) );
if( iMouse.z>0.001 )
{
d = sdRoundBox(m, si, ra );
col = mix(col, vec3(1.0,1.0,0.0), 1.0-smoothstep(0.0, 0.005, abs(length(p-m)-abs(d))-0.0025));
col = mix(col, vec3(1.0,1.0,0.0), 1.0-smoothstep(0.0, 0.005, length(p-m)-0.015));
}
fragColor = vec4(col,1.0);
} | mit | [
1478,
1632,
1686,
1686,
1843
] | [
[
1478,
1632,
1686,
1686,
1843
],
[
1845,
1845,
1902,
1902,
2667
]
] | // b.x = width
// b.y = height
// r.x = roundness top-right
// r.y = roundness boottom-right
// r.z = roundness top-left
// r.w = roundness bottom-left
| float sdRoundBox( in vec2 p, in vec2 b, in vec4 r )
{ |
r.xy = (p.x>0.0)?r.xy : r.zw;
r.x = (p.y>0.0)?r.x : r.y;
vec2 q = abs(p)-b+r.x;
return min(max(q.x,q.y),0.0) + length(max(q,0.0)) - r.x;
} | // b.x = width
// b.y = height
// r.x = roundness top-right
// r.y = roundness boottom-right
// r.z = roundness top-left
// r.w = roundness bottom-left
float sdRoundBox( in vec2 p, in vec2 b, in vec4 r )
{ | 4 | 6 |
ltlSWf | otaviogood | 2015-08-25T04:26:33 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// ---------------- Config ----------------
// This is an option that lets you render high quality frames for screenshots. It enables
// stochastic antialiasing and motion blur automatically for any shader.
//#define NON_REALTIME_HQ_RENDER
const float frameToRenderHQ = 20.0; // Time in seconds of frame to render
const float antialiasingSamples = 16.0; // 16x antialiasing - too much might make the shader compiler angry.
//#define MANUAL_CAMERA
#define ZERO_TRICK max(0, -iFrame)
// --------------------------------------------------------
// These variables are for the non-realtime block renderer.
float localTime = 0.0;
float seed = 1.0;
// Animation variables
float animStructure = 1.0;
float fade = 1.0;
// ---- noise functions ----
float v31(vec3 a)
{
return a.x + a.y * 37.0 + a.z * 521.0;
}
float v21(vec2 a)
{
return a.x + a.y * 37.0;
}
float Hash11(float a)
{
return fract(sin(a)*10403.9);
}
float Hash21(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
vec2 Hash22(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(cos(f)*vec2(10003.579, 37049.7));
}
vec2 Hash12(float f)
{
return fract(cos(f)*vec2(10003.579, 37049.7));
}
float Hash1d(float u)
{
return fract(sin(u)*143.9); // scale this down to kill the jitters
}
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(sin(f)*110003.9);
}
float mixP(float f0, float f1, float a)
{
return mix(f0, f1, a*a*(3.0-2.0*a));
}
const vec2 zeroOne = vec2(0.0, 1.0);
float noise2d(vec2 uv)
{
vec2 fr = fract(uv.xy);
vec2 fl = floor(uv.xy);
float h00 = Hash2d(fl);
float h10 = Hash2d(fl + zeroOne.yx);
float h01 = Hash2d(fl + zeroOne);
float h11 = Hash2d(fl + zeroOne.yy);
return mixP(mixP(h00, h10, fr.x), mixP(h01, h11, fr.x), fr.y);
}
float noise(vec3 uv)
{
vec3 fr = fract(uv.xyz);
vec3 fl = floor(uv.xyz);
float h000 = Hash3d(fl);
float h100 = Hash3d(fl + zeroOne.yxx);
float h010 = Hash3d(fl + zeroOne.xyx);
float h110 = Hash3d(fl + zeroOne.yyx);
float h001 = Hash3d(fl + zeroOne.xxy);
float h101 = Hash3d(fl + zeroOne.yxy);
float h011 = Hash3d(fl + zeroOne.xyy);
float h111 = Hash3d(fl + zeroOne.yyy);
return mixP(
mixP(mixP(h000, h100, fr.x),
mixP(h010, h110, fr.x), fr.y),
mixP(mixP(h001, h101, fr.x),
mixP(h011, h111, fr.x), fr.y)
, fr.z);
}
const float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
// This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.71; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
// Total hack of the spiral noise function to get a rust look
float RustNoise3D(vec3 p)
{
float n = 0.0;
float iter = 1.0;
float pn = noise(p*0.125);
pn += noise(p*0.25)*0.5;
pn += noise(p*0.5)*0.25;
pn += noise(p*1.0)*0.125;
for (int i = ZERO_TRICK; i < 7; i++)
{
//n += (sin(p.y*iter) + cos(p.x*iter)) / iter;
float wave = saturate(cos(p.y*0.25 + pn) - 0.998);
wave *= noise(p * 0.125)*1016.0;
n += wave;
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.4733;
}
return n;
}
// ---- functions to remap / warp space ----
float repsDouble(float a)
{
return abs(a * 2.0 - 1.0);
}
vec2 repsDouble(vec2 a)
{
return abs(a * 2.0 - 1.0);
}
vec2 mapSpiralMirror(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
at = at / PI;
float dist = (fract(log(len)+at*0.5)-0.5) * 2.0;
at = repsDouble(at);
at = repsDouble(at);
return vec2(abs(dist), abs(at));
}
vec2 mapSpiral(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
at = at / PI;
float dist = (fract(log(len)+at*0.5)-0.5) * 2.0;
//dist += sin(at*32.0)*0.05;
// at is [-1..1]
// dist is [-1..1]
at = repsDouble(at);
at = repsDouble(at);
return vec2(dist, at);
}
vec2 mapCircleInvert(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
//at = at / PI;
//return uv;
len = 1.0 / len;
return vec2(sin(at)*len, cos(at)*len);
}
vec3 mapSphereInvert(vec3 uv)
{
float len = length(uv);
vec3 dir = normalize(uv);
len = 1.0 / len;
return dir * len;
}
// ---- shapes defined by distance fields ----
// See this site for a reference to more distance functions...
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
float length8(vec2 v)
{
return pow(pow(abs(v.x),8.0) + pow(abs(v.y), 8.0), 1.0/8.0);
}
// box distance field
float sdBox(vec3 p, vec3 radius)
{
vec3 dist = abs(p) - radius;
return min(max(dist.x, max(dist.y, dist.z)), 0.0) + length(max(dist, 0.0));
}
// Makes a warped torus that rotates around
float sdTorusWobble( vec3 p, vec2 t, float offset)
{
float a = atan(p.x, p.z);
float subs = 2.0;
a = sin(a*subs+localTime*4.0+offset*3.234567);
vec2 q = vec2(length(p.xz)-t.x-a*0.1,p.y);
return length8(q)-t.y;
}
// simple cylinder distance field
float cyl(vec2 p, float r)
{
return length(p) - r;
}
float glow = 0.0, glow2 = 0.0, glow3 = 0.0;
float pulse;
// This is the big money function that makes the crazy fractally shape
// The input is a position in space.
// The output is the distance to the nearest surface.
float DistanceToObject(vec3 p)
{
vec3 orig = p;
// Magically remap space to be in a spiral
p.yz = mapSpiralMirror(p.yz);
// Mix between spiral space and unwarped space. This changes the scene
// from the tunnel to the spiral.
p = mix(orig, p, animStructure);
// p = mix(p, orig, cos(localTime)*0.5+0.5);
// Cut out stuff outside of outer radius
const float outerRad = 3.5;
float lenXY = length(p.xy);
float final = lenXY - outerRad;
// Carve out inner radius
final = max(final, -(lenXY - (outerRad-0.65)));
// Slice the object in a 3d grid
float slice = 0.04;
vec3 grid = -abs(fract(p)-0.5) + slice;
//final = max(final, grid.x);
//final = max(final, grid.y);
final = max(final, grid.z);
// Carve out cylinders from the object on all 3 axis, scaled 3 times
// This gives it the fractal look.
vec3 rep = fract(p)-0.5;
float scale = 1.0;
float mult = 0.32;
for (int i = ZERO_TRICK; i < 3; i++)
{
float uglyDivider = max(1.0, float(i)); // wtf is this? My math sucks :(
// carve out 3 cylinders
float dist = cyl(rep.xz/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
dist = cyl(rep.xy/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
dist = cyl(rep.yz/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
// Scale and repeat.
scale *= 1.14+1.0;// + sin(localTime)*0.995;
rep = fract(rep*scale) - 0.5;
}
// Make radial struts that poke into the center of the spiral
vec3 sp = p;
sp.x = abs(sp.x)-5.4;
sp.z = fract(sp.z) - 0.5;
// Bad distance field on these makes them sometimes disappear. Math. :(
float struts = sdBox(sp+vec3(2.95, 0.1-sin(sp.x*2.0)*1.1, 0.0), vec3(1.5, 0.05, 0.02))*0.5;
//glow3 += (0.00005)/max(0.01, struts);
final = min(final, struts);
// Make spiral glows that rotate and pulse energy to the center
rep.yz = (fract(p.yz)-0.5);
rep.x = p.x;
scale = 1.14+1.0;
float jolt = max(0.0, sin(length(orig.yz) + localTime*20.0))*0.94;
jolt *= saturate(0.3-pulse);
float spiral = sdBox(RotateX(rep+vec3(-0.05,0.0,0.0), pulse), vec3(0.01+jolt,1.06, mult*0.01)/scale );
glow3 += (0.0018)/max(0.0025,spiral);
final = min(final, spiral + (1.0-animStructure) * 100.0);
// Make a warped torus that rotates around and glows orange
vec3 rp = p.xzy;
rp.x = -abs(rp.x);
rp.y = fract(rp.y) - 0.5;
float torus = sdTorusWobble(rp + vec3(3.0, 0.0, 0.0), vec2(0.2, 0.0003), p.z);
glow2 += 0.0015 / max(0.03, torus);
final = min(final, torus);
// Make the glowing tower in the center.
// This also gives a bit of a glow to everything.
glow += (0.02+abs(sin(orig.x-localTime*3.0)*0.15)*jolt )/length(orig.yz);
return final;
}
// Input is UV coordinate of pixel to render.
// Output is RGB color.
vec3 RayTrace(in vec2 fragCoord )
{
glow = 0.0;
glow2 = 0.0;
glow3 = 0.0;
// -------------------------------- animate ---------------------------------------
// Default to spiral shape
animStructure = 1.0;
// Make a cycling, clamped sin wave to animate the glow-spiral rotation.
float slt = sin(localTime);
float stepLike = pow(abs(slt), 0.75)*sign(slt);
stepLike = max(-1.0, min(1.0, stepLike*1.5));
pulse = stepLike*PI/4.0 + PI/4.0;
vec3 camPos, camUp, camLookat;
// ------------------- Set up the camera rays for ray marching --------------------
// Map uv to [-1.0..1.0]
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
#ifdef MANUAL_CAMERA
// Camera up vector.
camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0,0.0,0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0;// + localTime * 0.166;
float my=-iMouse.y/iResolution.y*10.0;// + sin(localTime * 0.3)*0.8+0.1;//*PI/2.01;
camPos = vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*8.35;
#else
// Do the camera fly-by animation and different scenes.
// Time variables for start and end of each scene
const float t0 = 0.0;
const float t1 = 9.0;
const float t2 = 16.0;
const float t3 = 24.0;
const float t4 = 40.0;
const float t5 = 48.0;
const float t6 = 70.0;
// Repeat the animation after time t6
localTime = fract(localTime / t6) * t6;
/*const float t0 = 0.0;
const float t1 = 0.0;
const float t2 = 0.0;
const float t3 = 0.0;
const float t4 = 0.0;
const float t5 = 0.0;
const float t6 = 18.0;*/
if (localTime < t1)
{
animStructure = 0.0;
float time = localTime - t0;
float alpha = time / (t1 - t0);
fade = saturate(time);
fade *= saturate(t1 - localTime);
camPos = vec3(56.0, -2.5, 1.5);
camPos.x -= alpha * 6.8;
camUp=vec3(0,1,0);
camLookat=vec3(50,0.0,0);
} else if (localTime < t2)
{
animStructure = 0.0;
float time = localTime - t1;
float alpha = time / (t2 - t1);
fade = saturate(time);
fade *= saturate(t2 - localTime);
camPos = vec3(12.0, 3.3, -0.5);
camPos.x -= smoothstep(0.0, 1.0, alpha) * 4.8;
camUp=vec3(0,1,0);
camLookat=vec3(0,5.5,-0.5);
} else if (localTime < t3)
{
animStructure = 1.0;
float time = localTime - t2;
float alpha = time / (t3 - t2);
fade = saturate(time);
fade *= saturate(t3 - localTime);
camPos = vec3(12.0, 6.3, -0.5);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 6.3;
camPos.z = sin(alpha*1.0) * 6.3;
camUp=normalize(vec3(0,1,-0.3 - alpha * 0.5));
camLookat=vec3(0,0.0,-0.5);
} else if (localTime < t4)
{
animStructure = 1.0;
float time = localTime - t3;
float alpha = time / (t4 - t3);
fade = saturate(time);
fade *= saturate(t4 - localTime);
camPos = vec3(12.0, 3.0, -2.6);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 6.5-alpha*0.25;
camPos.z += sin(alpha*1.0) * 6.5-alpha*0.25;
camUp=normalize(vec3(0,1,0.0));
camLookat=vec3(0,0.0,-0.0);
} else if (localTime < t5)
{
animStructure = 1.0;
float time = localTime - t4;
float alpha = time / (t5 - t4);
fade = saturate(time);
fade *= saturate(t5 - localTime);
camPos = vec3(0.0, -7.0, -0.9);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 1.5-alpha*1.5;
camPos.z += sin(alpha*1.0) * 1.5-alpha*1.5;
camUp=normalize(vec3(0,1,0.0));
camLookat=vec3(0,-3.0,-0.0);
} else if (localTime < t6)
{
float time = localTime - t5;
float alpha = time / (t6 - t5);
float smoothv = smoothstep(0.0, 1.0, saturate(alpha*1.8-0.1));
animStructure = 1.0-smoothv;
fade = saturate(time);
fade *= saturate(t6 - localTime);
camPos = vec3(10.0, -0.95+smoothv*1.0, 0.0);
camPos.x -= alpha * 6.8;
camUp=normalize(vec3(0,1.0-smoothv,0.0+smoothv));
camLookat=vec3(0,-0.0,-0.0);
}
#endif
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 rayVec = normalize(worldPix - camPos);
// ----------------------------- Ray march the scene ------------------------------
float dist = 1.0;
float t = 0.1 + Hash2d(uv)*0.1; // random dither-fade things close to the camera
const float maxDepth = 45.0; // farthest distance rays will travel
vec3 pos = vec3(0,0,0);
const float smallVal = 0.000625;
// ray marching time
for (int i = ZERO_TRICK; i < 210; i++) // This is the count of the max times the ray actually marches.
{
// Step along the ray. Switch x, y, and z because I messed up the orientation.
pos = (camPos + rayVec * t).yzx;
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry. The idea is that the
// distance field returns the distance to the closest object, and then
// we know we are safe to "march" along the ray by that much distance
// without hitting anything. We repeat this until we get really close
// and then break because we have effectively hit the object.
dist = DistanceToObject(pos);
// This makes the ray trace more precisely in the center so it will not miss the
// vertical glowy beam.
dist = min(dist, length(pos.yz));
t += dist;
// If we are very close to the object, let's call it a hit and exit this loop.
if ((t > maxDepth) || (abs(dist) < smallVal)) break;
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
float glowSave = glow;
float glow2Save = glow2;
float glow3Save = glow3;
vec3 sunDir = normalize(vec3(0.93, 1.0, -1.5));
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(smallVal, 0, 0);
vec3 normalU = vec3(dist - DistanceToObject(pos - smallVec.xyy),
dist - DistanceToObject(pos - smallVec.yxy),
dist - DistanceToObject(pos - smallVec.yyx));
vec3 normal = normalize(normalU);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff
float ambientS = 1.0;
ambientS *= saturate(DistanceToObject(pos + normal * 0.05)*20.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.1)*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2)*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4)*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8)*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6)*1.25*0.5);
//ambient *= saturate(DistanceToObject(pos + normal * 3.2)*1.25*0.25);
//ambient *= saturate(DistanceToObject(pos + normal * 6.4)*1.25*0.125);
//ambient = max(0.05, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// calculate the reflection vector for highlights
//vec3 ref = reflect(rayVec, normal);
// Trace a ray toward the sun for sun shadows
float sunShadow = 1.0;
float iter = 0.01;
vec3 nudgePos = pos + normal*0.002; // don't start tracing too close or inside the object
for (int i = ZERO_TRICK; i < 30; i++)
{
float tempDist = DistanceToObject(nudgePos + sunDir * iter);
sunShadow *= saturate(tempDist*150.0); // Shadow hardness
if (tempDist <= 0.0) break;
//iter *= 1.5; // constant is more reliable than distance-based
iter += max(0.01, tempDist)*1.0;
if (iter > 4.2) break;
}
sunShadow = saturate(sunShadow);
// make a few frequencies of noise to give it some texture
float n =0.0;
n += noise(pos*32.0);
n += noise(pos*64.0);
n += noise(pos*128.0);
n += noise(pos*256.0);
n += noise(pos*512.0);
n *= 0.8;
normal = normalize(normal + (n-2.0)*0.1);
// ------ Calculate texture color ------
vec3 texColor = vec3(0.95, 1.0, 1.0);
vec3 rust = vec3(0.65, 0.25, 0.1) - noise(pos*128.0);
// Call the function that makes rust stripes on the texture
texColor *= smoothstep(texColor, rust, vec3(saturate(RustNoise3D(pos*8.0))-0.2));
// apply noise
texColor *= vec3(1.0)*n*0.05;
texColor *= 0.7;
texColor = saturate(texColor);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(3.6) * saturate(dot(sunDir, normal)) * sunShadow;
// weighted average the near ambient occlusion with the far for just the right look
float ambientAvg = (ambient*3.0 + ambientS) * 0.25;
// a red and blue light coming from different directions
lightColor += (vec3(1.0, 0.2, 0.4) * saturate(-normal.z *0.5+0.5))*pow(ambientAvg, 0.35);
lightColor += (vec3(0.1, 0.5, 0.99) * saturate(normal.y *0.5+0.5))*pow(ambientAvg, 0.35);
// blue glow light coming from the glow in the middle
lightColor += vec3(0.3, 0.5, 0.9) * saturate(dot(-pos, normal))*pow(ambientS, 0.3);
lightColor *= 4.0;
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// sun reflection to make it look metal
//finalColor += vec3(1.0)*pow(n,4.0)* GetSunColorSmall(ref, sunDir) * sunShadow;// * ambientS;
// visualize length of gradient of distance field to check distance field correctness
//finalColor = vec3(0.5) * (length(normalU) / smallVec.x);
}
else
{
// Our ray trace hit nothing, so draw sky.
}
// add the ray marching glows
float center = length(pos.yz);
finalColor += vec3(0.3, 0.5, 0.9) * glowSave*1.2;
finalColor += vec3(0.9, 0.5, 0.3) * glow2*1.2;
finalColor += vec3(0.25, 0.29, 0.93) * glow3Save*2.0;
// vignette?
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
finalColor *= 1.0;// 1.3;
// output the final color without gamma correction - will do gamma later.
return vec3(clamp(finalColor, 0.0, 1.0)*saturate(fade+0.25));
}
#ifdef NON_REALTIME_HQ_RENDER
// This function breaks the image down into blocks and scans
// through them, rendering 1 block at a time. It's for non-
// realtime things that take a long time to render.
// This is the frame rate to render at. Too fast and you will
// miss some blocks.
const float blockRate = 20.0;
void BlockRender(in vec2 fragCoord)
{
// blockSize is how much it will try to render in 1 frame.
// adjust this smaller for more complex scenes, bigger for
// faster render times.
const float blockSize = 64.0;
// Make the block repeatedly scan across the image based on time.
float frame = floor(iTime * blockRate);
vec2 blockRes = floor(iResolution.xy / blockSize) + vec2(1.0);
// ugly bug with mod.
//float blockX = mod(frame, blockRes.x);
float blockX = fract(frame / blockRes.x) * blockRes.x;
//float blockY = mod(floor(frame / blockRes.x), blockRes.y);
float blockY = fract(floor(frame / blockRes.x) / blockRes.y) * blockRes.y;
// Don't draw anything outside the current block.
if ((fragCoord.x - blockX * blockSize >= blockSize) ||
(fragCoord.x - (blockX - 1.0) * blockSize < blockSize) ||
(fragCoord.y - blockY * blockSize >= blockSize) ||
(fragCoord.y - (blockY - 1.0) * blockSize < blockSize))
{
discard;
}
}
#endif
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
#ifdef NON_REALTIME_HQ_RENDER
// Optionally render a non-realtime scene with high quality
BlockRender(fragCoord);
#endif
// Do a multi-pass render
vec3 finalColor = vec3(0.0);
#ifdef NON_REALTIME_HQ_RENDER
for (float i = 0.0; i < antialiasingSamples; i++)
{
const float motionBlurLengthInSeconds = 1.0 / 60.0;
// Set this to the time in seconds of the frame to render.
localTime = frameToRenderHQ;
// This line will motion-blur the renders
localTime += Hash11(v21(fragCoord + seed)) * motionBlurLengthInSeconds;
// Jitter the pixel position so we get antialiasing when we do multiple passes.
vec2 jittered = fragCoord.xy + vec2(
Hash21(fragCoord + seed),
Hash21(fragCoord*7.234567 + seed)
);
// don't antialias if only 1 sample.
if (antialiasingSamples == 1.0) jittered = fragCoord;
// Accumulate one pass of raytracing into our pixel value
finalColor += RayTrace(jittered);
// Change the random seed for each pass.
seed *= 1.01234567;
}
// Average all accumulated pixel intensities
finalColor /= antialiasingSamples;
#else
// Regular real-time rendering
localTime = iTime;
finalColor = RayTrace(fragCoord);
#endif
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
4861,
4906,
4933,
4933,
4966
] | [
[
1278,
1307,
1326,
1326,
1371
],
[
1372,
1372,
1391,
1391,
1422
],
[
1423,
1423,
1446,
1446,
1482
],
[
1483,
1483,
1506,
1506,
1577
],
[
1578,
1578,
1600,
1600,
1687
],
[
1688,
1688,
1710,
1710,
1763
],
[
1764,
1764,
1787,
1787,
1860
],
[
1861,
1861,
1884,
1884,
1955
],
[
1956,
1956,
1979,
1979,
2065
],
[
2066,
2066,
2107,
2107,
2150
],
[
2188,
2188,
2212,
2212,
2485
],
[
2486,
2486,
2508,
2508,
3093
],
[
3123,
3123,
3146,
3146,
3175
],
[
3176,
3176,
3199,
3199,
3228
],
[
3229,
3229,
3254,
3254,
3283
],
[
3285,
3285,
3318,
3318,
3435
],
[
3436,
3436,
3469,
3469,
3585
],
[
3586,
3586,
3619,
3619,
3736
],
[
3738,
4267,
4294,
4294,
4859
],
[
4861,
4906,
4933,
4933,
4966
],
[
4967,
4967,
4992,
4992,
5025
],
[
5027,
5027,
5058,
5058,
5279
],
[
5281,
5281,
5306,
5306,
5594
],
[
5596,
5596,
5627,
5627,
5791
],
[
5793,
5793,
5824,
5824,
5927
],
[
5929,
6109,
6132,
6132,
6196
],
[
6198,
6220,
6254,
6254,
6365
],
[
6367,
6411,
6463,
6463,
6633
],
[
6635,
6669,
6697,
6697,
6725
],
[
6784,
6946,
6978,
6978,
9802
],
[
9804,
9874,
9909,
9909,
20901
],
[
22233,
22233,
22290,
22290,
23649
]
] | // ---- functions to remap / warp space ----
| float repsDouble(float a)
{ |
return abs(a * 2.0 - 1.0);
} | // ---- functions to remap / warp space ----
float repsDouble(float a)
{ | 1 | 1 |
ltlSWf | otaviogood | 2015-08-25T04:26:33 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// ---------------- Config ----------------
// This is an option that lets you render high quality frames for screenshots. It enables
// stochastic antialiasing and motion blur automatically for any shader.
//#define NON_REALTIME_HQ_RENDER
const float frameToRenderHQ = 20.0; // Time in seconds of frame to render
const float antialiasingSamples = 16.0; // 16x antialiasing - too much might make the shader compiler angry.
//#define MANUAL_CAMERA
#define ZERO_TRICK max(0, -iFrame)
// --------------------------------------------------------
// These variables are for the non-realtime block renderer.
float localTime = 0.0;
float seed = 1.0;
// Animation variables
float animStructure = 1.0;
float fade = 1.0;
// ---- noise functions ----
float v31(vec3 a)
{
return a.x + a.y * 37.0 + a.z * 521.0;
}
float v21(vec2 a)
{
return a.x + a.y * 37.0;
}
float Hash11(float a)
{
return fract(sin(a)*10403.9);
}
float Hash21(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
vec2 Hash22(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(cos(f)*vec2(10003.579, 37049.7));
}
vec2 Hash12(float f)
{
return fract(cos(f)*vec2(10003.579, 37049.7));
}
float Hash1d(float u)
{
return fract(sin(u)*143.9); // scale this down to kill the jitters
}
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(sin(f)*110003.9);
}
float mixP(float f0, float f1, float a)
{
return mix(f0, f1, a*a*(3.0-2.0*a));
}
const vec2 zeroOne = vec2(0.0, 1.0);
float noise2d(vec2 uv)
{
vec2 fr = fract(uv.xy);
vec2 fl = floor(uv.xy);
float h00 = Hash2d(fl);
float h10 = Hash2d(fl + zeroOne.yx);
float h01 = Hash2d(fl + zeroOne);
float h11 = Hash2d(fl + zeroOne.yy);
return mixP(mixP(h00, h10, fr.x), mixP(h01, h11, fr.x), fr.y);
}
float noise(vec3 uv)
{
vec3 fr = fract(uv.xyz);
vec3 fl = floor(uv.xyz);
float h000 = Hash3d(fl);
float h100 = Hash3d(fl + zeroOne.yxx);
float h010 = Hash3d(fl + zeroOne.xyx);
float h110 = Hash3d(fl + zeroOne.yyx);
float h001 = Hash3d(fl + zeroOne.xxy);
float h101 = Hash3d(fl + zeroOne.yxy);
float h011 = Hash3d(fl + zeroOne.xyy);
float h111 = Hash3d(fl + zeroOne.yyy);
return mixP(
mixP(mixP(h000, h100, fr.x),
mixP(h010, h110, fr.x), fr.y),
mixP(mixP(h001, h101, fr.x),
mixP(h011, h111, fr.x), fr.y)
, fr.z);
}
const float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
// This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.71; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
// Total hack of the spiral noise function to get a rust look
float RustNoise3D(vec3 p)
{
float n = 0.0;
float iter = 1.0;
float pn = noise(p*0.125);
pn += noise(p*0.25)*0.5;
pn += noise(p*0.5)*0.25;
pn += noise(p*1.0)*0.125;
for (int i = ZERO_TRICK; i < 7; i++)
{
//n += (sin(p.y*iter) + cos(p.x*iter)) / iter;
float wave = saturate(cos(p.y*0.25 + pn) - 0.998);
wave *= noise(p * 0.125)*1016.0;
n += wave;
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.4733;
}
return n;
}
// ---- functions to remap / warp space ----
float repsDouble(float a)
{
return abs(a * 2.0 - 1.0);
}
vec2 repsDouble(vec2 a)
{
return abs(a * 2.0 - 1.0);
}
vec2 mapSpiralMirror(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
at = at / PI;
float dist = (fract(log(len)+at*0.5)-0.5) * 2.0;
at = repsDouble(at);
at = repsDouble(at);
return vec2(abs(dist), abs(at));
}
vec2 mapSpiral(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
at = at / PI;
float dist = (fract(log(len)+at*0.5)-0.5) * 2.0;
//dist += sin(at*32.0)*0.05;
// at is [-1..1]
// dist is [-1..1]
at = repsDouble(at);
at = repsDouble(at);
return vec2(dist, at);
}
vec2 mapCircleInvert(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
//at = at / PI;
//return uv;
len = 1.0 / len;
return vec2(sin(at)*len, cos(at)*len);
}
vec3 mapSphereInvert(vec3 uv)
{
float len = length(uv);
vec3 dir = normalize(uv);
len = 1.0 / len;
return dir * len;
}
// ---- shapes defined by distance fields ----
// See this site for a reference to more distance functions...
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
float length8(vec2 v)
{
return pow(pow(abs(v.x),8.0) + pow(abs(v.y), 8.0), 1.0/8.0);
}
// box distance field
float sdBox(vec3 p, vec3 radius)
{
vec3 dist = abs(p) - radius;
return min(max(dist.x, max(dist.y, dist.z)), 0.0) + length(max(dist, 0.0));
}
// Makes a warped torus that rotates around
float sdTorusWobble( vec3 p, vec2 t, float offset)
{
float a = atan(p.x, p.z);
float subs = 2.0;
a = sin(a*subs+localTime*4.0+offset*3.234567);
vec2 q = vec2(length(p.xz)-t.x-a*0.1,p.y);
return length8(q)-t.y;
}
// simple cylinder distance field
float cyl(vec2 p, float r)
{
return length(p) - r;
}
float glow = 0.0, glow2 = 0.0, glow3 = 0.0;
float pulse;
// This is the big money function that makes the crazy fractally shape
// The input is a position in space.
// The output is the distance to the nearest surface.
float DistanceToObject(vec3 p)
{
vec3 orig = p;
// Magically remap space to be in a spiral
p.yz = mapSpiralMirror(p.yz);
// Mix between spiral space and unwarped space. This changes the scene
// from the tunnel to the spiral.
p = mix(orig, p, animStructure);
// p = mix(p, orig, cos(localTime)*0.5+0.5);
// Cut out stuff outside of outer radius
const float outerRad = 3.5;
float lenXY = length(p.xy);
float final = lenXY - outerRad;
// Carve out inner radius
final = max(final, -(lenXY - (outerRad-0.65)));
// Slice the object in a 3d grid
float slice = 0.04;
vec3 grid = -abs(fract(p)-0.5) + slice;
//final = max(final, grid.x);
//final = max(final, grid.y);
final = max(final, grid.z);
// Carve out cylinders from the object on all 3 axis, scaled 3 times
// This gives it the fractal look.
vec3 rep = fract(p)-0.5;
float scale = 1.0;
float mult = 0.32;
for (int i = ZERO_TRICK; i < 3; i++)
{
float uglyDivider = max(1.0, float(i)); // wtf is this? My math sucks :(
// carve out 3 cylinders
float dist = cyl(rep.xz/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
dist = cyl(rep.xy/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
dist = cyl(rep.yz/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
// Scale and repeat.
scale *= 1.14+1.0;// + sin(localTime)*0.995;
rep = fract(rep*scale) - 0.5;
}
// Make radial struts that poke into the center of the spiral
vec3 sp = p;
sp.x = abs(sp.x)-5.4;
sp.z = fract(sp.z) - 0.5;
// Bad distance field on these makes them sometimes disappear. Math. :(
float struts = sdBox(sp+vec3(2.95, 0.1-sin(sp.x*2.0)*1.1, 0.0), vec3(1.5, 0.05, 0.02))*0.5;
//glow3 += (0.00005)/max(0.01, struts);
final = min(final, struts);
// Make spiral glows that rotate and pulse energy to the center
rep.yz = (fract(p.yz)-0.5);
rep.x = p.x;
scale = 1.14+1.0;
float jolt = max(0.0, sin(length(orig.yz) + localTime*20.0))*0.94;
jolt *= saturate(0.3-pulse);
float spiral = sdBox(RotateX(rep+vec3(-0.05,0.0,0.0), pulse), vec3(0.01+jolt,1.06, mult*0.01)/scale );
glow3 += (0.0018)/max(0.0025,spiral);
final = min(final, spiral + (1.0-animStructure) * 100.0);
// Make a warped torus that rotates around and glows orange
vec3 rp = p.xzy;
rp.x = -abs(rp.x);
rp.y = fract(rp.y) - 0.5;
float torus = sdTorusWobble(rp + vec3(3.0, 0.0, 0.0), vec2(0.2, 0.0003), p.z);
glow2 += 0.0015 / max(0.03, torus);
final = min(final, torus);
// Make the glowing tower in the center.
// This also gives a bit of a glow to everything.
glow += (0.02+abs(sin(orig.x-localTime*3.0)*0.15)*jolt )/length(orig.yz);
return final;
}
// Input is UV coordinate of pixel to render.
// Output is RGB color.
vec3 RayTrace(in vec2 fragCoord )
{
glow = 0.0;
glow2 = 0.0;
glow3 = 0.0;
// -------------------------------- animate ---------------------------------------
// Default to spiral shape
animStructure = 1.0;
// Make a cycling, clamped sin wave to animate the glow-spiral rotation.
float slt = sin(localTime);
float stepLike = pow(abs(slt), 0.75)*sign(slt);
stepLike = max(-1.0, min(1.0, stepLike*1.5));
pulse = stepLike*PI/4.0 + PI/4.0;
vec3 camPos, camUp, camLookat;
// ------------------- Set up the camera rays for ray marching --------------------
// Map uv to [-1.0..1.0]
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
#ifdef MANUAL_CAMERA
// Camera up vector.
camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0,0.0,0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0;// + localTime * 0.166;
float my=-iMouse.y/iResolution.y*10.0;// + sin(localTime * 0.3)*0.8+0.1;//*PI/2.01;
camPos = vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*8.35;
#else
// Do the camera fly-by animation and different scenes.
// Time variables for start and end of each scene
const float t0 = 0.0;
const float t1 = 9.0;
const float t2 = 16.0;
const float t3 = 24.0;
const float t4 = 40.0;
const float t5 = 48.0;
const float t6 = 70.0;
// Repeat the animation after time t6
localTime = fract(localTime / t6) * t6;
/*const float t0 = 0.0;
const float t1 = 0.0;
const float t2 = 0.0;
const float t3 = 0.0;
const float t4 = 0.0;
const float t5 = 0.0;
const float t6 = 18.0;*/
if (localTime < t1)
{
animStructure = 0.0;
float time = localTime - t0;
float alpha = time / (t1 - t0);
fade = saturate(time);
fade *= saturate(t1 - localTime);
camPos = vec3(56.0, -2.5, 1.5);
camPos.x -= alpha * 6.8;
camUp=vec3(0,1,0);
camLookat=vec3(50,0.0,0);
} else if (localTime < t2)
{
animStructure = 0.0;
float time = localTime - t1;
float alpha = time / (t2 - t1);
fade = saturate(time);
fade *= saturate(t2 - localTime);
camPos = vec3(12.0, 3.3, -0.5);
camPos.x -= smoothstep(0.0, 1.0, alpha) * 4.8;
camUp=vec3(0,1,0);
camLookat=vec3(0,5.5,-0.5);
} else if (localTime < t3)
{
animStructure = 1.0;
float time = localTime - t2;
float alpha = time / (t3 - t2);
fade = saturate(time);
fade *= saturate(t3 - localTime);
camPos = vec3(12.0, 6.3, -0.5);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 6.3;
camPos.z = sin(alpha*1.0) * 6.3;
camUp=normalize(vec3(0,1,-0.3 - alpha * 0.5));
camLookat=vec3(0,0.0,-0.5);
} else if (localTime < t4)
{
animStructure = 1.0;
float time = localTime - t3;
float alpha = time / (t4 - t3);
fade = saturate(time);
fade *= saturate(t4 - localTime);
camPos = vec3(12.0, 3.0, -2.6);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 6.5-alpha*0.25;
camPos.z += sin(alpha*1.0) * 6.5-alpha*0.25;
camUp=normalize(vec3(0,1,0.0));
camLookat=vec3(0,0.0,-0.0);
} else if (localTime < t5)
{
animStructure = 1.0;
float time = localTime - t4;
float alpha = time / (t5 - t4);
fade = saturate(time);
fade *= saturate(t5 - localTime);
camPos = vec3(0.0, -7.0, -0.9);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 1.5-alpha*1.5;
camPos.z += sin(alpha*1.0) * 1.5-alpha*1.5;
camUp=normalize(vec3(0,1,0.0));
camLookat=vec3(0,-3.0,-0.0);
} else if (localTime < t6)
{
float time = localTime - t5;
float alpha = time / (t6 - t5);
float smoothv = smoothstep(0.0, 1.0, saturate(alpha*1.8-0.1));
animStructure = 1.0-smoothv;
fade = saturate(time);
fade *= saturate(t6 - localTime);
camPos = vec3(10.0, -0.95+smoothv*1.0, 0.0);
camPos.x -= alpha * 6.8;
camUp=normalize(vec3(0,1.0-smoothv,0.0+smoothv));
camLookat=vec3(0,-0.0,-0.0);
}
#endif
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 rayVec = normalize(worldPix - camPos);
// ----------------------------- Ray march the scene ------------------------------
float dist = 1.0;
float t = 0.1 + Hash2d(uv)*0.1; // random dither-fade things close to the camera
const float maxDepth = 45.0; // farthest distance rays will travel
vec3 pos = vec3(0,0,0);
const float smallVal = 0.000625;
// ray marching time
for (int i = ZERO_TRICK; i < 210; i++) // This is the count of the max times the ray actually marches.
{
// Step along the ray. Switch x, y, and z because I messed up the orientation.
pos = (camPos + rayVec * t).yzx;
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry. The idea is that the
// distance field returns the distance to the closest object, and then
// we know we are safe to "march" along the ray by that much distance
// without hitting anything. We repeat this until we get really close
// and then break because we have effectively hit the object.
dist = DistanceToObject(pos);
// This makes the ray trace more precisely in the center so it will not miss the
// vertical glowy beam.
dist = min(dist, length(pos.yz));
t += dist;
// If we are very close to the object, let's call it a hit and exit this loop.
if ((t > maxDepth) || (abs(dist) < smallVal)) break;
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
float glowSave = glow;
float glow2Save = glow2;
float glow3Save = glow3;
vec3 sunDir = normalize(vec3(0.93, 1.0, -1.5));
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(smallVal, 0, 0);
vec3 normalU = vec3(dist - DistanceToObject(pos - smallVec.xyy),
dist - DistanceToObject(pos - smallVec.yxy),
dist - DistanceToObject(pos - smallVec.yyx));
vec3 normal = normalize(normalU);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff
float ambientS = 1.0;
ambientS *= saturate(DistanceToObject(pos + normal * 0.05)*20.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.1)*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2)*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4)*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8)*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6)*1.25*0.5);
//ambient *= saturate(DistanceToObject(pos + normal * 3.2)*1.25*0.25);
//ambient *= saturate(DistanceToObject(pos + normal * 6.4)*1.25*0.125);
//ambient = max(0.05, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// calculate the reflection vector for highlights
//vec3 ref = reflect(rayVec, normal);
// Trace a ray toward the sun for sun shadows
float sunShadow = 1.0;
float iter = 0.01;
vec3 nudgePos = pos + normal*0.002; // don't start tracing too close or inside the object
for (int i = ZERO_TRICK; i < 30; i++)
{
float tempDist = DistanceToObject(nudgePos + sunDir * iter);
sunShadow *= saturate(tempDist*150.0); // Shadow hardness
if (tempDist <= 0.0) break;
//iter *= 1.5; // constant is more reliable than distance-based
iter += max(0.01, tempDist)*1.0;
if (iter > 4.2) break;
}
sunShadow = saturate(sunShadow);
// make a few frequencies of noise to give it some texture
float n =0.0;
n += noise(pos*32.0);
n += noise(pos*64.0);
n += noise(pos*128.0);
n += noise(pos*256.0);
n += noise(pos*512.0);
n *= 0.8;
normal = normalize(normal + (n-2.0)*0.1);
// ------ Calculate texture color ------
vec3 texColor = vec3(0.95, 1.0, 1.0);
vec3 rust = vec3(0.65, 0.25, 0.1) - noise(pos*128.0);
// Call the function that makes rust stripes on the texture
texColor *= smoothstep(texColor, rust, vec3(saturate(RustNoise3D(pos*8.0))-0.2));
// apply noise
texColor *= vec3(1.0)*n*0.05;
texColor *= 0.7;
texColor = saturate(texColor);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(3.6) * saturate(dot(sunDir, normal)) * sunShadow;
// weighted average the near ambient occlusion with the far for just the right look
float ambientAvg = (ambient*3.0 + ambientS) * 0.25;
// a red and blue light coming from different directions
lightColor += (vec3(1.0, 0.2, 0.4) * saturate(-normal.z *0.5+0.5))*pow(ambientAvg, 0.35);
lightColor += (vec3(0.1, 0.5, 0.99) * saturate(normal.y *0.5+0.5))*pow(ambientAvg, 0.35);
// blue glow light coming from the glow in the middle
lightColor += vec3(0.3, 0.5, 0.9) * saturate(dot(-pos, normal))*pow(ambientS, 0.3);
lightColor *= 4.0;
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// sun reflection to make it look metal
//finalColor += vec3(1.0)*pow(n,4.0)* GetSunColorSmall(ref, sunDir) * sunShadow;// * ambientS;
// visualize length of gradient of distance field to check distance field correctness
//finalColor = vec3(0.5) * (length(normalU) / smallVec.x);
}
else
{
// Our ray trace hit nothing, so draw sky.
}
// add the ray marching glows
float center = length(pos.yz);
finalColor += vec3(0.3, 0.5, 0.9) * glowSave*1.2;
finalColor += vec3(0.9, 0.5, 0.3) * glow2*1.2;
finalColor += vec3(0.25, 0.29, 0.93) * glow3Save*2.0;
// vignette?
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
finalColor *= 1.0;// 1.3;
// output the final color without gamma correction - will do gamma later.
return vec3(clamp(finalColor, 0.0, 1.0)*saturate(fade+0.25));
}
#ifdef NON_REALTIME_HQ_RENDER
// This function breaks the image down into blocks and scans
// through them, rendering 1 block at a time. It's for non-
// realtime things that take a long time to render.
// This is the frame rate to render at. Too fast and you will
// miss some blocks.
const float blockRate = 20.0;
void BlockRender(in vec2 fragCoord)
{
// blockSize is how much it will try to render in 1 frame.
// adjust this smaller for more complex scenes, bigger for
// faster render times.
const float blockSize = 64.0;
// Make the block repeatedly scan across the image based on time.
float frame = floor(iTime * blockRate);
vec2 blockRes = floor(iResolution.xy / blockSize) + vec2(1.0);
// ugly bug with mod.
//float blockX = mod(frame, blockRes.x);
float blockX = fract(frame / blockRes.x) * blockRes.x;
//float blockY = mod(floor(frame / blockRes.x), blockRes.y);
float blockY = fract(floor(frame / blockRes.x) / blockRes.y) * blockRes.y;
// Don't draw anything outside the current block.
if ((fragCoord.x - blockX * blockSize >= blockSize) ||
(fragCoord.x - (blockX - 1.0) * blockSize < blockSize) ||
(fragCoord.y - blockY * blockSize >= blockSize) ||
(fragCoord.y - (blockY - 1.0) * blockSize < blockSize))
{
discard;
}
}
#endif
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
#ifdef NON_REALTIME_HQ_RENDER
// Optionally render a non-realtime scene with high quality
BlockRender(fragCoord);
#endif
// Do a multi-pass render
vec3 finalColor = vec3(0.0);
#ifdef NON_REALTIME_HQ_RENDER
for (float i = 0.0; i < antialiasingSamples; i++)
{
const float motionBlurLengthInSeconds = 1.0 / 60.0;
// Set this to the time in seconds of the frame to render.
localTime = frameToRenderHQ;
// This line will motion-blur the renders
localTime += Hash11(v21(fragCoord + seed)) * motionBlurLengthInSeconds;
// Jitter the pixel position so we get antialiasing when we do multiple passes.
vec2 jittered = fragCoord.xy + vec2(
Hash21(fragCoord + seed),
Hash21(fragCoord*7.234567 + seed)
);
// don't antialias if only 1 sample.
if (antialiasingSamples == 1.0) jittered = fragCoord;
// Accumulate one pass of raytracing into our pixel value
finalColor += RayTrace(jittered);
// Change the random seed for each pass.
seed *= 1.01234567;
}
// Average all accumulated pixel intensities
finalColor /= antialiasingSamples;
#else
// Regular real-time rendering
localTime = iTime;
finalColor = RayTrace(fragCoord);
#endif
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
5929,
6109,
6132,
6132,
6196
] | [
[
1278,
1307,
1326,
1326,
1371
],
[
1372,
1372,
1391,
1391,
1422
],
[
1423,
1423,
1446,
1446,
1482
],
[
1483,
1483,
1506,
1506,
1577
],
[
1578,
1578,
1600,
1600,
1687
],
[
1688,
1688,
1710,
1710,
1763
],
[
1764,
1764,
1787,
1787,
1860
],
[
1861,
1861,
1884,
1884,
1955
],
[
1956,
1956,
1979,
1979,
2065
],
[
2066,
2066,
2107,
2107,
2150
],
[
2188,
2188,
2212,
2212,
2485
],
[
2486,
2486,
2508,
2508,
3093
],
[
3123,
3123,
3146,
3146,
3175
],
[
3176,
3176,
3199,
3199,
3228
],
[
3229,
3229,
3254,
3254,
3283
],
[
3285,
3285,
3318,
3318,
3435
],
[
3436,
3436,
3469,
3469,
3585
],
[
3586,
3586,
3619,
3619,
3736
],
[
3738,
4267,
4294,
4294,
4859
],
[
4861,
4906,
4933,
4933,
4966
],
[
4967,
4967,
4992,
4992,
5025
],
[
5027,
5027,
5058,
5058,
5279
],
[
5281,
5281,
5306,
5306,
5594
],
[
5596,
5596,
5627,
5627,
5791
],
[
5793,
5793,
5824,
5824,
5927
],
[
5929,
6109,
6132,
6132,
6196
],
[
6198,
6220,
6254,
6254,
6365
],
[
6367,
6411,
6463,
6463,
6633
],
[
6635,
6669,
6697,
6697,
6725
],
[
6784,
6946,
6978,
6978,
9802
],
[
9804,
9874,
9909,
9909,
20901
],
[
22233,
22233,
22290,
22290,
23649
]
] | // ---- shapes defined by distance fields ----
// See this site for a reference to more distance functions...
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
| float length8(vec2 v)
{ |
return pow(pow(abs(v.x),8.0) + pow(abs(v.y), 8.0), 1.0/8.0);
} | // ---- shapes defined by distance fields ----
// See this site for a reference to more distance functions...
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
float length8(vec2 v)
{ | 1 | 2 |
ltlSWf | otaviogood | 2015-08-25T04:26:33 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// ---------------- Config ----------------
// This is an option that lets you render high quality frames for screenshots. It enables
// stochastic antialiasing and motion blur automatically for any shader.
//#define NON_REALTIME_HQ_RENDER
const float frameToRenderHQ = 20.0; // Time in seconds of frame to render
const float antialiasingSamples = 16.0; // 16x antialiasing - too much might make the shader compiler angry.
//#define MANUAL_CAMERA
#define ZERO_TRICK max(0, -iFrame)
// --------------------------------------------------------
// These variables are for the non-realtime block renderer.
float localTime = 0.0;
float seed = 1.0;
// Animation variables
float animStructure = 1.0;
float fade = 1.0;
// ---- noise functions ----
float v31(vec3 a)
{
return a.x + a.y * 37.0 + a.z * 521.0;
}
float v21(vec2 a)
{
return a.x + a.y * 37.0;
}
float Hash11(float a)
{
return fract(sin(a)*10403.9);
}
float Hash21(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
vec2 Hash22(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(cos(f)*vec2(10003.579, 37049.7));
}
vec2 Hash12(float f)
{
return fract(cos(f)*vec2(10003.579, 37049.7));
}
float Hash1d(float u)
{
return fract(sin(u)*143.9); // scale this down to kill the jitters
}
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(sin(f)*110003.9);
}
float mixP(float f0, float f1, float a)
{
return mix(f0, f1, a*a*(3.0-2.0*a));
}
const vec2 zeroOne = vec2(0.0, 1.0);
float noise2d(vec2 uv)
{
vec2 fr = fract(uv.xy);
vec2 fl = floor(uv.xy);
float h00 = Hash2d(fl);
float h10 = Hash2d(fl + zeroOne.yx);
float h01 = Hash2d(fl + zeroOne);
float h11 = Hash2d(fl + zeroOne.yy);
return mixP(mixP(h00, h10, fr.x), mixP(h01, h11, fr.x), fr.y);
}
float noise(vec3 uv)
{
vec3 fr = fract(uv.xyz);
vec3 fl = floor(uv.xyz);
float h000 = Hash3d(fl);
float h100 = Hash3d(fl + zeroOne.yxx);
float h010 = Hash3d(fl + zeroOne.xyx);
float h110 = Hash3d(fl + zeroOne.yyx);
float h001 = Hash3d(fl + zeroOne.xxy);
float h101 = Hash3d(fl + zeroOne.yxy);
float h011 = Hash3d(fl + zeroOne.xyy);
float h111 = Hash3d(fl + zeroOne.yyy);
return mixP(
mixP(mixP(h000, h100, fr.x),
mixP(h010, h110, fr.x), fr.y),
mixP(mixP(h001, h101, fr.x),
mixP(h011, h111, fr.x), fr.y)
, fr.z);
}
const float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
// This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.71; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
// Total hack of the spiral noise function to get a rust look
float RustNoise3D(vec3 p)
{
float n = 0.0;
float iter = 1.0;
float pn = noise(p*0.125);
pn += noise(p*0.25)*0.5;
pn += noise(p*0.5)*0.25;
pn += noise(p*1.0)*0.125;
for (int i = ZERO_TRICK; i < 7; i++)
{
//n += (sin(p.y*iter) + cos(p.x*iter)) / iter;
float wave = saturate(cos(p.y*0.25 + pn) - 0.998);
wave *= noise(p * 0.125)*1016.0;
n += wave;
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.4733;
}
return n;
}
// ---- functions to remap / warp space ----
float repsDouble(float a)
{
return abs(a * 2.0 - 1.0);
}
vec2 repsDouble(vec2 a)
{
return abs(a * 2.0 - 1.0);
}
vec2 mapSpiralMirror(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
at = at / PI;
float dist = (fract(log(len)+at*0.5)-0.5) * 2.0;
at = repsDouble(at);
at = repsDouble(at);
return vec2(abs(dist), abs(at));
}
vec2 mapSpiral(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
at = at / PI;
float dist = (fract(log(len)+at*0.5)-0.5) * 2.0;
//dist += sin(at*32.0)*0.05;
// at is [-1..1]
// dist is [-1..1]
at = repsDouble(at);
at = repsDouble(at);
return vec2(dist, at);
}
vec2 mapCircleInvert(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
//at = at / PI;
//return uv;
len = 1.0 / len;
return vec2(sin(at)*len, cos(at)*len);
}
vec3 mapSphereInvert(vec3 uv)
{
float len = length(uv);
vec3 dir = normalize(uv);
len = 1.0 / len;
return dir * len;
}
// ---- shapes defined by distance fields ----
// See this site for a reference to more distance functions...
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
float length8(vec2 v)
{
return pow(pow(abs(v.x),8.0) + pow(abs(v.y), 8.0), 1.0/8.0);
}
// box distance field
float sdBox(vec3 p, vec3 radius)
{
vec3 dist = abs(p) - radius;
return min(max(dist.x, max(dist.y, dist.z)), 0.0) + length(max(dist, 0.0));
}
// Makes a warped torus that rotates around
float sdTorusWobble( vec3 p, vec2 t, float offset)
{
float a = atan(p.x, p.z);
float subs = 2.0;
a = sin(a*subs+localTime*4.0+offset*3.234567);
vec2 q = vec2(length(p.xz)-t.x-a*0.1,p.y);
return length8(q)-t.y;
}
// simple cylinder distance field
float cyl(vec2 p, float r)
{
return length(p) - r;
}
float glow = 0.0, glow2 = 0.0, glow3 = 0.0;
float pulse;
// This is the big money function that makes the crazy fractally shape
// The input is a position in space.
// The output is the distance to the nearest surface.
float DistanceToObject(vec3 p)
{
vec3 orig = p;
// Magically remap space to be in a spiral
p.yz = mapSpiralMirror(p.yz);
// Mix between spiral space and unwarped space. This changes the scene
// from the tunnel to the spiral.
p = mix(orig, p, animStructure);
// p = mix(p, orig, cos(localTime)*0.5+0.5);
// Cut out stuff outside of outer radius
const float outerRad = 3.5;
float lenXY = length(p.xy);
float final = lenXY - outerRad;
// Carve out inner radius
final = max(final, -(lenXY - (outerRad-0.65)));
// Slice the object in a 3d grid
float slice = 0.04;
vec3 grid = -abs(fract(p)-0.5) + slice;
//final = max(final, grid.x);
//final = max(final, grid.y);
final = max(final, grid.z);
// Carve out cylinders from the object on all 3 axis, scaled 3 times
// This gives it the fractal look.
vec3 rep = fract(p)-0.5;
float scale = 1.0;
float mult = 0.32;
for (int i = ZERO_TRICK; i < 3; i++)
{
float uglyDivider = max(1.0, float(i)); // wtf is this? My math sucks :(
// carve out 3 cylinders
float dist = cyl(rep.xz/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
dist = cyl(rep.xy/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
dist = cyl(rep.yz/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
// Scale and repeat.
scale *= 1.14+1.0;// + sin(localTime)*0.995;
rep = fract(rep*scale) - 0.5;
}
// Make radial struts that poke into the center of the spiral
vec3 sp = p;
sp.x = abs(sp.x)-5.4;
sp.z = fract(sp.z) - 0.5;
// Bad distance field on these makes them sometimes disappear. Math. :(
float struts = sdBox(sp+vec3(2.95, 0.1-sin(sp.x*2.0)*1.1, 0.0), vec3(1.5, 0.05, 0.02))*0.5;
//glow3 += (0.00005)/max(0.01, struts);
final = min(final, struts);
// Make spiral glows that rotate and pulse energy to the center
rep.yz = (fract(p.yz)-0.5);
rep.x = p.x;
scale = 1.14+1.0;
float jolt = max(0.0, sin(length(orig.yz) + localTime*20.0))*0.94;
jolt *= saturate(0.3-pulse);
float spiral = sdBox(RotateX(rep+vec3(-0.05,0.0,0.0), pulse), vec3(0.01+jolt,1.06, mult*0.01)/scale );
glow3 += (0.0018)/max(0.0025,spiral);
final = min(final, spiral + (1.0-animStructure) * 100.0);
// Make a warped torus that rotates around and glows orange
vec3 rp = p.xzy;
rp.x = -abs(rp.x);
rp.y = fract(rp.y) - 0.5;
float torus = sdTorusWobble(rp + vec3(3.0, 0.0, 0.0), vec2(0.2, 0.0003), p.z);
glow2 += 0.0015 / max(0.03, torus);
final = min(final, torus);
// Make the glowing tower in the center.
// This also gives a bit of a glow to everything.
glow += (0.02+abs(sin(orig.x-localTime*3.0)*0.15)*jolt )/length(orig.yz);
return final;
}
// Input is UV coordinate of pixel to render.
// Output is RGB color.
vec3 RayTrace(in vec2 fragCoord )
{
glow = 0.0;
glow2 = 0.0;
glow3 = 0.0;
// -------------------------------- animate ---------------------------------------
// Default to spiral shape
animStructure = 1.0;
// Make a cycling, clamped sin wave to animate the glow-spiral rotation.
float slt = sin(localTime);
float stepLike = pow(abs(slt), 0.75)*sign(slt);
stepLike = max(-1.0, min(1.0, stepLike*1.5));
pulse = stepLike*PI/4.0 + PI/4.0;
vec3 camPos, camUp, camLookat;
// ------------------- Set up the camera rays for ray marching --------------------
// Map uv to [-1.0..1.0]
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
#ifdef MANUAL_CAMERA
// Camera up vector.
camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0,0.0,0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0;// + localTime * 0.166;
float my=-iMouse.y/iResolution.y*10.0;// + sin(localTime * 0.3)*0.8+0.1;//*PI/2.01;
camPos = vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*8.35;
#else
// Do the camera fly-by animation and different scenes.
// Time variables for start and end of each scene
const float t0 = 0.0;
const float t1 = 9.0;
const float t2 = 16.0;
const float t3 = 24.0;
const float t4 = 40.0;
const float t5 = 48.0;
const float t6 = 70.0;
// Repeat the animation after time t6
localTime = fract(localTime / t6) * t6;
/*const float t0 = 0.0;
const float t1 = 0.0;
const float t2 = 0.0;
const float t3 = 0.0;
const float t4 = 0.0;
const float t5 = 0.0;
const float t6 = 18.0;*/
if (localTime < t1)
{
animStructure = 0.0;
float time = localTime - t0;
float alpha = time / (t1 - t0);
fade = saturate(time);
fade *= saturate(t1 - localTime);
camPos = vec3(56.0, -2.5, 1.5);
camPos.x -= alpha * 6.8;
camUp=vec3(0,1,0);
camLookat=vec3(50,0.0,0);
} else if (localTime < t2)
{
animStructure = 0.0;
float time = localTime - t1;
float alpha = time / (t2 - t1);
fade = saturate(time);
fade *= saturate(t2 - localTime);
camPos = vec3(12.0, 3.3, -0.5);
camPos.x -= smoothstep(0.0, 1.0, alpha) * 4.8;
camUp=vec3(0,1,0);
camLookat=vec3(0,5.5,-0.5);
} else if (localTime < t3)
{
animStructure = 1.0;
float time = localTime - t2;
float alpha = time / (t3 - t2);
fade = saturate(time);
fade *= saturate(t3 - localTime);
camPos = vec3(12.0, 6.3, -0.5);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 6.3;
camPos.z = sin(alpha*1.0) * 6.3;
camUp=normalize(vec3(0,1,-0.3 - alpha * 0.5));
camLookat=vec3(0,0.0,-0.5);
} else if (localTime < t4)
{
animStructure = 1.0;
float time = localTime - t3;
float alpha = time / (t4 - t3);
fade = saturate(time);
fade *= saturate(t4 - localTime);
camPos = vec3(12.0, 3.0, -2.6);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 6.5-alpha*0.25;
camPos.z += sin(alpha*1.0) * 6.5-alpha*0.25;
camUp=normalize(vec3(0,1,0.0));
camLookat=vec3(0,0.0,-0.0);
} else if (localTime < t5)
{
animStructure = 1.0;
float time = localTime - t4;
float alpha = time / (t5 - t4);
fade = saturate(time);
fade *= saturate(t5 - localTime);
camPos = vec3(0.0, -7.0, -0.9);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 1.5-alpha*1.5;
camPos.z += sin(alpha*1.0) * 1.5-alpha*1.5;
camUp=normalize(vec3(0,1,0.0));
camLookat=vec3(0,-3.0,-0.0);
} else if (localTime < t6)
{
float time = localTime - t5;
float alpha = time / (t6 - t5);
float smoothv = smoothstep(0.0, 1.0, saturate(alpha*1.8-0.1));
animStructure = 1.0-smoothv;
fade = saturate(time);
fade *= saturate(t6 - localTime);
camPos = vec3(10.0, -0.95+smoothv*1.0, 0.0);
camPos.x -= alpha * 6.8;
camUp=normalize(vec3(0,1.0-smoothv,0.0+smoothv));
camLookat=vec3(0,-0.0,-0.0);
}
#endif
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 rayVec = normalize(worldPix - camPos);
// ----------------------------- Ray march the scene ------------------------------
float dist = 1.0;
float t = 0.1 + Hash2d(uv)*0.1; // random dither-fade things close to the camera
const float maxDepth = 45.0; // farthest distance rays will travel
vec3 pos = vec3(0,0,0);
const float smallVal = 0.000625;
// ray marching time
for (int i = ZERO_TRICK; i < 210; i++) // This is the count of the max times the ray actually marches.
{
// Step along the ray. Switch x, y, and z because I messed up the orientation.
pos = (camPos + rayVec * t).yzx;
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry. The idea is that the
// distance field returns the distance to the closest object, and then
// we know we are safe to "march" along the ray by that much distance
// without hitting anything. We repeat this until we get really close
// and then break because we have effectively hit the object.
dist = DistanceToObject(pos);
// This makes the ray trace more precisely in the center so it will not miss the
// vertical glowy beam.
dist = min(dist, length(pos.yz));
t += dist;
// If we are very close to the object, let's call it a hit and exit this loop.
if ((t > maxDepth) || (abs(dist) < smallVal)) break;
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
float glowSave = glow;
float glow2Save = glow2;
float glow3Save = glow3;
vec3 sunDir = normalize(vec3(0.93, 1.0, -1.5));
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(smallVal, 0, 0);
vec3 normalU = vec3(dist - DistanceToObject(pos - smallVec.xyy),
dist - DistanceToObject(pos - smallVec.yxy),
dist - DistanceToObject(pos - smallVec.yyx));
vec3 normal = normalize(normalU);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff
float ambientS = 1.0;
ambientS *= saturate(DistanceToObject(pos + normal * 0.05)*20.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.1)*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2)*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4)*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8)*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6)*1.25*0.5);
//ambient *= saturate(DistanceToObject(pos + normal * 3.2)*1.25*0.25);
//ambient *= saturate(DistanceToObject(pos + normal * 6.4)*1.25*0.125);
//ambient = max(0.05, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// calculate the reflection vector for highlights
//vec3 ref = reflect(rayVec, normal);
// Trace a ray toward the sun for sun shadows
float sunShadow = 1.0;
float iter = 0.01;
vec3 nudgePos = pos + normal*0.002; // don't start tracing too close or inside the object
for (int i = ZERO_TRICK; i < 30; i++)
{
float tempDist = DistanceToObject(nudgePos + sunDir * iter);
sunShadow *= saturate(tempDist*150.0); // Shadow hardness
if (tempDist <= 0.0) break;
//iter *= 1.5; // constant is more reliable than distance-based
iter += max(0.01, tempDist)*1.0;
if (iter > 4.2) break;
}
sunShadow = saturate(sunShadow);
// make a few frequencies of noise to give it some texture
float n =0.0;
n += noise(pos*32.0);
n += noise(pos*64.0);
n += noise(pos*128.0);
n += noise(pos*256.0);
n += noise(pos*512.0);
n *= 0.8;
normal = normalize(normal + (n-2.0)*0.1);
// ------ Calculate texture color ------
vec3 texColor = vec3(0.95, 1.0, 1.0);
vec3 rust = vec3(0.65, 0.25, 0.1) - noise(pos*128.0);
// Call the function that makes rust stripes on the texture
texColor *= smoothstep(texColor, rust, vec3(saturate(RustNoise3D(pos*8.0))-0.2));
// apply noise
texColor *= vec3(1.0)*n*0.05;
texColor *= 0.7;
texColor = saturate(texColor);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(3.6) * saturate(dot(sunDir, normal)) * sunShadow;
// weighted average the near ambient occlusion with the far for just the right look
float ambientAvg = (ambient*3.0 + ambientS) * 0.25;
// a red and blue light coming from different directions
lightColor += (vec3(1.0, 0.2, 0.4) * saturate(-normal.z *0.5+0.5))*pow(ambientAvg, 0.35);
lightColor += (vec3(0.1, 0.5, 0.99) * saturate(normal.y *0.5+0.5))*pow(ambientAvg, 0.35);
// blue glow light coming from the glow in the middle
lightColor += vec3(0.3, 0.5, 0.9) * saturate(dot(-pos, normal))*pow(ambientS, 0.3);
lightColor *= 4.0;
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// sun reflection to make it look metal
//finalColor += vec3(1.0)*pow(n,4.0)* GetSunColorSmall(ref, sunDir) * sunShadow;// * ambientS;
// visualize length of gradient of distance field to check distance field correctness
//finalColor = vec3(0.5) * (length(normalU) / smallVec.x);
}
else
{
// Our ray trace hit nothing, so draw sky.
}
// add the ray marching glows
float center = length(pos.yz);
finalColor += vec3(0.3, 0.5, 0.9) * glowSave*1.2;
finalColor += vec3(0.9, 0.5, 0.3) * glow2*1.2;
finalColor += vec3(0.25, 0.29, 0.93) * glow3Save*2.0;
// vignette?
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
finalColor *= 1.0;// 1.3;
// output the final color without gamma correction - will do gamma later.
return vec3(clamp(finalColor, 0.0, 1.0)*saturate(fade+0.25));
}
#ifdef NON_REALTIME_HQ_RENDER
// This function breaks the image down into blocks and scans
// through them, rendering 1 block at a time. It's for non-
// realtime things that take a long time to render.
// This is the frame rate to render at. Too fast and you will
// miss some blocks.
const float blockRate = 20.0;
void BlockRender(in vec2 fragCoord)
{
// blockSize is how much it will try to render in 1 frame.
// adjust this smaller for more complex scenes, bigger for
// faster render times.
const float blockSize = 64.0;
// Make the block repeatedly scan across the image based on time.
float frame = floor(iTime * blockRate);
vec2 blockRes = floor(iResolution.xy / blockSize) + vec2(1.0);
// ugly bug with mod.
//float blockX = mod(frame, blockRes.x);
float blockX = fract(frame / blockRes.x) * blockRes.x;
//float blockY = mod(floor(frame / blockRes.x), blockRes.y);
float blockY = fract(floor(frame / blockRes.x) / blockRes.y) * blockRes.y;
// Don't draw anything outside the current block.
if ((fragCoord.x - blockX * blockSize >= blockSize) ||
(fragCoord.x - (blockX - 1.0) * blockSize < blockSize) ||
(fragCoord.y - blockY * blockSize >= blockSize) ||
(fragCoord.y - (blockY - 1.0) * blockSize < blockSize))
{
discard;
}
}
#endif
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
#ifdef NON_REALTIME_HQ_RENDER
// Optionally render a non-realtime scene with high quality
BlockRender(fragCoord);
#endif
// Do a multi-pass render
vec3 finalColor = vec3(0.0);
#ifdef NON_REALTIME_HQ_RENDER
for (float i = 0.0; i < antialiasingSamples; i++)
{
const float motionBlurLengthInSeconds = 1.0 / 60.0;
// Set this to the time in seconds of the frame to render.
localTime = frameToRenderHQ;
// This line will motion-blur the renders
localTime += Hash11(v21(fragCoord + seed)) * motionBlurLengthInSeconds;
// Jitter the pixel position so we get antialiasing when we do multiple passes.
vec2 jittered = fragCoord.xy + vec2(
Hash21(fragCoord + seed),
Hash21(fragCoord*7.234567 + seed)
);
// don't antialias if only 1 sample.
if (antialiasingSamples == 1.0) jittered = fragCoord;
// Accumulate one pass of raytracing into our pixel value
finalColor += RayTrace(jittered);
// Change the random seed for each pass.
seed *= 1.01234567;
}
// Average all accumulated pixel intensities
finalColor /= antialiasingSamples;
#else
// Regular real-time rendering
localTime = iTime;
finalColor = RayTrace(fragCoord);
#endif
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
6198,
6220,
6254,
6254,
6365
] | [
[
1278,
1307,
1326,
1326,
1371
],
[
1372,
1372,
1391,
1391,
1422
],
[
1423,
1423,
1446,
1446,
1482
],
[
1483,
1483,
1506,
1506,
1577
],
[
1578,
1578,
1600,
1600,
1687
],
[
1688,
1688,
1710,
1710,
1763
],
[
1764,
1764,
1787,
1787,
1860
],
[
1861,
1861,
1884,
1884,
1955
],
[
1956,
1956,
1979,
1979,
2065
],
[
2066,
2066,
2107,
2107,
2150
],
[
2188,
2188,
2212,
2212,
2485
],
[
2486,
2486,
2508,
2508,
3093
],
[
3123,
3123,
3146,
3146,
3175
],
[
3176,
3176,
3199,
3199,
3228
],
[
3229,
3229,
3254,
3254,
3283
],
[
3285,
3285,
3318,
3318,
3435
],
[
3436,
3436,
3469,
3469,
3585
],
[
3586,
3586,
3619,
3619,
3736
],
[
3738,
4267,
4294,
4294,
4859
],
[
4861,
4906,
4933,
4933,
4966
],
[
4967,
4967,
4992,
4992,
5025
],
[
5027,
5027,
5058,
5058,
5279
],
[
5281,
5281,
5306,
5306,
5594
],
[
5596,
5596,
5627,
5627,
5791
],
[
5793,
5793,
5824,
5824,
5927
],
[
5929,
6109,
6132,
6132,
6196
],
[
6198,
6220,
6254,
6254,
6365
],
[
6367,
6411,
6463,
6463,
6633
],
[
6635,
6669,
6697,
6697,
6725
],
[
6784,
6946,
6978,
6978,
9802
],
[
9804,
9874,
9909,
9909,
20901
],
[
22233,
22233,
22290,
22290,
23649
]
] | // box distance field
| float sdBox(vec3 p, vec3 radius)
{ |
vec3 dist = abs(p) - radius;
return min(max(dist.x, max(dist.y, dist.z)), 0.0) + length(max(dist, 0.0));
} | // box distance field
float sdBox(vec3 p, vec3 radius)
{ | 10 | 10 |
ltlSWf | otaviogood | 2015-08-25T04:26:33 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// ---------------- Config ----------------
// This is an option that lets you render high quality frames for screenshots. It enables
// stochastic antialiasing and motion blur automatically for any shader.
//#define NON_REALTIME_HQ_RENDER
const float frameToRenderHQ = 20.0; // Time in seconds of frame to render
const float antialiasingSamples = 16.0; // 16x antialiasing - too much might make the shader compiler angry.
//#define MANUAL_CAMERA
#define ZERO_TRICK max(0, -iFrame)
// --------------------------------------------------------
// These variables are for the non-realtime block renderer.
float localTime = 0.0;
float seed = 1.0;
// Animation variables
float animStructure = 1.0;
float fade = 1.0;
// ---- noise functions ----
float v31(vec3 a)
{
return a.x + a.y * 37.0 + a.z * 521.0;
}
float v21(vec2 a)
{
return a.x + a.y * 37.0;
}
float Hash11(float a)
{
return fract(sin(a)*10403.9);
}
float Hash21(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
vec2 Hash22(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(cos(f)*vec2(10003.579, 37049.7));
}
vec2 Hash12(float f)
{
return fract(cos(f)*vec2(10003.579, 37049.7));
}
float Hash1d(float u)
{
return fract(sin(u)*143.9); // scale this down to kill the jitters
}
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(sin(f)*110003.9);
}
float mixP(float f0, float f1, float a)
{
return mix(f0, f1, a*a*(3.0-2.0*a));
}
const vec2 zeroOne = vec2(0.0, 1.0);
float noise2d(vec2 uv)
{
vec2 fr = fract(uv.xy);
vec2 fl = floor(uv.xy);
float h00 = Hash2d(fl);
float h10 = Hash2d(fl + zeroOne.yx);
float h01 = Hash2d(fl + zeroOne);
float h11 = Hash2d(fl + zeroOne.yy);
return mixP(mixP(h00, h10, fr.x), mixP(h01, h11, fr.x), fr.y);
}
float noise(vec3 uv)
{
vec3 fr = fract(uv.xyz);
vec3 fl = floor(uv.xyz);
float h000 = Hash3d(fl);
float h100 = Hash3d(fl + zeroOne.yxx);
float h010 = Hash3d(fl + zeroOne.xyx);
float h110 = Hash3d(fl + zeroOne.yyx);
float h001 = Hash3d(fl + zeroOne.xxy);
float h101 = Hash3d(fl + zeroOne.yxy);
float h011 = Hash3d(fl + zeroOne.xyy);
float h111 = Hash3d(fl + zeroOne.yyy);
return mixP(
mixP(mixP(h000, h100, fr.x),
mixP(h010, h110, fr.x), fr.y),
mixP(mixP(h001, h101, fr.x),
mixP(h011, h111, fr.x), fr.y)
, fr.z);
}
const float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
// This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.71; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
// Total hack of the spiral noise function to get a rust look
float RustNoise3D(vec3 p)
{
float n = 0.0;
float iter = 1.0;
float pn = noise(p*0.125);
pn += noise(p*0.25)*0.5;
pn += noise(p*0.5)*0.25;
pn += noise(p*1.0)*0.125;
for (int i = ZERO_TRICK; i < 7; i++)
{
//n += (sin(p.y*iter) + cos(p.x*iter)) / iter;
float wave = saturate(cos(p.y*0.25 + pn) - 0.998);
wave *= noise(p * 0.125)*1016.0;
n += wave;
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.4733;
}
return n;
}
// ---- functions to remap / warp space ----
float repsDouble(float a)
{
return abs(a * 2.0 - 1.0);
}
vec2 repsDouble(vec2 a)
{
return abs(a * 2.0 - 1.0);
}
vec2 mapSpiralMirror(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
at = at / PI;
float dist = (fract(log(len)+at*0.5)-0.5) * 2.0;
at = repsDouble(at);
at = repsDouble(at);
return vec2(abs(dist), abs(at));
}
vec2 mapSpiral(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
at = at / PI;
float dist = (fract(log(len)+at*0.5)-0.5) * 2.0;
//dist += sin(at*32.0)*0.05;
// at is [-1..1]
// dist is [-1..1]
at = repsDouble(at);
at = repsDouble(at);
return vec2(dist, at);
}
vec2 mapCircleInvert(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
//at = at / PI;
//return uv;
len = 1.0 / len;
return vec2(sin(at)*len, cos(at)*len);
}
vec3 mapSphereInvert(vec3 uv)
{
float len = length(uv);
vec3 dir = normalize(uv);
len = 1.0 / len;
return dir * len;
}
// ---- shapes defined by distance fields ----
// See this site for a reference to more distance functions...
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
float length8(vec2 v)
{
return pow(pow(abs(v.x),8.0) + pow(abs(v.y), 8.0), 1.0/8.0);
}
// box distance field
float sdBox(vec3 p, vec3 radius)
{
vec3 dist = abs(p) - radius;
return min(max(dist.x, max(dist.y, dist.z)), 0.0) + length(max(dist, 0.0));
}
// Makes a warped torus that rotates around
float sdTorusWobble( vec3 p, vec2 t, float offset)
{
float a = atan(p.x, p.z);
float subs = 2.0;
a = sin(a*subs+localTime*4.0+offset*3.234567);
vec2 q = vec2(length(p.xz)-t.x-a*0.1,p.y);
return length8(q)-t.y;
}
// simple cylinder distance field
float cyl(vec2 p, float r)
{
return length(p) - r;
}
float glow = 0.0, glow2 = 0.0, glow3 = 0.0;
float pulse;
// This is the big money function that makes the crazy fractally shape
// The input is a position in space.
// The output is the distance to the nearest surface.
float DistanceToObject(vec3 p)
{
vec3 orig = p;
// Magically remap space to be in a spiral
p.yz = mapSpiralMirror(p.yz);
// Mix between spiral space and unwarped space. This changes the scene
// from the tunnel to the spiral.
p = mix(orig, p, animStructure);
// p = mix(p, orig, cos(localTime)*0.5+0.5);
// Cut out stuff outside of outer radius
const float outerRad = 3.5;
float lenXY = length(p.xy);
float final = lenXY - outerRad;
// Carve out inner radius
final = max(final, -(lenXY - (outerRad-0.65)));
// Slice the object in a 3d grid
float slice = 0.04;
vec3 grid = -abs(fract(p)-0.5) + slice;
//final = max(final, grid.x);
//final = max(final, grid.y);
final = max(final, grid.z);
// Carve out cylinders from the object on all 3 axis, scaled 3 times
// This gives it the fractal look.
vec3 rep = fract(p)-0.5;
float scale = 1.0;
float mult = 0.32;
for (int i = ZERO_TRICK; i < 3; i++)
{
float uglyDivider = max(1.0, float(i)); // wtf is this? My math sucks :(
// carve out 3 cylinders
float dist = cyl(rep.xz/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
dist = cyl(rep.xy/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
dist = cyl(rep.yz/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
// Scale and repeat.
scale *= 1.14+1.0;// + sin(localTime)*0.995;
rep = fract(rep*scale) - 0.5;
}
// Make radial struts that poke into the center of the spiral
vec3 sp = p;
sp.x = abs(sp.x)-5.4;
sp.z = fract(sp.z) - 0.5;
// Bad distance field on these makes them sometimes disappear. Math. :(
float struts = sdBox(sp+vec3(2.95, 0.1-sin(sp.x*2.0)*1.1, 0.0), vec3(1.5, 0.05, 0.02))*0.5;
//glow3 += (0.00005)/max(0.01, struts);
final = min(final, struts);
// Make spiral glows that rotate and pulse energy to the center
rep.yz = (fract(p.yz)-0.5);
rep.x = p.x;
scale = 1.14+1.0;
float jolt = max(0.0, sin(length(orig.yz) + localTime*20.0))*0.94;
jolt *= saturate(0.3-pulse);
float spiral = sdBox(RotateX(rep+vec3(-0.05,0.0,0.0), pulse), vec3(0.01+jolt,1.06, mult*0.01)/scale );
glow3 += (0.0018)/max(0.0025,spiral);
final = min(final, spiral + (1.0-animStructure) * 100.0);
// Make a warped torus that rotates around and glows orange
vec3 rp = p.xzy;
rp.x = -abs(rp.x);
rp.y = fract(rp.y) - 0.5;
float torus = sdTorusWobble(rp + vec3(3.0, 0.0, 0.0), vec2(0.2, 0.0003), p.z);
glow2 += 0.0015 / max(0.03, torus);
final = min(final, torus);
// Make the glowing tower in the center.
// This also gives a bit of a glow to everything.
glow += (0.02+abs(sin(orig.x-localTime*3.0)*0.15)*jolt )/length(orig.yz);
return final;
}
// Input is UV coordinate of pixel to render.
// Output is RGB color.
vec3 RayTrace(in vec2 fragCoord )
{
glow = 0.0;
glow2 = 0.0;
glow3 = 0.0;
// -------------------------------- animate ---------------------------------------
// Default to spiral shape
animStructure = 1.0;
// Make a cycling, clamped sin wave to animate the glow-spiral rotation.
float slt = sin(localTime);
float stepLike = pow(abs(slt), 0.75)*sign(slt);
stepLike = max(-1.0, min(1.0, stepLike*1.5));
pulse = stepLike*PI/4.0 + PI/4.0;
vec3 camPos, camUp, camLookat;
// ------------------- Set up the camera rays for ray marching --------------------
// Map uv to [-1.0..1.0]
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
#ifdef MANUAL_CAMERA
// Camera up vector.
camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0,0.0,0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0;// + localTime * 0.166;
float my=-iMouse.y/iResolution.y*10.0;// + sin(localTime * 0.3)*0.8+0.1;//*PI/2.01;
camPos = vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*8.35;
#else
// Do the camera fly-by animation and different scenes.
// Time variables for start and end of each scene
const float t0 = 0.0;
const float t1 = 9.0;
const float t2 = 16.0;
const float t3 = 24.0;
const float t4 = 40.0;
const float t5 = 48.0;
const float t6 = 70.0;
// Repeat the animation after time t6
localTime = fract(localTime / t6) * t6;
/*const float t0 = 0.0;
const float t1 = 0.0;
const float t2 = 0.0;
const float t3 = 0.0;
const float t4 = 0.0;
const float t5 = 0.0;
const float t6 = 18.0;*/
if (localTime < t1)
{
animStructure = 0.0;
float time = localTime - t0;
float alpha = time / (t1 - t0);
fade = saturate(time);
fade *= saturate(t1 - localTime);
camPos = vec3(56.0, -2.5, 1.5);
camPos.x -= alpha * 6.8;
camUp=vec3(0,1,0);
camLookat=vec3(50,0.0,0);
} else if (localTime < t2)
{
animStructure = 0.0;
float time = localTime - t1;
float alpha = time / (t2 - t1);
fade = saturate(time);
fade *= saturate(t2 - localTime);
camPos = vec3(12.0, 3.3, -0.5);
camPos.x -= smoothstep(0.0, 1.0, alpha) * 4.8;
camUp=vec3(0,1,0);
camLookat=vec3(0,5.5,-0.5);
} else if (localTime < t3)
{
animStructure = 1.0;
float time = localTime - t2;
float alpha = time / (t3 - t2);
fade = saturate(time);
fade *= saturate(t3 - localTime);
camPos = vec3(12.0, 6.3, -0.5);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 6.3;
camPos.z = sin(alpha*1.0) * 6.3;
camUp=normalize(vec3(0,1,-0.3 - alpha * 0.5));
camLookat=vec3(0,0.0,-0.5);
} else if (localTime < t4)
{
animStructure = 1.0;
float time = localTime - t3;
float alpha = time / (t4 - t3);
fade = saturate(time);
fade *= saturate(t4 - localTime);
camPos = vec3(12.0, 3.0, -2.6);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 6.5-alpha*0.25;
camPos.z += sin(alpha*1.0) * 6.5-alpha*0.25;
camUp=normalize(vec3(0,1,0.0));
camLookat=vec3(0,0.0,-0.0);
} else if (localTime < t5)
{
animStructure = 1.0;
float time = localTime - t4;
float alpha = time / (t5 - t4);
fade = saturate(time);
fade *= saturate(t5 - localTime);
camPos = vec3(0.0, -7.0, -0.9);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 1.5-alpha*1.5;
camPos.z += sin(alpha*1.0) * 1.5-alpha*1.5;
camUp=normalize(vec3(0,1,0.0));
camLookat=vec3(0,-3.0,-0.0);
} else if (localTime < t6)
{
float time = localTime - t5;
float alpha = time / (t6 - t5);
float smoothv = smoothstep(0.0, 1.0, saturate(alpha*1.8-0.1));
animStructure = 1.0-smoothv;
fade = saturate(time);
fade *= saturate(t6 - localTime);
camPos = vec3(10.0, -0.95+smoothv*1.0, 0.0);
camPos.x -= alpha * 6.8;
camUp=normalize(vec3(0,1.0-smoothv,0.0+smoothv));
camLookat=vec3(0,-0.0,-0.0);
}
#endif
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 rayVec = normalize(worldPix - camPos);
// ----------------------------- Ray march the scene ------------------------------
float dist = 1.0;
float t = 0.1 + Hash2d(uv)*0.1; // random dither-fade things close to the camera
const float maxDepth = 45.0; // farthest distance rays will travel
vec3 pos = vec3(0,0,0);
const float smallVal = 0.000625;
// ray marching time
for (int i = ZERO_TRICK; i < 210; i++) // This is the count of the max times the ray actually marches.
{
// Step along the ray. Switch x, y, and z because I messed up the orientation.
pos = (camPos + rayVec * t).yzx;
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry. The idea is that the
// distance field returns the distance to the closest object, and then
// we know we are safe to "march" along the ray by that much distance
// without hitting anything. We repeat this until we get really close
// and then break because we have effectively hit the object.
dist = DistanceToObject(pos);
// This makes the ray trace more precisely in the center so it will not miss the
// vertical glowy beam.
dist = min(dist, length(pos.yz));
t += dist;
// If we are very close to the object, let's call it a hit and exit this loop.
if ((t > maxDepth) || (abs(dist) < smallVal)) break;
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
float glowSave = glow;
float glow2Save = glow2;
float glow3Save = glow3;
vec3 sunDir = normalize(vec3(0.93, 1.0, -1.5));
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(smallVal, 0, 0);
vec3 normalU = vec3(dist - DistanceToObject(pos - smallVec.xyy),
dist - DistanceToObject(pos - smallVec.yxy),
dist - DistanceToObject(pos - smallVec.yyx));
vec3 normal = normalize(normalU);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff
float ambientS = 1.0;
ambientS *= saturate(DistanceToObject(pos + normal * 0.05)*20.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.1)*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2)*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4)*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8)*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6)*1.25*0.5);
//ambient *= saturate(DistanceToObject(pos + normal * 3.2)*1.25*0.25);
//ambient *= saturate(DistanceToObject(pos + normal * 6.4)*1.25*0.125);
//ambient = max(0.05, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// calculate the reflection vector for highlights
//vec3 ref = reflect(rayVec, normal);
// Trace a ray toward the sun for sun shadows
float sunShadow = 1.0;
float iter = 0.01;
vec3 nudgePos = pos + normal*0.002; // don't start tracing too close or inside the object
for (int i = ZERO_TRICK; i < 30; i++)
{
float tempDist = DistanceToObject(nudgePos + sunDir * iter);
sunShadow *= saturate(tempDist*150.0); // Shadow hardness
if (tempDist <= 0.0) break;
//iter *= 1.5; // constant is more reliable than distance-based
iter += max(0.01, tempDist)*1.0;
if (iter > 4.2) break;
}
sunShadow = saturate(sunShadow);
// make a few frequencies of noise to give it some texture
float n =0.0;
n += noise(pos*32.0);
n += noise(pos*64.0);
n += noise(pos*128.0);
n += noise(pos*256.0);
n += noise(pos*512.0);
n *= 0.8;
normal = normalize(normal + (n-2.0)*0.1);
// ------ Calculate texture color ------
vec3 texColor = vec3(0.95, 1.0, 1.0);
vec3 rust = vec3(0.65, 0.25, 0.1) - noise(pos*128.0);
// Call the function that makes rust stripes on the texture
texColor *= smoothstep(texColor, rust, vec3(saturate(RustNoise3D(pos*8.0))-0.2));
// apply noise
texColor *= vec3(1.0)*n*0.05;
texColor *= 0.7;
texColor = saturate(texColor);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(3.6) * saturate(dot(sunDir, normal)) * sunShadow;
// weighted average the near ambient occlusion with the far for just the right look
float ambientAvg = (ambient*3.0 + ambientS) * 0.25;
// a red and blue light coming from different directions
lightColor += (vec3(1.0, 0.2, 0.4) * saturate(-normal.z *0.5+0.5))*pow(ambientAvg, 0.35);
lightColor += (vec3(0.1, 0.5, 0.99) * saturate(normal.y *0.5+0.5))*pow(ambientAvg, 0.35);
// blue glow light coming from the glow in the middle
lightColor += vec3(0.3, 0.5, 0.9) * saturate(dot(-pos, normal))*pow(ambientS, 0.3);
lightColor *= 4.0;
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// sun reflection to make it look metal
//finalColor += vec3(1.0)*pow(n,4.0)* GetSunColorSmall(ref, sunDir) * sunShadow;// * ambientS;
// visualize length of gradient of distance field to check distance field correctness
//finalColor = vec3(0.5) * (length(normalU) / smallVec.x);
}
else
{
// Our ray trace hit nothing, so draw sky.
}
// add the ray marching glows
float center = length(pos.yz);
finalColor += vec3(0.3, 0.5, 0.9) * glowSave*1.2;
finalColor += vec3(0.9, 0.5, 0.3) * glow2*1.2;
finalColor += vec3(0.25, 0.29, 0.93) * glow3Save*2.0;
// vignette?
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
finalColor *= 1.0;// 1.3;
// output the final color without gamma correction - will do gamma later.
return vec3(clamp(finalColor, 0.0, 1.0)*saturate(fade+0.25));
}
#ifdef NON_REALTIME_HQ_RENDER
// This function breaks the image down into blocks and scans
// through them, rendering 1 block at a time. It's for non-
// realtime things that take a long time to render.
// This is the frame rate to render at. Too fast and you will
// miss some blocks.
const float blockRate = 20.0;
void BlockRender(in vec2 fragCoord)
{
// blockSize is how much it will try to render in 1 frame.
// adjust this smaller for more complex scenes, bigger for
// faster render times.
const float blockSize = 64.0;
// Make the block repeatedly scan across the image based on time.
float frame = floor(iTime * blockRate);
vec2 blockRes = floor(iResolution.xy / blockSize) + vec2(1.0);
// ugly bug with mod.
//float blockX = mod(frame, blockRes.x);
float blockX = fract(frame / blockRes.x) * blockRes.x;
//float blockY = mod(floor(frame / blockRes.x), blockRes.y);
float blockY = fract(floor(frame / blockRes.x) / blockRes.y) * blockRes.y;
// Don't draw anything outside the current block.
if ((fragCoord.x - blockX * blockSize >= blockSize) ||
(fragCoord.x - (blockX - 1.0) * blockSize < blockSize) ||
(fragCoord.y - blockY * blockSize >= blockSize) ||
(fragCoord.y - (blockY - 1.0) * blockSize < blockSize))
{
discard;
}
}
#endif
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
#ifdef NON_REALTIME_HQ_RENDER
// Optionally render a non-realtime scene with high quality
BlockRender(fragCoord);
#endif
// Do a multi-pass render
vec3 finalColor = vec3(0.0);
#ifdef NON_REALTIME_HQ_RENDER
for (float i = 0.0; i < antialiasingSamples; i++)
{
const float motionBlurLengthInSeconds = 1.0 / 60.0;
// Set this to the time in seconds of the frame to render.
localTime = frameToRenderHQ;
// This line will motion-blur the renders
localTime += Hash11(v21(fragCoord + seed)) * motionBlurLengthInSeconds;
// Jitter the pixel position so we get antialiasing when we do multiple passes.
vec2 jittered = fragCoord.xy + vec2(
Hash21(fragCoord + seed),
Hash21(fragCoord*7.234567 + seed)
);
// don't antialias if only 1 sample.
if (antialiasingSamples == 1.0) jittered = fragCoord;
// Accumulate one pass of raytracing into our pixel value
finalColor += RayTrace(jittered);
// Change the random seed for each pass.
seed *= 1.01234567;
}
// Average all accumulated pixel intensities
finalColor /= antialiasingSamples;
#else
// Regular real-time rendering
localTime = iTime;
finalColor = RayTrace(fragCoord);
#endif
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
6367,
6411,
6463,
6463,
6633
] | [
[
1278,
1307,
1326,
1326,
1371
],
[
1372,
1372,
1391,
1391,
1422
],
[
1423,
1423,
1446,
1446,
1482
],
[
1483,
1483,
1506,
1506,
1577
],
[
1578,
1578,
1600,
1600,
1687
],
[
1688,
1688,
1710,
1710,
1763
],
[
1764,
1764,
1787,
1787,
1860
],
[
1861,
1861,
1884,
1884,
1955
],
[
1956,
1956,
1979,
1979,
2065
],
[
2066,
2066,
2107,
2107,
2150
],
[
2188,
2188,
2212,
2212,
2485
],
[
2486,
2486,
2508,
2508,
3093
],
[
3123,
3123,
3146,
3146,
3175
],
[
3176,
3176,
3199,
3199,
3228
],
[
3229,
3229,
3254,
3254,
3283
],
[
3285,
3285,
3318,
3318,
3435
],
[
3436,
3436,
3469,
3469,
3585
],
[
3586,
3586,
3619,
3619,
3736
],
[
3738,
4267,
4294,
4294,
4859
],
[
4861,
4906,
4933,
4933,
4966
],
[
4967,
4967,
4992,
4992,
5025
],
[
5027,
5027,
5058,
5058,
5279
],
[
5281,
5281,
5306,
5306,
5594
],
[
5596,
5596,
5627,
5627,
5791
],
[
5793,
5793,
5824,
5824,
5927
],
[
5929,
6109,
6132,
6132,
6196
],
[
6198,
6220,
6254,
6254,
6365
],
[
6367,
6411,
6463,
6463,
6633
],
[
6635,
6669,
6697,
6697,
6725
],
[
6784,
6946,
6978,
6978,
9802
],
[
9804,
9874,
9909,
9909,
20901
],
[
22233,
22233,
22290,
22290,
23649
]
] | // Makes a warped torus that rotates around
| float sdTorusWobble( vec3 p, vec2 t, float offset)
{ |
float a = atan(p.x, p.z);
float subs = 2.0;
a = sin(a*subs+localTime*4.0+offset*3.234567);
vec2 q = vec2(length(p.xz)-t.x-a*0.1,p.y);
return length8(q)-t.y;
} | // Makes a warped torus that rotates around
float sdTorusWobble( vec3 p, vec2 t, float offset)
{ | 1 | 1 |
ltlSWf | otaviogood | 2015-08-25T04:26:33 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// ---------------- Config ----------------
// This is an option that lets you render high quality frames for screenshots. It enables
// stochastic antialiasing and motion blur automatically for any shader.
//#define NON_REALTIME_HQ_RENDER
const float frameToRenderHQ = 20.0; // Time in seconds of frame to render
const float antialiasingSamples = 16.0; // 16x antialiasing - too much might make the shader compiler angry.
//#define MANUAL_CAMERA
#define ZERO_TRICK max(0, -iFrame)
// --------------------------------------------------------
// These variables are for the non-realtime block renderer.
float localTime = 0.0;
float seed = 1.0;
// Animation variables
float animStructure = 1.0;
float fade = 1.0;
// ---- noise functions ----
float v31(vec3 a)
{
return a.x + a.y * 37.0 + a.z * 521.0;
}
float v21(vec2 a)
{
return a.x + a.y * 37.0;
}
float Hash11(float a)
{
return fract(sin(a)*10403.9);
}
float Hash21(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
vec2 Hash22(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(cos(f)*vec2(10003.579, 37049.7));
}
vec2 Hash12(float f)
{
return fract(cos(f)*vec2(10003.579, 37049.7));
}
float Hash1d(float u)
{
return fract(sin(u)*143.9); // scale this down to kill the jitters
}
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(sin(f)*110003.9);
}
float mixP(float f0, float f1, float a)
{
return mix(f0, f1, a*a*(3.0-2.0*a));
}
const vec2 zeroOne = vec2(0.0, 1.0);
float noise2d(vec2 uv)
{
vec2 fr = fract(uv.xy);
vec2 fl = floor(uv.xy);
float h00 = Hash2d(fl);
float h10 = Hash2d(fl + zeroOne.yx);
float h01 = Hash2d(fl + zeroOne);
float h11 = Hash2d(fl + zeroOne.yy);
return mixP(mixP(h00, h10, fr.x), mixP(h01, h11, fr.x), fr.y);
}
float noise(vec3 uv)
{
vec3 fr = fract(uv.xyz);
vec3 fl = floor(uv.xyz);
float h000 = Hash3d(fl);
float h100 = Hash3d(fl + zeroOne.yxx);
float h010 = Hash3d(fl + zeroOne.xyx);
float h110 = Hash3d(fl + zeroOne.yyx);
float h001 = Hash3d(fl + zeroOne.xxy);
float h101 = Hash3d(fl + zeroOne.yxy);
float h011 = Hash3d(fl + zeroOne.xyy);
float h111 = Hash3d(fl + zeroOne.yyy);
return mixP(
mixP(mixP(h000, h100, fr.x),
mixP(h010, h110, fr.x), fr.y),
mixP(mixP(h001, h101, fr.x),
mixP(h011, h111, fr.x), fr.y)
, fr.z);
}
const float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
vec3 RotateX(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(v.x, cos * v.y + sin * v.z, -sin * v.y + cos * v.z);
}
vec3 RotateY(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x - sin * v.z, v.y, sin * v.x + cos * v.z);
}
vec3 RotateZ(vec3 v, float rad)
{
float cos = cos(rad);
float sin = sin(rad);
return vec3(cos * v.x + sin * v.y, -sin * v.x + cos * v.y, v.z);
}
// This spiral noise works by successively adding and rotating sin waves while increasing frequency.
// It should work the same on all computers since it's not based on a hash function like some other noises.
// It can be much faster than other noise functions if you're ok with some repetition.
const float nudge = 0.71; // size of perpendicular vector
float normalizer = 1.0 / sqrt(1.0 + nudge*nudge); // pythagorean theorem on that perpendicular to maintain scale
// Total hack of the spiral noise function to get a rust look
float RustNoise3D(vec3 p)
{
float n = 0.0;
float iter = 1.0;
float pn = noise(p*0.125);
pn += noise(p*0.25)*0.5;
pn += noise(p*0.5)*0.25;
pn += noise(p*1.0)*0.125;
for (int i = ZERO_TRICK; i < 7; i++)
{
//n += (sin(p.y*iter) + cos(p.x*iter)) / iter;
float wave = saturate(cos(p.y*0.25 + pn) - 0.998);
wave *= noise(p * 0.125)*1016.0;
n += wave;
p.xy += vec2(p.y, -p.x) * nudge;
p.xy *= normalizer;
p.xz += vec2(p.z, -p.x) * nudge;
p.xz *= normalizer;
iter *= 1.4733;
}
return n;
}
// ---- functions to remap / warp space ----
float repsDouble(float a)
{
return abs(a * 2.0 - 1.0);
}
vec2 repsDouble(vec2 a)
{
return abs(a * 2.0 - 1.0);
}
vec2 mapSpiralMirror(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
at = at / PI;
float dist = (fract(log(len)+at*0.5)-0.5) * 2.0;
at = repsDouble(at);
at = repsDouble(at);
return vec2(abs(dist), abs(at));
}
vec2 mapSpiral(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
at = at / PI;
float dist = (fract(log(len)+at*0.5)-0.5) * 2.0;
//dist += sin(at*32.0)*0.05;
// at is [-1..1]
// dist is [-1..1]
at = repsDouble(at);
at = repsDouble(at);
return vec2(dist, at);
}
vec2 mapCircleInvert(vec2 uv)
{
float len = length(uv);
float at = atan(uv.x, uv.y);
//at = at / PI;
//return uv;
len = 1.0 / len;
return vec2(sin(at)*len, cos(at)*len);
}
vec3 mapSphereInvert(vec3 uv)
{
float len = length(uv);
vec3 dir = normalize(uv);
len = 1.0 / len;
return dir * len;
}
// ---- shapes defined by distance fields ----
// See this site for a reference to more distance functions...
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
float length8(vec2 v)
{
return pow(pow(abs(v.x),8.0) + pow(abs(v.y), 8.0), 1.0/8.0);
}
// box distance field
float sdBox(vec3 p, vec3 radius)
{
vec3 dist = abs(p) - radius;
return min(max(dist.x, max(dist.y, dist.z)), 0.0) + length(max(dist, 0.0));
}
// Makes a warped torus that rotates around
float sdTorusWobble( vec3 p, vec2 t, float offset)
{
float a = atan(p.x, p.z);
float subs = 2.0;
a = sin(a*subs+localTime*4.0+offset*3.234567);
vec2 q = vec2(length(p.xz)-t.x-a*0.1,p.y);
return length8(q)-t.y;
}
// simple cylinder distance field
float cyl(vec2 p, float r)
{
return length(p) - r;
}
float glow = 0.0, glow2 = 0.0, glow3 = 0.0;
float pulse;
// This is the big money function that makes the crazy fractally shape
// The input is a position in space.
// The output is the distance to the nearest surface.
float DistanceToObject(vec3 p)
{
vec3 orig = p;
// Magically remap space to be in a spiral
p.yz = mapSpiralMirror(p.yz);
// Mix between spiral space and unwarped space. This changes the scene
// from the tunnel to the spiral.
p = mix(orig, p, animStructure);
// p = mix(p, orig, cos(localTime)*0.5+0.5);
// Cut out stuff outside of outer radius
const float outerRad = 3.5;
float lenXY = length(p.xy);
float final = lenXY - outerRad;
// Carve out inner radius
final = max(final, -(lenXY - (outerRad-0.65)));
// Slice the object in a 3d grid
float slice = 0.04;
vec3 grid = -abs(fract(p)-0.5) + slice;
//final = max(final, grid.x);
//final = max(final, grid.y);
final = max(final, grid.z);
// Carve out cylinders from the object on all 3 axis, scaled 3 times
// This gives it the fractal look.
vec3 rep = fract(p)-0.5;
float scale = 1.0;
float mult = 0.32;
for (int i = ZERO_TRICK; i < 3; i++)
{
float uglyDivider = max(1.0, float(i)); // wtf is this? My math sucks :(
// carve out 3 cylinders
float dist = cyl(rep.xz/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
dist = cyl(rep.xy/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
dist = cyl(rep.yz/scale, mult/scale)/uglyDivider;
final = max(final, -dist);
// Scale and repeat.
scale *= 1.14+1.0;// + sin(localTime)*0.995;
rep = fract(rep*scale) - 0.5;
}
// Make radial struts that poke into the center of the spiral
vec3 sp = p;
sp.x = abs(sp.x)-5.4;
sp.z = fract(sp.z) - 0.5;
// Bad distance field on these makes them sometimes disappear. Math. :(
float struts = sdBox(sp+vec3(2.95, 0.1-sin(sp.x*2.0)*1.1, 0.0), vec3(1.5, 0.05, 0.02))*0.5;
//glow3 += (0.00005)/max(0.01, struts);
final = min(final, struts);
// Make spiral glows that rotate and pulse energy to the center
rep.yz = (fract(p.yz)-0.5);
rep.x = p.x;
scale = 1.14+1.0;
float jolt = max(0.0, sin(length(orig.yz) + localTime*20.0))*0.94;
jolt *= saturate(0.3-pulse);
float spiral = sdBox(RotateX(rep+vec3(-0.05,0.0,0.0), pulse), vec3(0.01+jolt,1.06, mult*0.01)/scale );
glow3 += (0.0018)/max(0.0025,spiral);
final = min(final, spiral + (1.0-animStructure) * 100.0);
// Make a warped torus that rotates around and glows orange
vec3 rp = p.xzy;
rp.x = -abs(rp.x);
rp.y = fract(rp.y) - 0.5;
float torus = sdTorusWobble(rp + vec3(3.0, 0.0, 0.0), vec2(0.2, 0.0003), p.z);
glow2 += 0.0015 / max(0.03, torus);
final = min(final, torus);
// Make the glowing tower in the center.
// This also gives a bit of a glow to everything.
glow += (0.02+abs(sin(orig.x-localTime*3.0)*0.15)*jolt )/length(orig.yz);
return final;
}
// Input is UV coordinate of pixel to render.
// Output is RGB color.
vec3 RayTrace(in vec2 fragCoord )
{
glow = 0.0;
glow2 = 0.0;
glow3 = 0.0;
// -------------------------------- animate ---------------------------------------
// Default to spiral shape
animStructure = 1.0;
// Make a cycling, clamped sin wave to animate the glow-spiral rotation.
float slt = sin(localTime);
float stepLike = pow(abs(slt), 0.75)*sign(slt);
stepLike = max(-1.0, min(1.0, stepLike*1.5));
pulse = stepLike*PI/4.0 + PI/4.0;
vec3 camPos, camUp, camLookat;
// ------------------- Set up the camera rays for ray marching --------------------
// Map uv to [-1.0..1.0]
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
#ifdef MANUAL_CAMERA
// Camera up vector.
camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0,0.0,0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0;// + localTime * 0.166;
float my=-iMouse.y/iResolution.y*10.0;// + sin(localTime * 0.3)*0.8+0.1;//*PI/2.01;
camPos = vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*8.35;
#else
// Do the camera fly-by animation and different scenes.
// Time variables for start and end of each scene
const float t0 = 0.0;
const float t1 = 9.0;
const float t2 = 16.0;
const float t3 = 24.0;
const float t4 = 40.0;
const float t5 = 48.0;
const float t6 = 70.0;
// Repeat the animation after time t6
localTime = fract(localTime / t6) * t6;
/*const float t0 = 0.0;
const float t1 = 0.0;
const float t2 = 0.0;
const float t3 = 0.0;
const float t4 = 0.0;
const float t5 = 0.0;
const float t6 = 18.0;*/
if (localTime < t1)
{
animStructure = 0.0;
float time = localTime - t0;
float alpha = time / (t1 - t0);
fade = saturate(time);
fade *= saturate(t1 - localTime);
camPos = vec3(56.0, -2.5, 1.5);
camPos.x -= alpha * 6.8;
camUp=vec3(0,1,0);
camLookat=vec3(50,0.0,0);
} else if (localTime < t2)
{
animStructure = 0.0;
float time = localTime - t1;
float alpha = time / (t2 - t1);
fade = saturate(time);
fade *= saturate(t2 - localTime);
camPos = vec3(12.0, 3.3, -0.5);
camPos.x -= smoothstep(0.0, 1.0, alpha) * 4.8;
camUp=vec3(0,1,0);
camLookat=vec3(0,5.5,-0.5);
} else if (localTime < t3)
{
animStructure = 1.0;
float time = localTime - t2;
float alpha = time / (t3 - t2);
fade = saturate(time);
fade *= saturate(t3 - localTime);
camPos = vec3(12.0, 6.3, -0.5);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 6.3;
camPos.z = sin(alpha*1.0) * 6.3;
camUp=normalize(vec3(0,1,-0.3 - alpha * 0.5));
camLookat=vec3(0,0.0,-0.5);
} else if (localTime < t4)
{
animStructure = 1.0;
float time = localTime - t3;
float alpha = time / (t4 - t3);
fade = saturate(time);
fade *= saturate(t4 - localTime);
camPos = vec3(12.0, 3.0, -2.6);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 6.5-alpha*0.25;
camPos.z += sin(alpha*1.0) * 6.5-alpha*0.25;
camUp=normalize(vec3(0,1,0.0));
camLookat=vec3(0,0.0,-0.0);
} else if (localTime < t5)
{
animStructure = 1.0;
float time = localTime - t4;
float alpha = time / (t5 - t4);
fade = saturate(time);
fade *= saturate(t5 - localTime);
camPos = vec3(0.0, -7.0, -0.9);
camPos.y -= alpha * 1.8;
camPos.x = cos(alpha*1.0) * 1.5-alpha*1.5;
camPos.z += sin(alpha*1.0) * 1.5-alpha*1.5;
camUp=normalize(vec3(0,1,0.0));
camLookat=vec3(0,-3.0,-0.0);
} else if (localTime < t6)
{
float time = localTime - t5;
float alpha = time / (t6 - t5);
float smoothv = smoothstep(0.0, 1.0, saturate(alpha*1.8-0.1));
animStructure = 1.0-smoothv;
fade = saturate(time);
fade *= saturate(t6 - localTime);
camPos = vec3(10.0, -0.95+smoothv*1.0, 0.0);
camPos.x -= alpha * 6.8;
camUp=normalize(vec3(0,1.0-smoothv,0.0+smoothv));
camLookat=vec3(0,-0.0,-0.0);
}
#endif
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 rayVec = normalize(worldPix - camPos);
// ----------------------------- Ray march the scene ------------------------------
float dist = 1.0;
float t = 0.1 + Hash2d(uv)*0.1; // random dither-fade things close to the camera
const float maxDepth = 45.0; // farthest distance rays will travel
vec3 pos = vec3(0,0,0);
const float smallVal = 0.000625;
// ray marching time
for (int i = ZERO_TRICK; i < 210; i++) // This is the count of the max times the ray actually marches.
{
// Step along the ray. Switch x, y, and z because I messed up the orientation.
pos = (camPos + rayVec * t).yzx;
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry. The idea is that the
// distance field returns the distance to the closest object, and then
// we know we are safe to "march" along the ray by that much distance
// without hitting anything. We repeat this until we get really close
// and then break because we have effectively hit the object.
dist = DistanceToObject(pos);
// This makes the ray trace more precisely in the center so it will not miss the
// vertical glowy beam.
dist = min(dist, length(pos.yz));
t += dist;
// If we are very close to the object, let's call it a hit and exit this loop.
if ((t > maxDepth) || (abs(dist) < smallVal)) break;
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
float glowSave = glow;
float glow2Save = glow2;
float glow3Save = glow3;
vec3 sunDir = normalize(vec3(0.93, 1.0, -1.5));
vec3 finalColor = vec3(0.0);
// If a ray actually hit the object, let's light it.
if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(smallVal, 0, 0);
vec3 normalU = vec3(dist - DistanceToObject(pos - smallVec.xyy),
dist - DistanceToObject(pos - smallVec.yxy),
dist - DistanceToObject(pos - smallVec.yyx));
vec3 normal = normalize(normalU);
// calculate 2 ambient occlusion values. One for global stuff and one
// for local stuff
float ambientS = 1.0;
ambientS *= saturate(DistanceToObject(pos + normal * 0.05)*20.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.1)*10.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.2)*5.0);
ambientS *= saturate(DistanceToObject(pos + normal * 0.4)*2.5);
ambientS *= saturate(DistanceToObject(pos + normal * 0.8)*1.25);
float ambient = ambientS * saturate(DistanceToObject(pos + normal * 1.6)*1.25*0.5);
//ambient *= saturate(DistanceToObject(pos + normal * 3.2)*1.25*0.25);
//ambient *= saturate(DistanceToObject(pos + normal * 6.4)*1.25*0.125);
//ambient = max(0.05, pow(ambient, 0.3)); // tone down ambient with a pow and min clamp it.
ambient = saturate(ambient);
// calculate the reflection vector for highlights
//vec3 ref = reflect(rayVec, normal);
// Trace a ray toward the sun for sun shadows
float sunShadow = 1.0;
float iter = 0.01;
vec3 nudgePos = pos + normal*0.002; // don't start tracing too close or inside the object
for (int i = ZERO_TRICK; i < 30; i++)
{
float tempDist = DistanceToObject(nudgePos + sunDir * iter);
sunShadow *= saturate(tempDist*150.0); // Shadow hardness
if (tempDist <= 0.0) break;
//iter *= 1.5; // constant is more reliable than distance-based
iter += max(0.01, tempDist)*1.0;
if (iter > 4.2) break;
}
sunShadow = saturate(sunShadow);
// make a few frequencies of noise to give it some texture
float n =0.0;
n += noise(pos*32.0);
n += noise(pos*64.0);
n += noise(pos*128.0);
n += noise(pos*256.0);
n += noise(pos*512.0);
n *= 0.8;
normal = normalize(normal + (n-2.0)*0.1);
// ------ Calculate texture color ------
vec3 texColor = vec3(0.95, 1.0, 1.0);
vec3 rust = vec3(0.65, 0.25, 0.1) - noise(pos*128.0);
// Call the function that makes rust stripes on the texture
texColor *= smoothstep(texColor, rust, vec3(saturate(RustNoise3D(pos*8.0))-0.2));
// apply noise
texColor *= vec3(1.0)*n*0.05;
texColor *= 0.7;
texColor = saturate(texColor);
// ------ Calculate lighting color ------
// Start with sun color, standard lighting equation, and shadow
vec3 lightColor = vec3(3.6) * saturate(dot(sunDir, normal)) * sunShadow;
// weighted average the near ambient occlusion with the far for just the right look
float ambientAvg = (ambient*3.0 + ambientS) * 0.25;
// a red and blue light coming from different directions
lightColor += (vec3(1.0, 0.2, 0.4) * saturate(-normal.z *0.5+0.5))*pow(ambientAvg, 0.35);
lightColor += (vec3(0.1, 0.5, 0.99) * saturate(normal.y *0.5+0.5))*pow(ambientAvg, 0.35);
// blue glow light coming from the glow in the middle
lightColor += vec3(0.3, 0.5, 0.9) * saturate(dot(-pos, normal))*pow(ambientS, 0.3);
lightColor *= 4.0;
// finally, apply the light to the texture.
finalColor = texColor * lightColor;
// sun reflection to make it look metal
//finalColor += vec3(1.0)*pow(n,4.0)* GetSunColorSmall(ref, sunDir) * sunShadow;// * ambientS;
// visualize length of gradient of distance field to check distance field correctness
//finalColor = vec3(0.5) * (length(normalU) / smallVec.x);
}
else
{
// Our ray trace hit nothing, so draw sky.
}
// add the ray marching glows
float center = length(pos.yz);
finalColor += vec3(0.3, 0.5, 0.9) * glowSave*1.2;
finalColor += vec3(0.9, 0.5, 0.3) * glow2*1.2;
finalColor += vec3(0.25, 0.29, 0.93) * glow3Save*2.0;
// vignette?
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
finalColor *= 1.0;// 1.3;
// output the final color without gamma correction - will do gamma later.
return vec3(clamp(finalColor, 0.0, 1.0)*saturate(fade+0.25));
}
#ifdef NON_REALTIME_HQ_RENDER
// This function breaks the image down into blocks and scans
// through them, rendering 1 block at a time. It's for non-
// realtime things that take a long time to render.
// This is the frame rate to render at. Too fast and you will
// miss some blocks.
const float blockRate = 20.0;
void BlockRender(in vec2 fragCoord)
{
// blockSize is how much it will try to render in 1 frame.
// adjust this smaller for more complex scenes, bigger for
// faster render times.
const float blockSize = 64.0;
// Make the block repeatedly scan across the image based on time.
float frame = floor(iTime * blockRate);
vec2 blockRes = floor(iResolution.xy / blockSize) + vec2(1.0);
// ugly bug with mod.
//float blockX = mod(frame, blockRes.x);
float blockX = fract(frame / blockRes.x) * blockRes.x;
//float blockY = mod(floor(frame / blockRes.x), blockRes.y);
float blockY = fract(floor(frame / blockRes.x) / blockRes.y) * blockRes.y;
// Don't draw anything outside the current block.
if ((fragCoord.x - blockX * blockSize >= blockSize) ||
(fragCoord.x - (blockX - 1.0) * blockSize < blockSize) ||
(fragCoord.y - blockY * blockSize >= blockSize) ||
(fragCoord.y - (blockY - 1.0) * blockSize < blockSize))
{
discard;
}
}
#endif
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
#ifdef NON_REALTIME_HQ_RENDER
// Optionally render a non-realtime scene with high quality
BlockRender(fragCoord);
#endif
// Do a multi-pass render
vec3 finalColor = vec3(0.0);
#ifdef NON_REALTIME_HQ_RENDER
for (float i = 0.0; i < antialiasingSamples; i++)
{
const float motionBlurLengthInSeconds = 1.0 / 60.0;
// Set this to the time in seconds of the frame to render.
localTime = frameToRenderHQ;
// This line will motion-blur the renders
localTime += Hash11(v21(fragCoord + seed)) * motionBlurLengthInSeconds;
// Jitter the pixel position so we get antialiasing when we do multiple passes.
vec2 jittered = fragCoord.xy + vec2(
Hash21(fragCoord + seed),
Hash21(fragCoord*7.234567 + seed)
);
// don't antialias if only 1 sample.
if (antialiasingSamples == 1.0) jittered = fragCoord;
// Accumulate one pass of raytracing into our pixel value
finalColor += RayTrace(jittered);
// Change the random seed for each pass.
seed *= 1.01234567;
}
// Average all accumulated pixel intensities
finalColor /= antialiasingSamples;
#else
// Regular real-time rendering
localTime = iTime;
finalColor = RayTrace(fragCoord);
#endif
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
6635,
6669,
6697,
6697,
6725
] | [
[
1278,
1307,
1326,
1326,
1371
],
[
1372,
1372,
1391,
1391,
1422
],
[
1423,
1423,
1446,
1446,
1482
],
[
1483,
1483,
1506,
1506,
1577
],
[
1578,
1578,
1600,
1600,
1687
],
[
1688,
1688,
1710,
1710,
1763
],
[
1764,
1764,
1787,
1787,
1860
],
[
1861,
1861,
1884,
1884,
1955
],
[
1956,
1956,
1979,
1979,
2065
],
[
2066,
2066,
2107,
2107,
2150
],
[
2188,
2188,
2212,
2212,
2485
],
[
2486,
2486,
2508,
2508,
3093
],
[
3123,
3123,
3146,
3146,
3175
],
[
3176,
3176,
3199,
3199,
3228
],
[
3229,
3229,
3254,
3254,
3283
],
[
3285,
3285,
3318,
3318,
3435
],
[
3436,
3436,
3469,
3469,
3585
],
[
3586,
3586,
3619,
3619,
3736
],
[
3738,
4267,
4294,
4294,
4859
],
[
4861,
4906,
4933,
4933,
4966
],
[
4967,
4967,
4992,
4992,
5025
],
[
5027,
5027,
5058,
5058,
5279
],
[
5281,
5281,
5306,
5306,
5594
],
[
5596,
5596,
5627,
5627,
5791
],
[
5793,
5793,
5824,
5824,
5927
],
[
5929,
6109,
6132,
6132,
6196
],
[
6198,
6220,
6254,
6254,
6365
],
[
6367,
6411,
6463,
6463,
6633
],
[
6635,
6669,
6697,
6697,
6725
],
[
6784,
6946,
6978,
6978,
9802
],
[
9804,
9874,
9909,
9909,
20901
],
[
22233,
22233,
22290,
22290,
23649
]
] | // simple cylinder distance field
| float cyl(vec2 p, float r)
{ |
return length(p) - r;
} | // simple cylinder distance field
float cyl(vec2 p, float r)
{ | 3 | 6 |
4d33z4 | sagarpatel | 2015-11-23T08:44:22 | // @sagzorz
// My first shader on ShaderToy!
// The stuff below is pretty much all of the amazing @cabbibo's SDF tutorial
// https://www.shadertoy.com/view/Xl2XWt
// I read thorugh it then looked at IQ's page on distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// got inspired and remixed stuff in really messy code
// my only excuse was that I was in a rush since I did the tutorial and my hack all in a bus ride
// from Ha Long Bay to Hanoi and batteries were starting to run out :/
/*
CC0 1.0
@vrtree
who@tree.is
http://tree.is
I dont know if this is going to work, or be interesting,
or even understandable, But hey! Why not try!
To start, get inspired by some MAGICAL creations made by raytracing:
Volcanic by IQ
https://www.shadertoy.com/view/XsX3RB
Remnant X by Dave_Hoskins ( Audio Autoplay warnings )
https://www.shadertoy.com/view/4sjSW1
Cloud Ten by Nimitz
https://www.shadertoy.com/view/XtS3DD
Spectacles by MEEEEEE
https://www.shadertoy.com/view/4lBXWt
[2TC 15] Mystery Mountains by Dave_Hoskins
https://www.shadertoy.com/view/llsGW7
Raytracing graphics is kinda like baking cakes.
I want yall to first see how magical
the cake can be before trying to learn how to make it, because the thing we
make at first isn't going to be one of those crazy 10 story wedding cakes. its just
going to be some burnt sugar bread.
Making art using code can be so fufilling, and so infinite, but to get there you
need to learn some techniques that might not seem that inspiring. To bake a cake,
you first need to turn on an oven, and need to know what an oven even is. In this
tutorial we are going to be learning how to make the oven, how to turn it on,
and how to mix ingredients. as you can see on our left, our cake isn't very pretty
but it is a cake. and thats pretty crazy for just one tutorial!
Once you have gone through this tutorial, you can see a 'minimized' version
here: https://www.shadertoy.com/view/Xt2XDt
where I've rewritten it using the varibles and functions that
are used alot throughout shadertoy. The inspiration examples above
probably seem completely insane, because of all the single letter variable
names, but keep in mind, that they all start with most of the same ingredients
and overn that we will learn about right now!
I've tried to break up the code into 'sections'
which have the 'SECTION 'BLAH'' label above them. Not sure
if thats gonna help or not, but please leave comments
if you think something works or doesn't work, slash you
have any questions!!!
or contact me at @vrtree || @cabbibo
Cheat sheet for vectors:
x = left / right
y = up / down
z = forwards / backwards
also, for vectors labeled 'color'
x = red
y = green
z = blue
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
The best metaphor that I can think of for raytracing is
that the rectangle to our left is actually just a small window
into a fantastic world. We need to describe that world,
so that we can see it. BUT HOW ?!?!?!
What we are doing below is describing what color each pixel
of the window is, however because of the way that shader
programs work, we need to give the same instruction to every
single PIXEL ( or in shadertoy terms, FRAGMENT )
in the window. This is where the term SIMD comes
from : Same Instruction Multiple Data
In this case, the same instruction is the program below,
and the multiple data is the marvelous little piece of magic
called 'fragCoord' which is just the position of the pixel in
window. lets rename some things to look prettier.
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
If you think about what happens with an actual window, you
can begin to get an idea of how the magic of raytracing works
basically a bunch of rays come from the sun ( and or other
light sources ) , bounce around a bunch ( or a little ), and
eventually make it through the window, and into our eyes.
Now the number of rays are masssiveeee that come from the sun
and alot of them that are bouncing around, will end up going
directions that aren't even close to the window, or maybe
will hit the wall instead of the window.
We only care about the rays that go through the window
and make it to our eyeballs!
This means that we can be a bit intelligent. Instead of
figuring out the rays that come from the sun and bounce around
lets start with out eyes, and work backwards!!!!
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
After setting up all the neccesary ray information,
we FINALLY get to start building the scene. Up to this point,
we've only built up the window, and the rays that go from our
eyes through the window, but now we need to describe to the rays
if they hit anything and what they hit!
Now this part has some pretty scary code in it ( whenever I look
at it at least, my eyes glaze over ), so feel free to skip over
the checkRayHit function. I tried to explain it as best as I could
down below, and you might want to come back to it after going
throught the rest of the tutorial, but the important thing to
remember is the following:
These 'rays' that we've been talking about will move through the
scene along their direction. They do this iteratively, and at each
step will basically ask the question :
'HOW CLOSE AM I TO THINGS IN THE WORLD???'
because well, rays are lonely, and want to be closer to things in
the world. We provide them an answer to that question using our
description of the world, and they use this information to tell
them how much further along their path they should move. If the
answer to the question is:
'Lovely little ray, you are actually touching a thing in the world!'
We know what that the ray hit something, and can begin with our next
step!
The tricky part about this is that we have to as accuratly as
possible provide them an answer to their question 'how close??!!'
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
To answer the above concept, we are going to use this magical
concept called:
'Signed Distance Fields'
-----------------------
These things are the best, and very basically can be describe as
a function that takes in a position, and feeds back a value of
how close you are to a thing. If the value of this distance is negative
you are inside the thing, if it is positive, you are outside the thing
and if its 0 you are at the surface of the thing! This positive or negative
gives us the 'Signed' in 'Signed Distance Field'
For a super intensive description of many of the SDFs out there
check out Inigo Quilez's site:
http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
Also, if you want a deep dive into why these functions are the
ultimate magic, check out this crazy paper by the geniouses
over at Media Molecule about their new game: 'DREAMS'
http://media.lolrus.mediamolecule.com/AlexEvans_SIGGRAPH-2015.pdf
Needless to say, these lil puppies are super amazing, and are
here to free us from the tyranny of polygons.
---------
We are going to put all of our SDFs into a single function called
'mapTheWorld'
which will take in a position, and feed back two values.
The first value is the Distance of Signed Distance Field, and the
second value will tell us what we are closest too, so that if
we actually hit something, we can tell what it is. We will denote this
by an 'ID' value.
The hardest part for me to wrap my head around for this was the fact that
these fields do not just describe where the surface of an object is,
they actually describe how far you are from the object from ANYWHERE
in the world.
For example, if I was hitting a round ballon ( AKA a sphere :) )
I wouldn't just know if I was on the surface of the ballon, I would have
to know how close I was to the balloon from anywhere in space.
Check out the 'TAG : BALLOON' in the mapTheWorld function for more detail :)
I've also made a function for a box, that is slightly more complex, and to be
honest, I don't exactly understand the math of it, but the beauty of programming
is that someone else ( AKA Inigo ) does, and I can steal his knowledge, just by
looking at the functions from his website!
---------
One of the magical properties of SDFs is how easily they can be combined
contorted, and manipulated. They are just these lil functions that take
in a position and give back a distance value, so we can do things like play with the
input position, play with the output distance value, or just about anything
else.
We'll start by combining two SDFs by asking the simple question
'Which thing am I closer to?'
which is as simple as a '>' because we already know exactly how close we are
to each thing!
check out 'TAG : WHICH AM I CLOSER TO?' for more enough
We use these function to create a map of the world for the rays to navigate,
and than pass that map to the checkRayHit, which propates the rays throughout
the world and tells us what they hit.
Once they know that, we can FINALLY do our last step:
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD!
//--------------------------------------------------------------
At the end of our checkRayHit function we return a vec2 with two values:
.x is the distance that our ray traveled before hitting
.y is the ID of the thing that we hit.
if .y is less that 0.0 that means that our ray went as far as we allowed it
to go without hitting anything. thats one lonely ray :(
however, that doesn't mean that the ray didn't hit anything. It just meant
that it is part of the background.
Thanks little ray!
You told us important information about our scene,
and your hard work is helping to create the world!
We can get reallly crazy with how we color the background of the scene,
but for this tutorial lets just keep it black, because who doesn't love
the void.
we will use the function 'doBackgroundColor' to accomplish this task!
That tells us about the background, but what if .y is greater than 0.0?
then we get to make some stuff in the scene!
if the ID is equal to balloon id, then we 'doBalloonColor'
and if the ID is equal to the box , then we 'doBoxColor'
This is all that we need if we want to color simple solid objects,
but what if we want to add some shading, by doing what we originally
talked about, that is, following the ray to the sun?
For this first tutorial, we will keep it to a very naive approach,
but once you get the basics of sections A - D, we can get SUPER crazy
with this 'color' the world section.
For example, we could reflect the
ray off the surface, and than repeat the checkRayHit with this new information
continuing to follow this ray through more and more of the world. we could
repeat this process again and again, and even though our gpu would hate us
we could continue bouncing around until we got to a light source!
In a later tutorial we will do exactly this, but for now,
we are going to do 1 simple task:
See how much the surface that we hit, faces the sun.
to do that we need to do 2 things.
First, determine which way the surface faces
Second, determine which way rays go from the surface to get to the sun
1) To determine the way that the surface faces, we will use a function called
'getNormalOfSurface' This function will either make 100% sense, or 0% sense
depending on how often you have played with fields, but it made 0% sense to me
for many years, so don't worry if you don't get it! Whats important is that
it gives us the direction that the surface faces, which we call its 'Normal'
You can think of it as a vector that is perpendicular to the surface at a specific point
So that it is easier to understand what this value is, we are actually going to color our
box based on this value. We will map the X value of the normal to red, the Y value of the
normal to green and the Z value of the normal to blue. You can see this more in the
'doBoxColor' function
2) To get the direction the rays go to get to the sun, we just need to subtract the sun
position from the position of where we hit. This will provide us a direction from the sun
to the position. Look inside the doBalloonColor to see this calculation happen.
this will give us the direction of the rays from the sun to the surface!
Now that we have these 2 pieces of information, the last thing we need to do is see
how much the two vectors ( the normal and the light direction ) 'Face' each other.
that word 'Face', might not make much sense in this context, but think about it this way.
If you have a table, and a light above the table, the top of the table will 'Face',
the light, and the bottom of the table will 'Face' away from the light. The surface
that 'Faces' the light will get hit by the rays from the light, while the surface
that 'Faces' away from the light will be totally dark!
so how do we get this 'Face' value ( pun intended :p ) ?
There is a magical function called a 'dot product' which does exactly this. you
can read more here:
https://en.wikipedia.org/wiki/Dot_product
basically this function takes in 2 vectors, and feeds back a value from -1 -> 1.
if the value is -1 , the two vectors face in exact opposite directions, and if
the value is 1 , the two vectors face in exactly the same direction. if the value is
0, than they are perpendicular!
By using the dot product, we take get the ballon's 'Face' value and color it depending
on this value!
check out the doBallonColor to see all this craziness in action
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
What a journey it has been. Remember back when we were talking about
sending rays through the window? Remember them moving all through the
world trying to be closer to things?
So much has happened, and at the end of that journey, we got a color for each ray!
now all we need to do is output that color onto the screen , which is a single call,
and we've made our world.
I know this stuff might seem too dry or too complex at times, too confusing,
too frustrating, but I promise, if you stick with it, you'll soon be making some of the
other magical structures you see throughout the rest of this site.
I'll be trying to do some more of these tutorials, and you'll see that VERY
quickly, you get from this hideous monstrosity to our left, to marvelous worlds
filled with lights, colors, and love.
Thanks for staying around, and please contact me:
@vrtree , @cabbibo with questions, concerns , and improvments. Or just comment!
*/
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// Most of this is taken from many of the shaders
// that @iq have worked on. Make sure to check out
// more of his magic!!!
// This calculation basically gets a way for us to
// transform the rays coming out of our eyes and going through the window.
// If it doesn't make sense, thats ok. It doesn't make sense to me either :)
// Whats important to remember is that this basically gives us a way to position
// our window. We could you it to make the window look north, south, east, west, up, down
// or ANYWHERE in between!
mat3 calculateEyeRayTransformationMatrix( in vec3 ro, in vec3 ta, in float roll )
{
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(sin(roll),cos(roll),0.0) ) );
vec3 vv = normalize( cross(uu,ww));
return mat3( uu, vv, ww );
}
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
//'TAG: BALLOON'
vec2 sdfBalloon( vec3 currentRayPosition ){
float ballOrbitSpeed = 0.85;
float ballOrbitRadius = 1.0;
vec3 ballOrbitOffset = vec3(1.0,0,0);
float balloonPosX = ballOrbitRadius * cos( ballOrbitSpeed * iTime);
float balloonPosY = ballOrbitRadius * sin( ballOrbitSpeed * iTime);
// First we define our balloon position
vec3 balloonPosition = ballOrbitOffset + vec3(balloonPosX,balloonPosY,0); //vec3( -1.3 , .3 , -0.4 );
// than we define our balloon radius
float balloonRadius = 0.51;
// Here we get the distance to the surface of the balloon
float distanceToBalloon = length( currentRayPosition - balloonPosition );
// finally we get the distance to the balloon surface
// by substacting the balloon radius. This means that if
// the distance to the balloon is less than the balloon radius
// the value we get will be negative! giving us the 'Signed' in
// Signed Distance Field!
float distanceToBalloonSurface = distanceToBalloon - balloonRadius;
// Finally we build the full balloon information, by giving it an ID
float balloonID = 1.;
// And there we have it! A fully described balloon!
vec2 balloon = vec2( distanceToBalloonSurface, balloonID );
return balloon;
}
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
float opTwist_Torus( vec3 p , vec2 torusS)
{
float twistSpedd = 0.35;
float c = cos( 15.0 * (sin( twistSpedd * iTime)) *p.y );
float s = sin( 15.0 * (sin( twistSpedd * iTime)) *p.y );
mat2 m = mat2(c,-s,s,c);
vec3 q = vec3(m*p.xz,p.y);
return sdTorus(q, torusS);
}
vec2 sdfTorus( vec3 currentRayPos )
{
vec3 torusPos = vec3( 0.0, 0.0, 0.0);
vec2 torusSpec = vec2(0.6, 0.23);
vec3 adjustedRayPos = currentRayPos - torusPos;
float distToTorusSurface = opTwist_Torus(adjustedRayPos, torusSpec); //sdTorus(adjustedRayPos, torusSpec);
float torusID = 3.;
vec2 torus = vec2( distToTorusSurface, torusID);
return torus;
}
float smin( float a, float b)
{
float k = 0.77521;
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
float opBlend( float d1, float d2)
{
//float d1 = primitiveA(p);
//float d2 = primitiveB(p);
return smin( d1, d2 );
}
vec2 sdfBox( vec3 currentRayPosition ){
// First we define our box position
vec3 boxPosition = vec3( -.8 , -.4 , 0.2 );
// than we define our box dimensions using x , y and z
vec3 boxSize = vec3( .4 , .3 , .2 );
// Here we get the 'adjusted ray position' which is just
// writing the point of the ray as if the origin of the
// space was where the box was positioned, instead of
// at 0,0,0 . AKA the difference between the vectors in
// vector format.
vec3 adjustedRayPosition = currentRayPosition - boxPosition;
// finally we get the distance to the box surface.
// I don't get this part very much, but I bet Inigo does!
// Thanks for making code for us IQ !
vec3 distanceVec = abs( adjustedRayPosition ) - boxSize;
float maxDistance = max( distanceVec.x , max( distanceVec.y , distanceVec.z ) );
float distanceToBoxSurface = min( maxDistance , 0.0 ) + length( max( distanceVec , 0.0 ) );
// Finally we build the full box information, by giving it an ID
float boxID = 2.;
// And there we have it! A fully described box!
vec2 box = vec2( distanceToBoxSurface, boxID );
return box;
}
// 'TAG : WHICH AM I CLOSER TO?'
// This function takes in two things
// and says which is closer by using the
// distance to each thing, comparing them
// and returning the one that is closer!
vec2 whichThingAmICloserTo( vec2 thing1 , vec2 thing2 ){
vec2 closestThing;
// Check out the balloon function
// and remember how the x of the returned
// information is the distance, and the y
// is the id of the thing!
if( thing1.x <= thing2.x ){
closestThing = thing1;
}else if( thing2.x < thing1.x ){
closestThing = thing2;
}
return closestThing;
}
// Takes in the position of the ray, and feeds back
// 2 values of how close it is to things in the world
// what thing it is closest two in the world.
vec2 mapTheWorld( vec3 currentRayPosition ){
vec2 result;
vec2 balloon = sdfBalloon( currentRayPosition );
//vec2 box = sdfBox( currentRayPosition );
vec2 torus = sdfTorus( currentRayPosition );
result = whichThingAmICloserTo( balloon , torus); //box );
result.x = opBlend( balloon.x, torus.x);
return result;
}
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
// We want to know when the closeness to things in the world is
// 0.0 , but if we wanted to get exactly to 0 it would take us
// alot of time to be that precise. Here we define the laziness
// our navigation function. try chaning the value to see what it does!
// if you are getting too low of framerates, this value will help alot,
// but can also make your scene look very different
// from how it should
const float HOW_CLOSE_IS_CLOSE_ENOUGH = 0.0001;
// This is basically how big our scene is. each ray will be shot forward
// until it reaches this distance. the smaller it is, the quicker the
// ray will reach the edge, which should help speed up this function
const float FURTHEST_OUR_RAY_CAN_REACH = 10.75;
// This is how may steps our ray can take. Hopefully for this
// simple of a world, it will very quickly get to the 'close enough' value
// and stop the iteration, but for more complex scenes, this value
// will dramatically change not only how good the scene looks
// but how fast teh scene can render.
// remember that for each pixel we are displaying, the 'mapTheWorld' function
// could be called this many times! Thats ALOT of calculations!!!
const int HOW_MANY_STEPS_CAN_OUR_RAY_TAKE = 2000;
vec2 checkRayHit( in vec3 eyePosition , in vec3 rayDirection ){
//First we set some default values
// our distance to surface will get overwritten every step,
// so all that is important is that it is greater than our
// 'how close is close enough' value
float distanceToSurface = HOW_CLOSE_IS_CLOSE_ENOUGH * 2.;
// The total distance traveled by the ray obviously should start at 0
float totalDistanceTraveledByRay = 0.;
// if we hit something, this value will be overwritten by the
// totalDistance traveled, and if we don't hit something it will
// be overwritten by the furthest our ray can reach,
// so it can be whatever!
float finalDistanceTraveledByRay = -1.;
// if our id is less that 0. , it means we haven't hit anything
// so lets start by saying we haven't hit anything!
float finalID = -1.;
//here is the loop where the magic happens
for( int i = 0; i < HOW_MANY_STEPS_CAN_OUR_RAY_TAKE; i++ ){
// First off, stop the iteration, if we are close enough to the surface!
if( distanceToSurface < HOW_CLOSE_IS_CLOSE_ENOUGH ) break;
// Second off, stop the iteration, if we have reached the end of our scene!
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ) break;
// To check how close we are to things in the world,
// we need to get a position in the scene. to do this,
// we start at the rays origin, AKA the eye
// and move along the ray direction, the amount we have already traveled.
vec3 currentPositionOfRay = eyePosition + rayDirection * totalDistanceTraveledByRay;
// Distance to and ID of things in the world
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
vec2 distanceAndIDOfThingsInTheWorld = mapTheWorld( currentPositionOfRay );
// we get out the results from our mapping of the world
// I am reassigning them for clarity
float distanceToThingsInTheWorld = distanceAndIDOfThingsInTheWorld.x;
float idOfClosestThingInTheWorld = distanceAndIDOfThingsInTheWorld.y;
// We save out the distance to the surface, so that
// next iteration we can check to see if we are close enough
// to stop all this silly iteration
distanceToSurface = distanceToThingsInTheWorld;
// We are also finalID to the current closest id,
// because if we hit something, we will have the proper
// id, and we can skip reassigning it later!
finalID = idOfClosestThingInTheWorld;
// ATTENTION: THIS THING IS AWESOME!
// This last little calculation is probably the coolest hack
// of this entire tutorial. If we wanted too, we could basically
// step through the field at a constant amount, and at every step
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// that would take FOREVER, and get really annoying.
// Instead what we say is 'How far until we are there?'
// and move forward by that amount. This means that if
// we are really far away from everything, we can make large
// movements towards the surface, and if we are closer
// we can make more precise movements. making our marching functino
// faster, and ideally more precise!!
// WOW!
totalDistanceTraveledByRay += 0.05 * distanceToThingsInTheWorld; //0.001 + distanceToThingsInTheWorld * abs(sin(iTime)); //distanceToThingsInTheWorld;
}
// if we hit something set the finalDirastnce traveled by
// ray to that distance!
if( totalDistanceTraveledByRay < FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = totalDistanceTraveledByRay;
}
// If the total distance traveled by the ray is further than
// the ray can reach, that means that we've hit the edge of the scene
// Set the final distance to be the edge of the scene
// and the id to -1 to make sure we know we haven't hit anything
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = FURTHEST_OUR_RAY_CAN_REACH;
finalID = -1.;
}
return vec2( finalDistanceTraveledByRay , finalID );
}
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
// Here we are calcuting the normal of the surface
// Although it looks like alot of code, it actually
// is just trying to do something very simple, which
// is to figure out in what direction the SDF is increasing.
// What is amazing, is that this value is the same thing
// as telling you what direction the surface faces, AKA the
// normal of the surface.
vec3 getNormalOfSurface( in vec3 positionOfHit ){
vec3 tinyChangeX = vec3( 0.001, 0.0, 0.0 );
vec3 tinyChangeY = vec3( 0.0 , 0.001 , 0.0 );
vec3 tinyChangeZ = vec3( 0.0 , 0.0 , 0.001 );
float upTinyChangeInX = mapTheWorld( positionOfHit + tinyChangeX ).x;
float downTinyChangeInX = mapTheWorld( positionOfHit - tinyChangeX ).x;
float tinyChangeInX = upTinyChangeInX - downTinyChangeInX;
float upTinyChangeInY = mapTheWorld( positionOfHit + tinyChangeY ).x;
float downTinyChangeInY = mapTheWorld( positionOfHit - tinyChangeY ).x;
float tinyChangeInY = upTinyChangeInY - downTinyChangeInY;
float upTinyChangeInZ = mapTheWorld( positionOfHit + tinyChangeZ ).x;
float downTinyChangeInZ = mapTheWorld( positionOfHit - tinyChangeZ ).x;
float tinyChangeInZ = upTinyChangeInZ - downTinyChangeInZ;
vec3 normal = vec3(
tinyChangeInX,
tinyChangeInY,
tinyChangeInZ
);
return normalize(normal);
}
// doing our background color is easy enough,
// just make it pure black. like my soul.
vec3 doBackgroundColor(){
return vec3( 0.75 );
}
vec3 doBalloonColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 balloonColor = vec3( 1. , 0. , 0. );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = balloonColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
vec3 doTorusColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 torusColor = vec3( 0.25 , 0.95 , 0.25 );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = torusColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
// Here we are using the normal of the surface,
// and mapping it to color, to show you just how cool
// normals can be!
vec3 doBoxColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 color = vec3( normalOfSurface.x , normalOfSurface.y , normalOfSurface.z );
//could also just write color = normalOfSurce
//but trying to be explicit.
return color;
}
// This is where we decide
// what color the world will be!
// and what marvelous colors it will be!
vec3 colorTheWorld( vec2 rayHitInfo , vec3 eyePosition , vec3 rayDirection ){
// remember for color
// x = red , y = green , z = blue
vec3 color;
// THE LIL RAY WENT ALL THE WAY
// TO THE EDGE OF THE WORLD,
// AND DIDN'T HIT ANYTHING
if( rayHitInfo.y < 0.0 ){
color = doBackgroundColor();
// THE LIL RAY HIT SOMETHING!!!!
}else{
// If we hit something,
// we also know how far the ray has to travel to hit it
// and because we know the direction of the ray, we can
// get the exact position of where we hit the surface
// by following the ray from the eye, along its direction
// for the however far it had to travel to hit something
vec3 positionOfHit = eyePosition + rayHitInfo.x * rayDirection;
// We can then use this information to tell what direction
// the surface faces in
vec3 normalOfSurface = getNormalOfSurface( positionOfHit );
// 1.0 is the Balloon ID
if( rayHitInfo.y == 1.0 ){
color = doBalloonColor( positionOfHit , normalOfSurface );
// 2.0 is the Box ID
}else if( rayHitInfo.y == 2.0 ){
color = doBoxColor( positionOfHit , normalOfSurface );
}
else if( rayHitInfo.y == 3.0)
{
color = doTorusColor( positionOfHit , normalOfSurface );
}
}
return color;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
// Here we are getting our 'Position' of each pixel
// This section is important, because if we didn't
// divied by the resolution, our values would be masssive
// as fragCoord returns the value of how many pixels over we
// are. which is alot :)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// thats a super long name, so maybe we will
// keep on using uv, but im explicitly defining it
// so you can see exactly what those two letters mean
vec2 xyPositionOfPixelInWindow = p;
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// We use the eye position to tell use where the viewer is
float camRotSpeed = 0.5;
float rotRadius = 2.75;
float eyePosX = rotRadius * cos( camRotSpeed * iTime);
float eyePosZ = rotRadius * sin( camRotSpeed * iTime);
vec3 eyePosition = vec3( eyePosX, 0.5, eyePosZ); //vec3( 0., 0.5, 2.);
// This is the point the view is looking at.
// The window will be placed between the eye, and the
// position the eye is looking at!
vec3 pointWeAreLookingAt = vec3( 0. , 0. , 0. );
// This is where the magic of actual mathematics
// gives a way to actually place the window.
// the 0. at the end there gives the 'roll' of the transformation
// AKA we would be standing so up is up, but up could be changing
// like if we were one of those creepy dolls whos rotate their head
// all the way around along the z axis
mat3 eyeTransformationMatrix = calculateEyeRayTransformationMatrix( eyePosition , pointWeAreLookingAt , 0. );
// Here we get the actual ray that goes out of the eye
// and through the individual pixel! This basically the only thing
// that is different between the pixels, but is also the bread and butter
// of ray tracing. It should be since it has the word 'ray' in its variable name...
// the 2. at the end is the 'lens length' . I don't know how to best
// describe this, but once the full scene is built, tryin playing with it
// to understand inherently how it works
vec3 rayComingOutOfEyeDirection = normalize( eyeTransformationMatrix * vec3( p.xy , 2. ) );
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
vec2 rayHitInfo = checkRayHit( eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
vec3 color = colorTheWorld( rayHitInfo , eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
fragColor = vec4(color,1.0);
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
}
| cc0-1.0 | [
15590,
15992,
16075,
16075,
16253
] | [
[
15590,
15992,
16075,
16075,
16253
],
[
16457,
16474,
16517,
16517,
17738
],
[
17740,
17740,
17773,
17773,
17838
],
[
17840,
17840,
17884,
17884,
18130
],
[
18132,
18132,
18169,
18169,
18519
],
[
18521,
18521,
18552,
18552,
18668
],
[
18670,
18670,
18706,
18770,
18799
],
[
18802,
18802,
18841,
18882,
19967
],
[
19970,
20165,
20221,
20221,
20605
],
[
20613,
20765,
20809,
20809,
21118
],
[
22490,
22490,
22553,
22758,
27037
],
[
27214,
27576,
27625,
27625,
28622
],
[
28628,
28716,
28741,
28741,
28765
],
[
28770,
28770,
28834,
28834,
29925
],
[
29929,
29929,
29991,
29991,
31084
],
[
31087,
31208,
31268,
31268,
31467
],
[
31472,
31573,
31650,
31714,
33042
],
[
33046,
33046,
33103,
33547,
36672
]
] | // This calculation basically gets a way for us to
// transform the rays coming out of our eyes and going through the window.
// If it doesn't make sense, thats ok. It doesn't make sense to me either :)
// Whats important to remember is that this basically gives us a way to position
// our window. We could you it to make the window look north, south, east, west, up, down
// or ANYWHERE in between!
| mat3 calculateEyeRayTransformationMatrix( in vec3 ro, in vec3 ta, in float roll )
{ |
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(sin(roll),cos(roll),0.0) ) );
vec3 vv = normalize( cross(uu,ww));
return mat3( uu, vv, ww );
} | // This calculation basically gets a way for us to
// transform the rays coming out of our eyes and going through the window.
// If it doesn't make sense, thats ok. It doesn't make sense to me either :)
// Whats important to remember is that this basically gives us a way to position
// our window. We could you it to make the window look north, south, east, west, up, down
// or ANYWHERE in between!
mat3 calculateEyeRayTransformationMatrix( in vec3 ro, in vec3 ta, in float roll )
{ | 5 | 5 |
4d33z4 | sagarpatel | 2015-11-23T08:44:22 | // @sagzorz
// My first shader on ShaderToy!
// The stuff below is pretty much all of the amazing @cabbibo's SDF tutorial
// https://www.shadertoy.com/view/Xl2XWt
// I read thorugh it then looked at IQ's page on distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// got inspired and remixed stuff in really messy code
// my only excuse was that I was in a rush since I did the tutorial and my hack all in a bus ride
// from Ha Long Bay to Hanoi and batteries were starting to run out :/
/*
CC0 1.0
@vrtree
who@tree.is
http://tree.is
I dont know if this is going to work, or be interesting,
or even understandable, But hey! Why not try!
To start, get inspired by some MAGICAL creations made by raytracing:
Volcanic by IQ
https://www.shadertoy.com/view/XsX3RB
Remnant X by Dave_Hoskins ( Audio Autoplay warnings )
https://www.shadertoy.com/view/4sjSW1
Cloud Ten by Nimitz
https://www.shadertoy.com/view/XtS3DD
Spectacles by MEEEEEE
https://www.shadertoy.com/view/4lBXWt
[2TC 15] Mystery Mountains by Dave_Hoskins
https://www.shadertoy.com/view/llsGW7
Raytracing graphics is kinda like baking cakes.
I want yall to first see how magical
the cake can be before trying to learn how to make it, because the thing we
make at first isn't going to be one of those crazy 10 story wedding cakes. its just
going to be some burnt sugar bread.
Making art using code can be so fufilling, and so infinite, but to get there you
need to learn some techniques that might not seem that inspiring. To bake a cake,
you first need to turn on an oven, and need to know what an oven even is. In this
tutorial we are going to be learning how to make the oven, how to turn it on,
and how to mix ingredients. as you can see on our left, our cake isn't very pretty
but it is a cake. and thats pretty crazy for just one tutorial!
Once you have gone through this tutorial, you can see a 'minimized' version
here: https://www.shadertoy.com/view/Xt2XDt
where I've rewritten it using the varibles and functions that
are used alot throughout shadertoy. The inspiration examples above
probably seem completely insane, because of all the single letter variable
names, but keep in mind, that they all start with most of the same ingredients
and overn that we will learn about right now!
I've tried to break up the code into 'sections'
which have the 'SECTION 'BLAH'' label above them. Not sure
if thats gonna help or not, but please leave comments
if you think something works or doesn't work, slash you
have any questions!!!
or contact me at @vrtree || @cabbibo
Cheat sheet for vectors:
x = left / right
y = up / down
z = forwards / backwards
also, for vectors labeled 'color'
x = red
y = green
z = blue
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
The best metaphor that I can think of for raytracing is
that the rectangle to our left is actually just a small window
into a fantastic world. We need to describe that world,
so that we can see it. BUT HOW ?!?!?!
What we are doing below is describing what color each pixel
of the window is, however because of the way that shader
programs work, we need to give the same instruction to every
single PIXEL ( or in shadertoy terms, FRAGMENT )
in the window. This is where the term SIMD comes
from : Same Instruction Multiple Data
In this case, the same instruction is the program below,
and the multiple data is the marvelous little piece of magic
called 'fragCoord' which is just the position of the pixel in
window. lets rename some things to look prettier.
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
If you think about what happens with an actual window, you
can begin to get an idea of how the magic of raytracing works
basically a bunch of rays come from the sun ( and or other
light sources ) , bounce around a bunch ( or a little ), and
eventually make it through the window, and into our eyes.
Now the number of rays are masssiveeee that come from the sun
and alot of them that are bouncing around, will end up going
directions that aren't even close to the window, or maybe
will hit the wall instead of the window.
We only care about the rays that go through the window
and make it to our eyeballs!
This means that we can be a bit intelligent. Instead of
figuring out the rays that come from the sun and bounce around
lets start with out eyes, and work backwards!!!!
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
After setting up all the neccesary ray information,
we FINALLY get to start building the scene. Up to this point,
we've only built up the window, and the rays that go from our
eyes through the window, but now we need to describe to the rays
if they hit anything and what they hit!
Now this part has some pretty scary code in it ( whenever I look
at it at least, my eyes glaze over ), so feel free to skip over
the checkRayHit function. I tried to explain it as best as I could
down below, and you might want to come back to it after going
throught the rest of the tutorial, but the important thing to
remember is the following:
These 'rays' that we've been talking about will move through the
scene along their direction. They do this iteratively, and at each
step will basically ask the question :
'HOW CLOSE AM I TO THINGS IN THE WORLD???'
because well, rays are lonely, and want to be closer to things in
the world. We provide them an answer to that question using our
description of the world, and they use this information to tell
them how much further along their path they should move. If the
answer to the question is:
'Lovely little ray, you are actually touching a thing in the world!'
We know what that the ray hit something, and can begin with our next
step!
The tricky part about this is that we have to as accuratly as
possible provide them an answer to their question 'how close??!!'
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
To answer the above concept, we are going to use this magical
concept called:
'Signed Distance Fields'
-----------------------
These things are the best, and very basically can be describe as
a function that takes in a position, and feeds back a value of
how close you are to a thing. If the value of this distance is negative
you are inside the thing, if it is positive, you are outside the thing
and if its 0 you are at the surface of the thing! This positive or negative
gives us the 'Signed' in 'Signed Distance Field'
For a super intensive description of many of the SDFs out there
check out Inigo Quilez's site:
http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
Also, if you want a deep dive into why these functions are the
ultimate magic, check out this crazy paper by the geniouses
over at Media Molecule about their new game: 'DREAMS'
http://media.lolrus.mediamolecule.com/AlexEvans_SIGGRAPH-2015.pdf
Needless to say, these lil puppies are super amazing, and are
here to free us from the tyranny of polygons.
---------
We are going to put all of our SDFs into a single function called
'mapTheWorld'
which will take in a position, and feed back two values.
The first value is the Distance of Signed Distance Field, and the
second value will tell us what we are closest too, so that if
we actually hit something, we can tell what it is. We will denote this
by an 'ID' value.
The hardest part for me to wrap my head around for this was the fact that
these fields do not just describe where the surface of an object is,
they actually describe how far you are from the object from ANYWHERE
in the world.
For example, if I was hitting a round ballon ( AKA a sphere :) )
I wouldn't just know if I was on the surface of the ballon, I would have
to know how close I was to the balloon from anywhere in space.
Check out the 'TAG : BALLOON' in the mapTheWorld function for more detail :)
I've also made a function for a box, that is slightly more complex, and to be
honest, I don't exactly understand the math of it, but the beauty of programming
is that someone else ( AKA Inigo ) does, and I can steal his knowledge, just by
looking at the functions from his website!
---------
One of the magical properties of SDFs is how easily they can be combined
contorted, and manipulated. They are just these lil functions that take
in a position and give back a distance value, so we can do things like play with the
input position, play with the output distance value, or just about anything
else.
We'll start by combining two SDFs by asking the simple question
'Which thing am I closer to?'
which is as simple as a '>' because we already know exactly how close we are
to each thing!
check out 'TAG : WHICH AM I CLOSER TO?' for more enough
We use these function to create a map of the world for the rays to navigate,
and than pass that map to the checkRayHit, which propates the rays throughout
the world and tells us what they hit.
Once they know that, we can FINALLY do our last step:
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD!
//--------------------------------------------------------------
At the end of our checkRayHit function we return a vec2 with two values:
.x is the distance that our ray traveled before hitting
.y is the ID of the thing that we hit.
if .y is less that 0.0 that means that our ray went as far as we allowed it
to go without hitting anything. thats one lonely ray :(
however, that doesn't mean that the ray didn't hit anything. It just meant
that it is part of the background.
Thanks little ray!
You told us important information about our scene,
and your hard work is helping to create the world!
We can get reallly crazy with how we color the background of the scene,
but for this tutorial lets just keep it black, because who doesn't love
the void.
we will use the function 'doBackgroundColor' to accomplish this task!
That tells us about the background, but what if .y is greater than 0.0?
then we get to make some stuff in the scene!
if the ID is equal to balloon id, then we 'doBalloonColor'
and if the ID is equal to the box , then we 'doBoxColor'
This is all that we need if we want to color simple solid objects,
but what if we want to add some shading, by doing what we originally
talked about, that is, following the ray to the sun?
For this first tutorial, we will keep it to a very naive approach,
but once you get the basics of sections A - D, we can get SUPER crazy
with this 'color' the world section.
For example, we could reflect the
ray off the surface, and than repeat the checkRayHit with this new information
continuing to follow this ray through more and more of the world. we could
repeat this process again and again, and even though our gpu would hate us
we could continue bouncing around until we got to a light source!
In a later tutorial we will do exactly this, but for now,
we are going to do 1 simple task:
See how much the surface that we hit, faces the sun.
to do that we need to do 2 things.
First, determine which way the surface faces
Second, determine which way rays go from the surface to get to the sun
1) To determine the way that the surface faces, we will use a function called
'getNormalOfSurface' This function will either make 100% sense, or 0% sense
depending on how often you have played with fields, but it made 0% sense to me
for many years, so don't worry if you don't get it! Whats important is that
it gives us the direction that the surface faces, which we call its 'Normal'
You can think of it as a vector that is perpendicular to the surface at a specific point
So that it is easier to understand what this value is, we are actually going to color our
box based on this value. We will map the X value of the normal to red, the Y value of the
normal to green and the Z value of the normal to blue. You can see this more in the
'doBoxColor' function
2) To get the direction the rays go to get to the sun, we just need to subtract the sun
position from the position of where we hit. This will provide us a direction from the sun
to the position. Look inside the doBalloonColor to see this calculation happen.
this will give us the direction of the rays from the sun to the surface!
Now that we have these 2 pieces of information, the last thing we need to do is see
how much the two vectors ( the normal and the light direction ) 'Face' each other.
that word 'Face', might not make much sense in this context, but think about it this way.
If you have a table, and a light above the table, the top of the table will 'Face',
the light, and the bottom of the table will 'Face' away from the light. The surface
that 'Faces' the light will get hit by the rays from the light, while the surface
that 'Faces' away from the light will be totally dark!
so how do we get this 'Face' value ( pun intended :p ) ?
There is a magical function called a 'dot product' which does exactly this. you
can read more here:
https://en.wikipedia.org/wiki/Dot_product
basically this function takes in 2 vectors, and feeds back a value from -1 -> 1.
if the value is -1 , the two vectors face in exact opposite directions, and if
the value is 1 , the two vectors face in exactly the same direction. if the value is
0, than they are perpendicular!
By using the dot product, we take get the ballon's 'Face' value and color it depending
on this value!
check out the doBallonColor to see all this craziness in action
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
What a journey it has been. Remember back when we were talking about
sending rays through the window? Remember them moving all through the
world trying to be closer to things?
So much has happened, and at the end of that journey, we got a color for each ray!
now all we need to do is output that color onto the screen , which is a single call,
and we've made our world.
I know this stuff might seem too dry or too complex at times, too confusing,
too frustrating, but I promise, if you stick with it, you'll soon be making some of the
other magical structures you see throughout the rest of this site.
I'll be trying to do some more of these tutorials, and you'll see that VERY
quickly, you get from this hideous monstrosity to our left, to marvelous worlds
filled with lights, colors, and love.
Thanks for staying around, and please contact me:
@vrtree , @cabbibo with questions, concerns , and improvments. Or just comment!
*/
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// Most of this is taken from many of the shaders
// that @iq have worked on. Make sure to check out
// more of his magic!!!
// This calculation basically gets a way for us to
// transform the rays coming out of our eyes and going through the window.
// If it doesn't make sense, thats ok. It doesn't make sense to me either :)
// Whats important to remember is that this basically gives us a way to position
// our window. We could you it to make the window look north, south, east, west, up, down
// or ANYWHERE in between!
mat3 calculateEyeRayTransformationMatrix( in vec3 ro, in vec3 ta, in float roll )
{
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(sin(roll),cos(roll),0.0) ) );
vec3 vv = normalize( cross(uu,ww));
return mat3( uu, vv, ww );
}
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
//'TAG: BALLOON'
vec2 sdfBalloon( vec3 currentRayPosition ){
float ballOrbitSpeed = 0.85;
float ballOrbitRadius = 1.0;
vec3 ballOrbitOffset = vec3(1.0,0,0);
float balloonPosX = ballOrbitRadius * cos( ballOrbitSpeed * iTime);
float balloonPosY = ballOrbitRadius * sin( ballOrbitSpeed * iTime);
// First we define our balloon position
vec3 balloonPosition = ballOrbitOffset + vec3(balloonPosX,balloonPosY,0); //vec3( -1.3 , .3 , -0.4 );
// than we define our balloon radius
float balloonRadius = 0.51;
// Here we get the distance to the surface of the balloon
float distanceToBalloon = length( currentRayPosition - balloonPosition );
// finally we get the distance to the balloon surface
// by substacting the balloon radius. This means that if
// the distance to the balloon is less than the balloon radius
// the value we get will be negative! giving us the 'Signed' in
// Signed Distance Field!
float distanceToBalloonSurface = distanceToBalloon - balloonRadius;
// Finally we build the full balloon information, by giving it an ID
float balloonID = 1.;
// And there we have it! A fully described balloon!
vec2 balloon = vec2( distanceToBalloonSurface, balloonID );
return balloon;
}
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
float opTwist_Torus( vec3 p , vec2 torusS)
{
float twistSpedd = 0.35;
float c = cos( 15.0 * (sin( twistSpedd * iTime)) *p.y );
float s = sin( 15.0 * (sin( twistSpedd * iTime)) *p.y );
mat2 m = mat2(c,-s,s,c);
vec3 q = vec3(m*p.xz,p.y);
return sdTorus(q, torusS);
}
vec2 sdfTorus( vec3 currentRayPos )
{
vec3 torusPos = vec3( 0.0, 0.0, 0.0);
vec2 torusSpec = vec2(0.6, 0.23);
vec3 adjustedRayPos = currentRayPos - torusPos;
float distToTorusSurface = opTwist_Torus(adjustedRayPos, torusSpec); //sdTorus(adjustedRayPos, torusSpec);
float torusID = 3.;
vec2 torus = vec2( distToTorusSurface, torusID);
return torus;
}
float smin( float a, float b)
{
float k = 0.77521;
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
float opBlend( float d1, float d2)
{
//float d1 = primitiveA(p);
//float d2 = primitiveB(p);
return smin( d1, d2 );
}
vec2 sdfBox( vec3 currentRayPosition ){
// First we define our box position
vec3 boxPosition = vec3( -.8 , -.4 , 0.2 );
// than we define our box dimensions using x , y and z
vec3 boxSize = vec3( .4 , .3 , .2 );
// Here we get the 'adjusted ray position' which is just
// writing the point of the ray as if the origin of the
// space was where the box was positioned, instead of
// at 0,0,0 . AKA the difference between the vectors in
// vector format.
vec3 adjustedRayPosition = currentRayPosition - boxPosition;
// finally we get the distance to the box surface.
// I don't get this part very much, but I bet Inigo does!
// Thanks for making code for us IQ !
vec3 distanceVec = abs( adjustedRayPosition ) - boxSize;
float maxDistance = max( distanceVec.x , max( distanceVec.y , distanceVec.z ) );
float distanceToBoxSurface = min( maxDistance , 0.0 ) + length( max( distanceVec , 0.0 ) );
// Finally we build the full box information, by giving it an ID
float boxID = 2.;
// And there we have it! A fully described box!
vec2 box = vec2( distanceToBoxSurface, boxID );
return box;
}
// 'TAG : WHICH AM I CLOSER TO?'
// This function takes in two things
// and says which is closer by using the
// distance to each thing, comparing them
// and returning the one that is closer!
vec2 whichThingAmICloserTo( vec2 thing1 , vec2 thing2 ){
vec2 closestThing;
// Check out the balloon function
// and remember how the x of the returned
// information is the distance, and the y
// is the id of the thing!
if( thing1.x <= thing2.x ){
closestThing = thing1;
}else if( thing2.x < thing1.x ){
closestThing = thing2;
}
return closestThing;
}
// Takes in the position of the ray, and feeds back
// 2 values of how close it is to things in the world
// what thing it is closest two in the world.
vec2 mapTheWorld( vec3 currentRayPosition ){
vec2 result;
vec2 balloon = sdfBalloon( currentRayPosition );
//vec2 box = sdfBox( currentRayPosition );
vec2 torus = sdfTorus( currentRayPosition );
result = whichThingAmICloserTo( balloon , torus); //box );
result.x = opBlend( balloon.x, torus.x);
return result;
}
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
// We want to know when the closeness to things in the world is
// 0.0 , but if we wanted to get exactly to 0 it would take us
// alot of time to be that precise. Here we define the laziness
// our navigation function. try chaning the value to see what it does!
// if you are getting too low of framerates, this value will help alot,
// but can also make your scene look very different
// from how it should
const float HOW_CLOSE_IS_CLOSE_ENOUGH = 0.0001;
// This is basically how big our scene is. each ray will be shot forward
// until it reaches this distance. the smaller it is, the quicker the
// ray will reach the edge, which should help speed up this function
const float FURTHEST_OUR_RAY_CAN_REACH = 10.75;
// This is how may steps our ray can take. Hopefully for this
// simple of a world, it will very quickly get to the 'close enough' value
// and stop the iteration, but for more complex scenes, this value
// will dramatically change not only how good the scene looks
// but how fast teh scene can render.
// remember that for each pixel we are displaying, the 'mapTheWorld' function
// could be called this many times! Thats ALOT of calculations!!!
const int HOW_MANY_STEPS_CAN_OUR_RAY_TAKE = 2000;
vec2 checkRayHit( in vec3 eyePosition , in vec3 rayDirection ){
//First we set some default values
// our distance to surface will get overwritten every step,
// so all that is important is that it is greater than our
// 'how close is close enough' value
float distanceToSurface = HOW_CLOSE_IS_CLOSE_ENOUGH * 2.;
// The total distance traveled by the ray obviously should start at 0
float totalDistanceTraveledByRay = 0.;
// if we hit something, this value will be overwritten by the
// totalDistance traveled, and if we don't hit something it will
// be overwritten by the furthest our ray can reach,
// so it can be whatever!
float finalDistanceTraveledByRay = -1.;
// if our id is less that 0. , it means we haven't hit anything
// so lets start by saying we haven't hit anything!
float finalID = -1.;
//here is the loop where the magic happens
for( int i = 0; i < HOW_MANY_STEPS_CAN_OUR_RAY_TAKE; i++ ){
// First off, stop the iteration, if we are close enough to the surface!
if( distanceToSurface < HOW_CLOSE_IS_CLOSE_ENOUGH ) break;
// Second off, stop the iteration, if we have reached the end of our scene!
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ) break;
// To check how close we are to things in the world,
// we need to get a position in the scene. to do this,
// we start at the rays origin, AKA the eye
// and move along the ray direction, the amount we have already traveled.
vec3 currentPositionOfRay = eyePosition + rayDirection * totalDistanceTraveledByRay;
// Distance to and ID of things in the world
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
vec2 distanceAndIDOfThingsInTheWorld = mapTheWorld( currentPositionOfRay );
// we get out the results from our mapping of the world
// I am reassigning them for clarity
float distanceToThingsInTheWorld = distanceAndIDOfThingsInTheWorld.x;
float idOfClosestThingInTheWorld = distanceAndIDOfThingsInTheWorld.y;
// We save out the distance to the surface, so that
// next iteration we can check to see if we are close enough
// to stop all this silly iteration
distanceToSurface = distanceToThingsInTheWorld;
// We are also finalID to the current closest id,
// because if we hit something, we will have the proper
// id, and we can skip reassigning it later!
finalID = idOfClosestThingInTheWorld;
// ATTENTION: THIS THING IS AWESOME!
// This last little calculation is probably the coolest hack
// of this entire tutorial. If we wanted too, we could basically
// step through the field at a constant amount, and at every step
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// that would take FOREVER, and get really annoying.
// Instead what we say is 'How far until we are there?'
// and move forward by that amount. This means that if
// we are really far away from everything, we can make large
// movements towards the surface, and if we are closer
// we can make more precise movements. making our marching functino
// faster, and ideally more precise!!
// WOW!
totalDistanceTraveledByRay += 0.05 * distanceToThingsInTheWorld; //0.001 + distanceToThingsInTheWorld * abs(sin(iTime)); //distanceToThingsInTheWorld;
}
// if we hit something set the finalDirastnce traveled by
// ray to that distance!
if( totalDistanceTraveledByRay < FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = totalDistanceTraveledByRay;
}
// If the total distance traveled by the ray is further than
// the ray can reach, that means that we've hit the edge of the scene
// Set the final distance to be the edge of the scene
// and the id to -1 to make sure we know we haven't hit anything
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = FURTHEST_OUR_RAY_CAN_REACH;
finalID = -1.;
}
return vec2( finalDistanceTraveledByRay , finalID );
}
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
// Here we are calcuting the normal of the surface
// Although it looks like alot of code, it actually
// is just trying to do something very simple, which
// is to figure out in what direction the SDF is increasing.
// What is amazing, is that this value is the same thing
// as telling you what direction the surface faces, AKA the
// normal of the surface.
vec3 getNormalOfSurface( in vec3 positionOfHit ){
vec3 tinyChangeX = vec3( 0.001, 0.0, 0.0 );
vec3 tinyChangeY = vec3( 0.0 , 0.001 , 0.0 );
vec3 tinyChangeZ = vec3( 0.0 , 0.0 , 0.001 );
float upTinyChangeInX = mapTheWorld( positionOfHit + tinyChangeX ).x;
float downTinyChangeInX = mapTheWorld( positionOfHit - tinyChangeX ).x;
float tinyChangeInX = upTinyChangeInX - downTinyChangeInX;
float upTinyChangeInY = mapTheWorld( positionOfHit + tinyChangeY ).x;
float downTinyChangeInY = mapTheWorld( positionOfHit - tinyChangeY ).x;
float tinyChangeInY = upTinyChangeInY - downTinyChangeInY;
float upTinyChangeInZ = mapTheWorld( positionOfHit + tinyChangeZ ).x;
float downTinyChangeInZ = mapTheWorld( positionOfHit - tinyChangeZ ).x;
float tinyChangeInZ = upTinyChangeInZ - downTinyChangeInZ;
vec3 normal = vec3(
tinyChangeInX,
tinyChangeInY,
tinyChangeInZ
);
return normalize(normal);
}
// doing our background color is easy enough,
// just make it pure black. like my soul.
vec3 doBackgroundColor(){
return vec3( 0.75 );
}
vec3 doBalloonColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 balloonColor = vec3( 1. , 0. , 0. );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = balloonColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
vec3 doTorusColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 torusColor = vec3( 0.25 , 0.95 , 0.25 );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = torusColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
// Here we are using the normal of the surface,
// and mapping it to color, to show you just how cool
// normals can be!
vec3 doBoxColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 color = vec3( normalOfSurface.x , normalOfSurface.y , normalOfSurface.z );
//could also just write color = normalOfSurce
//but trying to be explicit.
return color;
}
// This is where we decide
// what color the world will be!
// and what marvelous colors it will be!
vec3 colorTheWorld( vec2 rayHitInfo , vec3 eyePosition , vec3 rayDirection ){
// remember for color
// x = red , y = green , z = blue
vec3 color;
// THE LIL RAY WENT ALL THE WAY
// TO THE EDGE OF THE WORLD,
// AND DIDN'T HIT ANYTHING
if( rayHitInfo.y < 0.0 ){
color = doBackgroundColor();
// THE LIL RAY HIT SOMETHING!!!!
}else{
// If we hit something,
// we also know how far the ray has to travel to hit it
// and because we know the direction of the ray, we can
// get the exact position of where we hit the surface
// by following the ray from the eye, along its direction
// for the however far it had to travel to hit something
vec3 positionOfHit = eyePosition + rayHitInfo.x * rayDirection;
// We can then use this information to tell what direction
// the surface faces in
vec3 normalOfSurface = getNormalOfSurface( positionOfHit );
// 1.0 is the Balloon ID
if( rayHitInfo.y == 1.0 ){
color = doBalloonColor( positionOfHit , normalOfSurface );
// 2.0 is the Box ID
}else if( rayHitInfo.y == 2.0 ){
color = doBoxColor( positionOfHit , normalOfSurface );
}
else if( rayHitInfo.y == 3.0)
{
color = doTorusColor( positionOfHit , normalOfSurface );
}
}
return color;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
// Here we are getting our 'Position' of each pixel
// This section is important, because if we didn't
// divied by the resolution, our values would be masssive
// as fragCoord returns the value of how many pixels over we
// are. which is alot :)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// thats a super long name, so maybe we will
// keep on using uv, but im explicitly defining it
// so you can see exactly what those two letters mean
vec2 xyPositionOfPixelInWindow = p;
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// We use the eye position to tell use where the viewer is
float camRotSpeed = 0.5;
float rotRadius = 2.75;
float eyePosX = rotRadius * cos( camRotSpeed * iTime);
float eyePosZ = rotRadius * sin( camRotSpeed * iTime);
vec3 eyePosition = vec3( eyePosX, 0.5, eyePosZ); //vec3( 0., 0.5, 2.);
// This is the point the view is looking at.
// The window will be placed between the eye, and the
// position the eye is looking at!
vec3 pointWeAreLookingAt = vec3( 0. , 0. , 0. );
// This is where the magic of actual mathematics
// gives a way to actually place the window.
// the 0. at the end there gives the 'roll' of the transformation
// AKA we would be standing so up is up, but up could be changing
// like if we were one of those creepy dolls whos rotate their head
// all the way around along the z axis
mat3 eyeTransformationMatrix = calculateEyeRayTransformationMatrix( eyePosition , pointWeAreLookingAt , 0. );
// Here we get the actual ray that goes out of the eye
// and through the individual pixel! This basically the only thing
// that is different between the pixels, but is also the bread and butter
// of ray tracing. It should be since it has the word 'ray' in its variable name...
// the 2. at the end is the 'lens length' . I don't know how to best
// describe this, but once the full scene is built, tryin playing with it
// to understand inherently how it works
vec3 rayComingOutOfEyeDirection = normalize( eyeTransformationMatrix * vec3( p.xy , 2. ) );
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
vec2 rayHitInfo = checkRayHit( eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
vec3 color = colorTheWorld( rayHitInfo , eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
fragColor = vec4(color,1.0);
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
}
| cc0-1.0 | [
16457,
16474,
16517,
16517,
17738
] | [
[
15590,
15992,
16075,
16075,
16253
],
[
16457,
16474,
16517,
16517,
17738
],
[
17740,
17740,
17773,
17773,
17838
],
[
17840,
17840,
17884,
17884,
18130
],
[
18132,
18132,
18169,
18169,
18519
],
[
18521,
18521,
18552,
18552,
18668
],
[
18670,
18670,
18706,
18770,
18799
],
[
18802,
18802,
18841,
18882,
19967
],
[
19970,
20165,
20221,
20221,
20605
],
[
20613,
20765,
20809,
20809,
21118
],
[
22490,
22490,
22553,
22758,
27037
],
[
27214,
27576,
27625,
27625,
28622
],
[
28628,
28716,
28741,
28741,
28765
],
[
28770,
28770,
28834,
28834,
29925
],
[
29929,
29929,
29991,
29991,
31084
],
[
31087,
31208,
31268,
31268,
31467
],
[
31472,
31573,
31650,
31714,
33042
],
[
33046,
33046,
33103,
33547,
36672
]
] | //'TAG: BALLOON'
| vec2 sdfBalloon( vec3 currentRayPosition ){ |
float ballOrbitSpeed = 0.85;
float ballOrbitRadius = 1.0;
vec3 ballOrbitOffset = vec3(1.0,0,0);
float balloonPosX = ballOrbitRadius * cos( ballOrbitSpeed * iTime);
float balloonPosY = ballOrbitRadius * sin( ballOrbitSpeed * iTime);
// First we define our balloon position
vec3 balloonPosition = ballOrbitOffset + vec3(balloonPosX,balloonPosY,0); //vec3( -1.3 , .3 , -0.4 );
// than we define our balloon radius
float balloonRadius = 0.51;
// Here we get the distance to the surface of the balloon
float distanceToBalloon = length( currentRayPosition - balloonPosition );
// finally we get the distance to the balloon surface
// by substacting the balloon radius. This means that if
// the distance to the balloon is less than the balloon radius
// the value we get will be negative! giving us the 'Signed' in
// Signed Distance Field!
float distanceToBalloonSurface = distanceToBalloon - balloonRadius;
// Finally we build the full balloon information, by giving it an ID
float balloonID = 1.;
// And there we have it! A fully described balloon!
vec2 balloon = vec2( distanceToBalloonSurface, balloonID );
return balloon;
} | //'TAG: BALLOON'
vec2 sdfBalloon( vec3 currentRayPosition ){ | 1 | 2 |
4d33z4 | sagarpatel | 2015-11-23T08:44:22 | // @sagzorz
// My first shader on ShaderToy!
// The stuff below is pretty much all of the amazing @cabbibo's SDF tutorial
// https://www.shadertoy.com/view/Xl2XWt
// I read thorugh it then looked at IQ's page on distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// got inspired and remixed stuff in really messy code
// my only excuse was that I was in a rush since I did the tutorial and my hack all in a bus ride
// from Ha Long Bay to Hanoi and batteries were starting to run out :/
/*
CC0 1.0
@vrtree
who@tree.is
http://tree.is
I dont know if this is going to work, or be interesting,
or even understandable, But hey! Why not try!
To start, get inspired by some MAGICAL creations made by raytracing:
Volcanic by IQ
https://www.shadertoy.com/view/XsX3RB
Remnant X by Dave_Hoskins ( Audio Autoplay warnings )
https://www.shadertoy.com/view/4sjSW1
Cloud Ten by Nimitz
https://www.shadertoy.com/view/XtS3DD
Spectacles by MEEEEEE
https://www.shadertoy.com/view/4lBXWt
[2TC 15] Mystery Mountains by Dave_Hoskins
https://www.shadertoy.com/view/llsGW7
Raytracing graphics is kinda like baking cakes.
I want yall to first see how magical
the cake can be before trying to learn how to make it, because the thing we
make at first isn't going to be one of those crazy 10 story wedding cakes. its just
going to be some burnt sugar bread.
Making art using code can be so fufilling, and so infinite, but to get there you
need to learn some techniques that might not seem that inspiring. To bake a cake,
you first need to turn on an oven, and need to know what an oven even is. In this
tutorial we are going to be learning how to make the oven, how to turn it on,
and how to mix ingredients. as you can see on our left, our cake isn't very pretty
but it is a cake. and thats pretty crazy for just one tutorial!
Once you have gone through this tutorial, you can see a 'minimized' version
here: https://www.shadertoy.com/view/Xt2XDt
where I've rewritten it using the varibles and functions that
are used alot throughout shadertoy. The inspiration examples above
probably seem completely insane, because of all the single letter variable
names, but keep in mind, that they all start with most of the same ingredients
and overn that we will learn about right now!
I've tried to break up the code into 'sections'
which have the 'SECTION 'BLAH'' label above them. Not sure
if thats gonna help or not, but please leave comments
if you think something works or doesn't work, slash you
have any questions!!!
or contact me at @vrtree || @cabbibo
Cheat sheet for vectors:
x = left / right
y = up / down
z = forwards / backwards
also, for vectors labeled 'color'
x = red
y = green
z = blue
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
The best metaphor that I can think of for raytracing is
that the rectangle to our left is actually just a small window
into a fantastic world. We need to describe that world,
so that we can see it. BUT HOW ?!?!?!
What we are doing below is describing what color each pixel
of the window is, however because of the way that shader
programs work, we need to give the same instruction to every
single PIXEL ( or in shadertoy terms, FRAGMENT )
in the window. This is where the term SIMD comes
from : Same Instruction Multiple Data
In this case, the same instruction is the program below,
and the multiple data is the marvelous little piece of magic
called 'fragCoord' which is just the position of the pixel in
window. lets rename some things to look prettier.
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
If you think about what happens with an actual window, you
can begin to get an idea of how the magic of raytracing works
basically a bunch of rays come from the sun ( and or other
light sources ) , bounce around a bunch ( or a little ), and
eventually make it through the window, and into our eyes.
Now the number of rays are masssiveeee that come from the sun
and alot of them that are bouncing around, will end up going
directions that aren't even close to the window, or maybe
will hit the wall instead of the window.
We only care about the rays that go through the window
and make it to our eyeballs!
This means that we can be a bit intelligent. Instead of
figuring out the rays that come from the sun and bounce around
lets start with out eyes, and work backwards!!!!
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
After setting up all the neccesary ray information,
we FINALLY get to start building the scene. Up to this point,
we've only built up the window, and the rays that go from our
eyes through the window, but now we need to describe to the rays
if they hit anything and what they hit!
Now this part has some pretty scary code in it ( whenever I look
at it at least, my eyes glaze over ), so feel free to skip over
the checkRayHit function. I tried to explain it as best as I could
down below, and you might want to come back to it after going
throught the rest of the tutorial, but the important thing to
remember is the following:
These 'rays' that we've been talking about will move through the
scene along their direction. They do this iteratively, and at each
step will basically ask the question :
'HOW CLOSE AM I TO THINGS IN THE WORLD???'
because well, rays are lonely, and want to be closer to things in
the world. We provide them an answer to that question using our
description of the world, and they use this information to tell
them how much further along their path they should move. If the
answer to the question is:
'Lovely little ray, you are actually touching a thing in the world!'
We know what that the ray hit something, and can begin with our next
step!
The tricky part about this is that we have to as accuratly as
possible provide them an answer to their question 'how close??!!'
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
To answer the above concept, we are going to use this magical
concept called:
'Signed Distance Fields'
-----------------------
These things are the best, and very basically can be describe as
a function that takes in a position, and feeds back a value of
how close you are to a thing. If the value of this distance is negative
you are inside the thing, if it is positive, you are outside the thing
and if its 0 you are at the surface of the thing! This positive or negative
gives us the 'Signed' in 'Signed Distance Field'
For a super intensive description of many of the SDFs out there
check out Inigo Quilez's site:
http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
Also, if you want a deep dive into why these functions are the
ultimate magic, check out this crazy paper by the geniouses
over at Media Molecule about their new game: 'DREAMS'
http://media.lolrus.mediamolecule.com/AlexEvans_SIGGRAPH-2015.pdf
Needless to say, these lil puppies are super amazing, and are
here to free us from the tyranny of polygons.
---------
We are going to put all of our SDFs into a single function called
'mapTheWorld'
which will take in a position, and feed back two values.
The first value is the Distance of Signed Distance Field, and the
second value will tell us what we are closest too, so that if
we actually hit something, we can tell what it is. We will denote this
by an 'ID' value.
The hardest part for me to wrap my head around for this was the fact that
these fields do not just describe where the surface of an object is,
they actually describe how far you are from the object from ANYWHERE
in the world.
For example, if I was hitting a round ballon ( AKA a sphere :) )
I wouldn't just know if I was on the surface of the ballon, I would have
to know how close I was to the balloon from anywhere in space.
Check out the 'TAG : BALLOON' in the mapTheWorld function for more detail :)
I've also made a function for a box, that is slightly more complex, and to be
honest, I don't exactly understand the math of it, but the beauty of programming
is that someone else ( AKA Inigo ) does, and I can steal his knowledge, just by
looking at the functions from his website!
---------
One of the magical properties of SDFs is how easily they can be combined
contorted, and manipulated. They are just these lil functions that take
in a position and give back a distance value, so we can do things like play with the
input position, play with the output distance value, or just about anything
else.
We'll start by combining two SDFs by asking the simple question
'Which thing am I closer to?'
which is as simple as a '>' because we already know exactly how close we are
to each thing!
check out 'TAG : WHICH AM I CLOSER TO?' for more enough
We use these function to create a map of the world for the rays to navigate,
and than pass that map to the checkRayHit, which propates the rays throughout
the world and tells us what they hit.
Once they know that, we can FINALLY do our last step:
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD!
//--------------------------------------------------------------
At the end of our checkRayHit function we return a vec2 with two values:
.x is the distance that our ray traveled before hitting
.y is the ID of the thing that we hit.
if .y is less that 0.0 that means that our ray went as far as we allowed it
to go without hitting anything. thats one lonely ray :(
however, that doesn't mean that the ray didn't hit anything. It just meant
that it is part of the background.
Thanks little ray!
You told us important information about our scene,
and your hard work is helping to create the world!
We can get reallly crazy with how we color the background of the scene,
but for this tutorial lets just keep it black, because who doesn't love
the void.
we will use the function 'doBackgroundColor' to accomplish this task!
That tells us about the background, but what if .y is greater than 0.0?
then we get to make some stuff in the scene!
if the ID is equal to balloon id, then we 'doBalloonColor'
and if the ID is equal to the box , then we 'doBoxColor'
This is all that we need if we want to color simple solid objects,
but what if we want to add some shading, by doing what we originally
talked about, that is, following the ray to the sun?
For this first tutorial, we will keep it to a very naive approach,
but once you get the basics of sections A - D, we can get SUPER crazy
with this 'color' the world section.
For example, we could reflect the
ray off the surface, and than repeat the checkRayHit with this new information
continuing to follow this ray through more and more of the world. we could
repeat this process again and again, and even though our gpu would hate us
we could continue bouncing around until we got to a light source!
In a later tutorial we will do exactly this, but for now,
we are going to do 1 simple task:
See how much the surface that we hit, faces the sun.
to do that we need to do 2 things.
First, determine which way the surface faces
Second, determine which way rays go from the surface to get to the sun
1) To determine the way that the surface faces, we will use a function called
'getNormalOfSurface' This function will either make 100% sense, or 0% sense
depending on how often you have played with fields, but it made 0% sense to me
for many years, so don't worry if you don't get it! Whats important is that
it gives us the direction that the surface faces, which we call its 'Normal'
You can think of it as a vector that is perpendicular to the surface at a specific point
So that it is easier to understand what this value is, we are actually going to color our
box based on this value. We will map the X value of the normal to red, the Y value of the
normal to green and the Z value of the normal to blue. You can see this more in the
'doBoxColor' function
2) To get the direction the rays go to get to the sun, we just need to subtract the sun
position from the position of where we hit. This will provide us a direction from the sun
to the position. Look inside the doBalloonColor to see this calculation happen.
this will give us the direction of the rays from the sun to the surface!
Now that we have these 2 pieces of information, the last thing we need to do is see
how much the two vectors ( the normal and the light direction ) 'Face' each other.
that word 'Face', might not make much sense in this context, but think about it this way.
If you have a table, and a light above the table, the top of the table will 'Face',
the light, and the bottom of the table will 'Face' away from the light. The surface
that 'Faces' the light will get hit by the rays from the light, while the surface
that 'Faces' away from the light will be totally dark!
so how do we get this 'Face' value ( pun intended :p ) ?
There is a magical function called a 'dot product' which does exactly this. you
can read more here:
https://en.wikipedia.org/wiki/Dot_product
basically this function takes in 2 vectors, and feeds back a value from -1 -> 1.
if the value is -1 , the two vectors face in exact opposite directions, and if
the value is 1 , the two vectors face in exactly the same direction. if the value is
0, than they are perpendicular!
By using the dot product, we take get the ballon's 'Face' value and color it depending
on this value!
check out the doBallonColor to see all this craziness in action
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
What a journey it has been. Remember back when we were talking about
sending rays through the window? Remember them moving all through the
world trying to be closer to things?
So much has happened, and at the end of that journey, we got a color for each ray!
now all we need to do is output that color onto the screen , which is a single call,
and we've made our world.
I know this stuff might seem too dry or too complex at times, too confusing,
too frustrating, but I promise, if you stick with it, you'll soon be making some of the
other magical structures you see throughout the rest of this site.
I'll be trying to do some more of these tutorials, and you'll see that VERY
quickly, you get from this hideous monstrosity to our left, to marvelous worlds
filled with lights, colors, and love.
Thanks for staying around, and please contact me:
@vrtree , @cabbibo with questions, concerns , and improvments. Or just comment!
*/
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// Most of this is taken from many of the shaders
// that @iq have worked on. Make sure to check out
// more of his magic!!!
// This calculation basically gets a way for us to
// transform the rays coming out of our eyes and going through the window.
// If it doesn't make sense, thats ok. It doesn't make sense to me either :)
// Whats important to remember is that this basically gives us a way to position
// our window. We could you it to make the window look north, south, east, west, up, down
// or ANYWHERE in between!
mat3 calculateEyeRayTransformationMatrix( in vec3 ro, in vec3 ta, in float roll )
{
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(sin(roll),cos(roll),0.0) ) );
vec3 vv = normalize( cross(uu,ww));
return mat3( uu, vv, ww );
}
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
//'TAG: BALLOON'
vec2 sdfBalloon( vec3 currentRayPosition ){
float ballOrbitSpeed = 0.85;
float ballOrbitRadius = 1.0;
vec3 ballOrbitOffset = vec3(1.0,0,0);
float balloonPosX = ballOrbitRadius * cos( ballOrbitSpeed * iTime);
float balloonPosY = ballOrbitRadius * sin( ballOrbitSpeed * iTime);
// First we define our balloon position
vec3 balloonPosition = ballOrbitOffset + vec3(balloonPosX,balloonPosY,0); //vec3( -1.3 , .3 , -0.4 );
// than we define our balloon radius
float balloonRadius = 0.51;
// Here we get the distance to the surface of the balloon
float distanceToBalloon = length( currentRayPosition - balloonPosition );
// finally we get the distance to the balloon surface
// by substacting the balloon radius. This means that if
// the distance to the balloon is less than the balloon radius
// the value we get will be negative! giving us the 'Signed' in
// Signed Distance Field!
float distanceToBalloonSurface = distanceToBalloon - balloonRadius;
// Finally we build the full balloon information, by giving it an ID
float balloonID = 1.;
// And there we have it! A fully described balloon!
vec2 balloon = vec2( distanceToBalloonSurface, balloonID );
return balloon;
}
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
float opTwist_Torus( vec3 p , vec2 torusS)
{
float twistSpedd = 0.35;
float c = cos( 15.0 * (sin( twistSpedd * iTime)) *p.y );
float s = sin( 15.0 * (sin( twistSpedd * iTime)) *p.y );
mat2 m = mat2(c,-s,s,c);
vec3 q = vec3(m*p.xz,p.y);
return sdTorus(q, torusS);
}
vec2 sdfTorus( vec3 currentRayPos )
{
vec3 torusPos = vec3( 0.0, 0.0, 0.0);
vec2 torusSpec = vec2(0.6, 0.23);
vec3 adjustedRayPos = currentRayPos - torusPos;
float distToTorusSurface = opTwist_Torus(adjustedRayPos, torusSpec); //sdTorus(adjustedRayPos, torusSpec);
float torusID = 3.;
vec2 torus = vec2( distToTorusSurface, torusID);
return torus;
}
float smin( float a, float b)
{
float k = 0.77521;
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
float opBlend( float d1, float d2)
{
//float d1 = primitiveA(p);
//float d2 = primitiveB(p);
return smin( d1, d2 );
}
vec2 sdfBox( vec3 currentRayPosition ){
// First we define our box position
vec3 boxPosition = vec3( -.8 , -.4 , 0.2 );
// than we define our box dimensions using x , y and z
vec3 boxSize = vec3( .4 , .3 , .2 );
// Here we get the 'adjusted ray position' which is just
// writing the point of the ray as if the origin of the
// space was where the box was positioned, instead of
// at 0,0,0 . AKA the difference between the vectors in
// vector format.
vec3 adjustedRayPosition = currentRayPosition - boxPosition;
// finally we get the distance to the box surface.
// I don't get this part very much, but I bet Inigo does!
// Thanks for making code for us IQ !
vec3 distanceVec = abs( adjustedRayPosition ) - boxSize;
float maxDistance = max( distanceVec.x , max( distanceVec.y , distanceVec.z ) );
float distanceToBoxSurface = min( maxDistance , 0.0 ) + length( max( distanceVec , 0.0 ) );
// Finally we build the full box information, by giving it an ID
float boxID = 2.;
// And there we have it! A fully described box!
vec2 box = vec2( distanceToBoxSurface, boxID );
return box;
}
// 'TAG : WHICH AM I CLOSER TO?'
// This function takes in two things
// and says which is closer by using the
// distance to each thing, comparing them
// and returning the one that is closer!
vec2 whichThingAmICloserTo( vec2 thing1 , vec2 thing2 ){
vec2 closestThing;
// Check out the balloon function
// and remember how the x of the returned
// information is the distance, and the y
// is the id of the thing!
if( thing1.x <= thing2.x ){
closestThing = thing1;
}else if( thing2.x < thing1.x ){
closestThing = thing2;
}
return closestThing;
}
// Takes in the position of the ray, and feeds back
// 2 values of how close it is to things in the world
// what thing it is closest two in the world.
vec2 mapTheWorld( vec3 currentRayPosition ){
vec2 result;
vec2 balloon = sdfBalloon( currentRayPosition );
//vec2 box = sdfBox( currentRayPosition );
vec2 torus = sdfTorus( currentRayPosition );
result = whichThingAmICloserTo( balloon , torus); //box );
result.x = opBlend( balloon.x, torus.x);
return result;
}
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
// We want to know when the closeness to things in the world is
// 0.0 , but if we wanted to get exactly to 0 it would take us
// alot of time to be that precise. Here we define the laziness
// our navigation function. try chaning the value to see what it does!
// if you are getting too low of framerates, this value will help alot,
// but can also make your scene look very different
// from how it should
const float HOW_CLOSE_IS_CLOSE_ENOUGH = 0.0001;
// This is basically how big our scene is. each ray will be shot forward
// until it reaches this distance. the smaller it is, the quicker the
// ray will reach the edge, which should help speed up this function
const float FURTHEST_OUR_RAY_CAN_REACH = 10.75;
// This is how may steps our ray can take. Hopefully for this
// simple of a world, it will very quickly get to the 'close enough' value
// and stop the iteration, but for more complex scenes, this value
// will dramatically change not only how good the scene looks
// but how fast teh scene can render.
// remember that for each pixel we are displaying, the 'mapTheWorld' function
// could be called this many times! Thats ALOT of calculations!!!
const int HOW_MANY_STEPS_CAN_OUR_RAY_TAKE = 2000;
vec2 checkRayHit( in vec3 eyePosition , in vec3 rayDirection ){
//First we set some default values
// our distance to surface will get overwritten every step,
// so all that is important is that it is greater than our
// 'how close is close enough' value
float distanceToSurface = HOW_CLOSE_IS_CLOSE_ENOUGH * 2.;
// The total distance traveled by the ray obviously should start at 0
float totalDistanceTraveledByRay = 0.;
// if we hit something, this value will be overwritten by the
// totalDistance traveled, and if we don't hit something it will
// be overwritten by the furthest our ray can reach,
// so it can be whatever!
float finalDistanceTraveledByRay = -1.;
// if our id is less that 0. , it means we haven't hit anything
// so lets start by saying we haven't hit anything!
float finalID = -1.;
//here is the loop where the magic happens
for( int i = 0; i < HOW_MANY_STEPS_CAN_OUR_RAY_TAKE; i++ ){
// First off, stop the iteration, if we are close enough to the surface!
if( distanceToSurface < HOW_CLOSE_IS_CLOSE_ENOUGH ) break;
// Second off, stop the iteration, if we have reached the end of our scene!
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ) break;
// To check how close we are to things in the world,
// we need to get a position in the scene. to do this,
// we start at the rays origin, AKA the eye
// and move along the ray direction, the amount we have already traveled.
vec3 currentPositionOfRay = eyePosition + rayDirection * totalDistanceTraveledByRay;
// Distance to and ID of things in the world
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
vec2 distanceAndIDOfThingsInTheWorld = mapTheWorld( currentPositionOfRay );
// we get out the results from our mapping of the world
// I am reassigning them for clarity
float distanceToThingsInTheWorld = distanceAndIDOfThingsInTheWorld.x;
float idOfClosestThingInTheWorld = distanceAndIDOfThingsInTheWorld.y;
// We save out the distance to the surface, so that
// next iteration we can check to see if we are close enough
// to stop all this silly iteration
distanceToSurface = distanceToThingsInTheWorld;
// We are also finalID to the current closest id,
// because if we hit something, we will have the proper
// id, and we can skip reassigning it later!
finalID = idOfClosestThingInTheWorld;
// ATTENTION: THIS THING IS AWESOME!
// This last little calculation is probably the coolest hack
// of this entire tutorial. If we wanted too, we could basically
// step through the field at a constant amount, and at every step
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// that would take FOREVER, and get really annoying.
// Instead what we say is 'How far until we are there?'
// and move forward by that amount. This means that if
// we are really far away from everything, we can make large
// movements towards the surface, and if we are closer
// we can make more precise movements. making our marching functino
// faster, and ideally more precise!!
// WOW!
totalDistanceTraveledByRay += 0.05 * distanceToThingsInTheWorld; //0.001 + distanceToThingsInTheWorld * abs(sin(iTime)); //distanceToThingsInTheWorld;
}
// if we hit something set the finalDirastnce traveled by
// ray to that distance!
if( totalDistanceTraveledByRay < FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = totalDistanceTraveledByRay;
}
// If the total distance traveled by the ray is further than
// the ray can reach, that means that we've hit the edge of the scene
// Set the final distance to be the edge of the scene
// and the id to -1 to make sure we know we haven't hit anything
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = FURTHEST_OUR_RAY_CAN_REACH;
finalID = -1.;
}
return vec2( finalDistanceTraveledByRay , finalID );
}
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
// Here we are calcuting the normal of the surface
// Although it looks like alot of code, it actually
// is just trying to do something very simple, which
// is to figure out in what direction the SDF is increasing.
// What is amazing, is that this value is the same thing
// as telling you what direction the surface faces, AKA the
// normal of the surface.
vec3 getNormalOfSurface( in vec3 positionOfHit ){
vec3 tinyChangeX = vec3( 0.001, 0.0, 0.0 );
vec3 tinyChangeY = vec3( 0.0 , 0.001 , 0.0 );
vec3 tinyChangeZ = vec3( 0.0 , 0.0 , 0.001 );
float upTinyChangeInX = mapTheWorld( positionOfHit + tinyChangeX ).x;
float downTinyChangeInX = mapTheWorld( positionOfHit - tinyChangeX ).x;
float tinyChangeInX = upTinyChangeInX - downTinyChangeInX;
float upTinyChangeInY = mapTheWorld( positionOfHit + tinyChangeY ).x;
float downTinyChangeInY = mapTheWorld( positionOfHit - tinyChangeY ).x;
float tinyChangeInY = upTinyChangeInY - downTinyChangeInY;
float upTinyChangeInZ = mapTheWorld( positionOfHit + tinyChangeZ ).x;
float downTinyChangeInZ = mapTheWorld( positionOfHit - tinyChangeZ ).x;
float tinyChangeInZ = upTinyChangeInZ - downTinyChangeInZ;
vec3 normal = vec3(
tinyChangeInX,
tinyChangeInY,
tinyChangeInZ
);
return normalize(normal);
}
// doing our background color is easy enough,
// just make it pure black. like my soul.
vec3 doBackgroundColor(){
return vec3( 0.75 );
}
vec3 doBalloonColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 balloonColor = vec3( 1. , 0. , 0. );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = balloonColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
vec3 doTorusColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 torusColor = vec3( 0.25 , 0.95 , 0.25 );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = torusColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
// Here we are using the normal of the surface,
// and mapping it to color, to show you just how cool
// normals can be!
vec3 doBoxColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 color = vec3( normalOfSurface.x , normalOfSurface.y , normalOfSurface.z );
//could also just write color = normalOfSurce
//but trying to be explicit.
return color;
}
// This is where we decide
// what color the world will be!
// and what marvelous colors it will be!
vec3 colorTheWorld( vec2 rayHitInfo , vec3 eyePosition , vec3 rayDirection ){
// remember for color
// x = red , y = green , z = blue
vec3 color;
// THE LIL RAY WENT ALL THE WAY
// TO THE EDGE OF THE WORLD,
// AND DIDN'T HIT ANYTHING
if( rayHitInfo.y < 0.0 ){
color = doBackgroundColor();
// THE LIL RAY HIT SOMETHING!!!!
}else{
// If we hit something,
// we also know how far the ray has to travel to hit it
// and because we know the direction of the ray, we can
// get the exact position of where we hit the surface
// by following the ray from the eye, along its direction
// for the however far it had to travel to hit something
vec3 positionOfHit = eyePosition + rayHitInfo.x * rayDirection;
// We can then use this information to tell what direction
// the surface faces in
vec3 normalOfSurface = getNormalOfSurface( positionOfHit );
// 1.0 is the Balloon ID
if( rayHitInfo.y == 1.0 ){
color = doBalloonColor( positionOfHit , normalOfSurface );
// 2.0 is the Box ID
}else if( rayHitInfo.y == 2.0 ){
color = doBoxColor( positionOfHit , normalOfSurface );
}
else if( rayHitInfo.y == 3.0)
{
color = doTorusColor( positionOfHit , normalOfSurface );
}
}
return color;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
// Here we are getting our 'Position' of each pixel
// This section is important, because if we didn't
// divied by the resolution, our values would be masssive
// as fragCoord returns the value of how many pixels over we
// are. which is alot :)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// thats a super long name, so maybe we will
// keep on using uv, but im explicitly defining it
// so you can see exactly what those two letters mean
vec2 xyPositionOfPixelInWindow = p;
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// We use the eye position to tell use where the viewer is
float camRotSpeed = 0.5;
float rotRadius = 2.75;
float eyePosX = rotRadius * cos( camRotSpeed * iTime);
float eyePosZ = rotRadius * sin( camRotSpeed * iTime);
vec3 eyePosition = vec3( eyePosX, 0.5, eyePosZ); //vec3( 0., 0.5, 2.);
// This is the point the view is looking at.
// The window will be placed between the eye, and the
// position the eye is looking at!
vec3 pointWeAreLookingAt = vec3( 0. , 0. , 0. );
// This is where the magic of actual mathematics
// gives a way to actually place the window.
// the 0. at the end there gives the 'roll' of the transformation
// AKA we would be standing so up is up, but up could be changing
// like if we were one of those creepy dolls whos rotate their head
// all the way around along the z axis
mat3 eyeTransformationMatrix = calculateEyeRayTransformationMatrix( eyePosition , pointWeAreLookingAt , 0. );
// Here we get the actual ray that goes out of the eye
// and through the individual pixel! This basically the only thing
// that is different between the pixels, but is also the bread and butter
// of ray tracing. It should be since it has the word 'ray' in its variable name...
// the 2. at the end is the 'lens length' . I don't know how to best
// describe this, but once the full scene is built, tryin playing with it
// to understand inherently how it works
vec3 rayComingOutOfEyeDirection = normalize( eyeTransformationMatrix * vec3( p.xy , 2. ) );
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
vec2 rayHitInfo = checkRayHit( eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
vec3 color = colorTheWorld( rayHitInfo , eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
fragColor = vec4(color,1.0);
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
}
| cc0-1.0 | [
19970,
20165,
20221,
20221,
20605
] | [
[
15590,
15992,
16075,
16075,
16253
],
[
16457,
16474,
16517,
16517,
17738
],
[
17740,
17740,
17773,
17773,
17838
],
[
17840,
17840,
17884,
17884,
18130
],
[
18132,
18132,
18169,
18169,
18519
],
[
18521,
18521,
18552,
18552,
18668
],
[
18670,
18670,
18706,
18770,
18799
],
[
18802,
18802,
18841,
18882,
19967
],
[
19970,
20165,
20221,
20221,
20605
],
[
20613,
20765,
20809,
20809,
21118
],
[
22490,
22490,
22553,
22758,
27037
],
[
27214,
27576,
27625,
27625,
28622
],
[
28628,
28716,
28741,
28741,
28765
],
[
28770,
28770,
28834,
28834,
29925
],
[
29929,
29929,
29991,
29991,
31084
],
[
31087,
31208,
31268,
31268,
31467
],
[
31472,
31573,
31650,
31714,
33042
],
[
33046,
33046,
33103,
33547,
36672
]
] | // 'TAG : WHICH AM I CLOSER TO?'
// This function takes in two things
// and says which is closer by using the
// distance to each thing, comparing them
// and returning the one that is closer!
| vec2 whichThingAmICloserTo( vec2 thing1 , vec2 thing2 ){ |
vec2 closestThing;
// Check out the balloon function
// and remember how the x of the returned
// information is the distance, and the y
// is the id of the thing!
if( thing1.x <= thing2.x ){
closestThing = thing1;
}else if( thing2.x < thing1.x ){
closestThing = thing2;
}
return closestThing;
} | // 'TAG : WHICH AM I CLOSER TO?'
// This function takes in two things
// and says which is closer by using the
// distance to each thing, comparing them
// and returning the one that is closer!
vec2 whichThingAmICloserTo( vec2 thing1 , vec2 thing2 ){ | 3 | 3 |
4d33z4 | sagarpatel | 2015-11-23T08:44:22 | // @sagzorz
// My first shader on ShaderToy!
// The stuff below is pretty much all of the amazing @cabbibo's SDF tutorial
// https://www.shadertoy.com/view/Xl2XWt
// I read thorugh it then looked at IQ's page on distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// got inspired and remixed stuff in really messy code
// my only excuse was that I was in a rush since I did the tutorial and my hack all in a bus ride
// from Ha Long Bay to Hanoi and batteries were starting to run out :/
/*
CC0 1.0
@vrtree
who@tree.is
http://tree.is
I dont know if this is going to work, or be interesting,
or even understandable, But hey! Why not try!
To start, get inspired by some MAGICAL creations made by raytracing:
Volcanic by IQ
https://www.shadertoy.com/view/XsX3RB
Remnant X by Dave_Hoskins ( Audio Autoplay warnings )
https://www.shadertoy.com/view/4sjSW1
Cloud Ten by Nimitz
https://www.shadertoy.com/view/XtS3DD
Spectacles by MEEEEEE
https://www.shadertoy.com/view/4lBXWt
[2TC 15] Mystery Mountains by Dave_Hoskins
https://www.shadertoy.com/view/llsGW7
Raytracing graphics is kinda like baking cakes.
I want yall to first see how magical
the cake can be before trying to learn how to make it, because the thing we
make at first isn't going to be one of those crazy 10 story wedding cakes. its just
going to be some burnt sugar bread.
Making art using code can be so fufilling, and so infinite, but to get there you
need to learn some techniques that might not seem that inspiring. To bake a cake,
you first need to turn on an oven, and need to know what an oven even is. In this
tutorial we are going to be learning how to make the oven, how to turn it on,
and how to mix ingredients. as you can see on our left, our cake isn't very pretty
but it is a cake. and thats pretty crazy for just one tutorial!
Once you have gone through this tutorial, you can see a 'minimized' version
here: https://www.shadertoy.com/view/Xt2XDt
where I've rewritten it using the varibles and functions that
are used alot throughout shadertoy. The inspiration examples above
probably seem completely insane, because of all the single letter variable
names, but keep in mind, that they all start with most of the same ingredients
and overn that we will learn about right now!
I've tried to break up the code into 'sections'
which have the 'SECTION 'BLAH'' label above them. Not sure
if thats gonna help or not, but please leave comments
if you think something works or doesn't work, slash you
have any questions!!!
or contact me at @vrtree || @cabbibo
Cheat sheet for vectors:
x = left / right
y = up / down
z = forwards / backwards
also, for vectors labeled 'color'
x = red
y = green
z = blue
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
The best metaphor that I can think of for raytracing is
that the rectangle to our left is actually just a small window
into a fantastic world. We need to describe that world,
so that we can see it. BUT HOW ?!?!?!
What we are doing below is describing what color each pixel
of the window is, however because of the way that shader
programs work, we need to give the same instruction to every
single PIXEL ( or in shadertoy terms, FRAGMENT )
in the window. This is where the term SIMD comes
from : Same Instruction Multiple Data
In this case, the same instruction is the program below,
and the multiple data is the marvelous little piece of magic
called 'fragCoord' which is just the position of the pixel in
window. lets rename some things to look prettier.
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
If you think about what happens with an actual window, you
can begin to get an idea of how the magic of raytracing works
basically a bunch of rays come from the sun ( and or other
light sources ) , bounce around a bunch ( or a little ), and
eventually make it through the window, and into our eyes.
Now the number of rays are masssiveeee that come from the sun
and alot of them that are bouncing around, will end up going
directions that aren't even close to the window, or maybe
will hit the wall instead of the window.
We only care about the rays that go through the window
and make it to our eyeballs!
This means that we can be a bit intelligent. Instead of
figuring out the rays that come from the sun and bounce around
lets start with out eyes, and work backwards!!!!
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
After setting up all the neccesary ray information,
we FINALLY get to start building the scene. Up to this point,
we've only built up the window, and the rays that go from our
eyes through the window, but now we need to describe to the rays
if they hit anything and what they hit!
Now this part has some pretty scary code in it ( whenever I look
at it at least, my eyes glaze over ), so feel free to skip over
the checkRayHit function. I tried to explain it as best as I could
down below, and you might want to come back to it after going
throught the rest of the tutorial, but the important thing to
remember is the following:
These 'rays' that we've been talking about will move through the
scene along their direction. They do this iteratively, and at each
step will basically ask the question :
'HOW CLOSE AM I TO THINGS IN THE WORLD???'
because well, rays are lonely, and want to be closer to things in
the world. We provide them an answer to that question using our
description of the world, and they use this information to tell
them how much further along their path they should move. If the
answer to the question is:
'Lovely little ray, you are actually touching a thing in the world!'
We know what that the ray hit something, and can begin with our next
step!
The tricky part about this is that we have to as accuratly as
possible provide them an answer to their question 'how close??!!'
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
To answer the above concept, we are going to use this magical
concept called:
'Signed Distance Fields'
-----------------------
These things are the best, and very basically can be describe as
a function that takes in a position, and feeds back a value of
how close you are to a thing. If the value of this distance is negative
you are inside the thing, if it is positive, you are outside the thing
and if its 0 you are at the surface of the thing! This positive or negative
gives us the 'Signed' in 'Signed Distance Field'
For a super intensive description of many of the SDFs out there
check out Inigo Quilez's site:
http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
Also, if you want a deep dive into why these functions are the
ultimate magic, check out this crazy paper by the geniouses
over at Media Molecule about their new game: 'DREAMS'
http://media.lolrus.mediamolecule.com/AlexEvans_SIGGRAPH-2015.pdf
Needless to say, these lil puppies are super amazing, and are
here to free us from the tyranny of polygons.
---------
We are going to put all of our SDFs into a single function called
'mapTheWorld'
which will take in a position, and feed back two values.
The first value is the Distance of Signed Distance Field, and the
second value will tell us what we are closest too, so that if
we actually hit something, we can tell what it is. We will denote this
by an 'ID' value.
The hardest part for me to wrap my head around for this was the fact that
these fields do not just describe where the surface of an object is,
they actually describe how far you are from the object from ANYWHERE
in the world.
For example, if I was hitting a round ballon ( AKA a sphere :) )
I wouldn't just know if I was on the surface of the ballon, I would have
to know how close I was to the balloon from anywhere in space.
Check out the 'TAG : BALLOON' in the mapTheWorld function for more detail :)
I've also made a function for a box, that is slightly more complex, and to be
honest, I don't exactly understand the math of it, but the beauty of programming
is that someone else ( AKA Inigo ) does, and I can steal his knowledge, just by
looking at the functions from his website!
---------
One of the magical properties of SDFs is how easily they can be combined
contorted, and manipulated. They are just these lil functions that take
in a position and give back a distance value, so we can do things like play with the
input position, play with the output distance value, or just about anything
else.
We'll start by combining two SDFs by asking the simple question
'Which thing am I closer to?'
which is as simple as a '>' because we already know exactly how close we are
to each thing!
check out 'TAG : WHICH AM I CLOSER TO?' for more enough
We use these function to create a map of the world for the rays to navigate,
and than pass that map to the checkRayHit, which propates the rays throughout
the world and tells us what they hit.
Once they know that, we can FINALLY do our last step:
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD!
//--------------------------------------------------------------
At the end of our checkRayHit function we return a vec2 with two values:
.x is the distance that our ray traveled before hitting
.y is the ID of the thing that we hit.
if .y is less that 0.0 that means that our ray went as far as we allowed it
to go without hitting anything. thats one lonely ray :(
however, that doesn't mean that the ray didn't hit anything. It just meant
that it is part of the background.
Thanks little ray!
You told us important information about our scene,
and your hard work is helping to create the world!
We can get reallly crazy with how we color the background of the scene,
but for this tutorial lets just keep it black, because who doesn't love
the void.
we will use the function 'doBackgroundColor' to accomplish this task!
That tells us about the background, but what if .y is greater than 0.0?
then we get to make some stuff in the scene!
if the ID is equal to balloon id, then we 'doBalloonColor'
and if the ID is equal to the box , then we 'doBoxColor'
This is all that we need if we want to color simple solid objects,
but what if we want to add some shading, by doing what we originally
talked about, that is, following the ray to the sun?
For this first tutorial, we will keep it to a very naive approach,
but once you get the basics of sections A - D, we can get SUPER crazy
with this 'color' the world section.
For example, we could reflect the
ray off the surface, and than repeat the checkRayHit with this new information
continuing to follow this ray through more and more of the world. we could
repeat this process again and again, and even though our gpu would hate us
we could continue bouncing around until we got to a light source!
In a later tutorial we will do exactly this, but for now,
we are going to do 1 simple task:
See how much the surface that we hit, faces the sun.
to do that we need to do 2 things.
First, determine which way the surface faces
Second, determine which way rays go from the surface to get to the sun
1) To determine the way that the surface faces, we will use a function called
'getNormalOfSurface' This function will either make 100% sense, or 0% sense
depending on how often you have played with fields, but it made 0% sense to me
for many years, so don't worry if you don't get it! Whats important is that
it gives us the direction that the surface faces, which we call its 'Normal'
You can think of it as a vector that is perpendicular to the surface at a specific point
So that it is easier to understand what this value is, we are actually going to color our
box based on this value. We will map the X value of the normal to red, the Y value of the
normal to green and the Z value of the normal to blue. You can see this more in the
'doBoxColor' function
2) To get the direction the rays go to get to the sun, we just need to subtract the sun
position from the position of where we hit. This will provide us a direction from the sun
to the position. Look inside the doBalloonColor to see this calculation happen.
this will give us the direction of the rays from the sun to the surface!
Now that we have these 2 pieces of information, the last thing we need to do is see
how much the two vectors ( the normal and the light direction ) 'Face' each other.
that word 'Face', might not make much sense in this context, but think about it this way.
If you have a table, and a light above the table, the top of the table will 'Face',
the light, and the bottom of the table will 'Face' away from the light. The surface
that 'Faces' the light will get hit by the rays from the light, while the surface
that 'Faces' away from the light will be totally dark!
so how do we get this 'Face' value ( pun intended :p ) ?
There is a magical function called a 'dot product' which does exactly this. you
can read more here:
https://en.wikipedia.org/wiki/Dot_product
basically this function takes in 2 vectors, and feeds back a value from -1 -> 1.
if the value is -1 , the two vectors face in exact opposite directions, and if
the value is 1 , the two vectors face in exactly the same direction. if the value is
0, than they are perpendicular!
By using the dot product, we take get the ballon's 'Face' value and color it depending
on this value!
check out the doBallonColor to see all this craziness in action
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
What a journey it has been. Remember back when we were talking about
sending rays through the window? Remember them moving all through the
world trying to be closer to things?
So much has happened, and at the end of that journey, we got a color for each ray!
now all we need to do is output that color onto the screen , which is a single call,
and we've made our world.
I know this stuff might seem too dry or too complex at times, too confusing,
too frustrating, but I promise, if you stick with it, you'll soon be making some of the
other magical structures you see throughout the rest of this site.
I'll be trying to do some more of these tutorials, and you'll see that VERY
quickly, you get from this hideous monstrosity to our left, to marvelous worlds
filled with lights, colors, and love.
Thanks for staying around, and please contact me:
@vrtree , @cabbibo with questions, concerns , and improvments. Or just comment!
*/
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// Most of this is taken from many of the shaders
// that @iq have worked on. Make sure to check out
// more of his magic!!!
// This calculation basically gets a way for us to
// transform the rays coming out of our eyes and going through the window.
// If it doesn't make sense, thats ok. It doesn't make sense to me either :)
// Whats important to remember is that this basically gives us a way to position
// our window. We could you it to make the window look north, south, east, west, up, down
// or ANYWHERE in between!
mat3 calculateEyeRayTransformationMatrix( in vec3 ro, in vec3 ta, in float roll )
{
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(sin(roll),cos(roll),0.0) ) );
vec3 vv = normalize( cross(uu,ww));
return mat3( uu, vv, ww );
}
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
//'TAG: BALLOON'
vec2 sdfBalloon( vec3 currentRayPosition ){
float ballOrbitSpeed = 0.85;
float ballOrbitRadius = 1.0;
vec3 ballOrbitOffset = vec3(1.0,0,0);
float balloonPosX = ballOrbitRadius * cos( ballOrbitSpeed * iTime);
float balloonPosY = ballOrbitRadius * sin( ballOrbitSpeed * iTime);
// First we define our balloon position
vec3 balloonPosition = ballOrbitOffset + vec3(balloonPosX,balloonPosY,0); //vec3( -1.3 , .3 , -0.4 );
// than we define our balloon radius
float balloonRadius = 0.51;
// Here we get the distance to the surface of the balloon
float distanceToBalloon = length( currentRayPosition - balloonPosition );
// finally we get the distance to the balloon surface
// by substacting the balloon radius. This means that if
// the distance to the balloon is less than the balloon radius
// the value we get will be negative! giving us the 'Signed' in
// Signed Distance Field!
float distanceToBalloonSurface = distanceToBalloon - balloonRadius;
// Finally we build the full balloon information, by giving it an ID
float balloonID = 1.;
// And there we have it! A fully described balloon!
vec2 balloon = vec2( distanceToBalloonSurface, balloonID );
return balloon;
}
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
float opTwist_Torus( vec3 p , vec2 torusS)
{
float twistSpedd = 0.35;
float c = cos( 15.0 * (sin( twistSpedd * iTime)) *p.y );
float s = sin( 15.0 * (sin( twistSpedd * iTime)) *p.y );
mat2 m = mat2(c,-s,s,c);
vec3 q = vec3(m*p.xz,p.y);
return sdTorus(q, torusS);
}
vec2 sdfTorus( vec3 currentRayPos )
{
vec3 torusPos = vec3( 0.0, 0.0, 0.0);
vec2 torusSpec = vec2(0.6, 0.23);
vec3 adjustedRayPos = currentRayPos - torusPos;
float distToTorusSurface = opTwist_Torus(adjustedRayPos, torusSpec); //sdTorus(adjustedRayPos, torusSpec);
float torusID = 3.;
vec2 torus = vec2( distToTorusSurface, torusID);
return torus;
}
float smin( float a, float b)
{
float k = 0.77521;
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
float opBlend( float d1, float d2)
{
//float d1 = primitiveA(p);
//float d2 = primitiveB(p);
return smin( d1, d2 );
}
vec2 sdfBox( vec3 currentRayPosition ){
// First we define our box position
vec3 boxPosition = vec3( -.8 , -.4 , 0.2 );
// than we define our box dimensions using x , y and z
vec3 boxSize = vec3( .4 , .3 , .2 );
// Here we get the 'adjusted ray position' which is just
// writing the point of the ray as if the origin of the
// space was where the box was positioned, instead of
// at 0,0,0 . AKA the difference between the vectors in
// vector format.
vec3 adjustedRayPosition = currentRayPosition - boxPosition;
// finally we get the distance to the box surface.
// I don't get this part very much, but I bet Inigo does!
// Thanks for making code for us IQ !
vec3 distanceVec = abs( adjustedRayPosition ) - boxSize;
float maxDistance = max( distanceVec.x , max( distanceVec.y , distanceVec.z ) );
float distanceToBoxSurface = min( maxDistance , 0.0 ) + length( max( distanceVec , 0.0 ) );
// Finally we build the full box information, by giving it an ID
float boxID = 2.;
// And there we have it! A fully described box!
vec2 box = vec2( distanceToBoxSurface, boxID );
return box;
}
// 'TAG : WHICH AM I CLOSER TO?'
// This function takes in two things
// and says which is closer by using the
// distance to each thing, comparing them
// and returning the one that is closer!
vec2 whichThingAmICloserTo( vec2 thing1 , vec2 thing2 ){
vec2 closestThing;
// Check out the balloon function
// and remember how the x of the returned
// information is the distance, and the y
// is the id of the thing!
if( thing1.x <= thing2.x ){
closestThing = thing1;
}else if( thing2.x < thing1.x ){
closestThing = thing2;
}
return closestThing;
}
// Takes in the position of the ray, and feeds back
// 2 values of how close it is to things in the world
// what thing it is closest two in the world.
vec2 mapTheWorld( vec3 currentRayPosition ){
vec2 result;
vec2 balloon = sdfBalloon( currentRayPosition );
//vec2 box = sdfBox( currentRayPosition );
vec2 torus = sdfTorus( currentRayPosition );
result = whichThingAmICloserTo( balloon , torus); //box );
result.x = opBlend( balloon.x, torus.x);
return result;
}
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
// We want to know when the closeness to things in the world is
// 0.0 , but if we wanted to get exactly to 0 it would take us
// alot of time to be that precise. Here we define the laziness
// our navigation function. try chaning the value to see what it does!
// if you are getting too low of framerates, this value will help alot,
// but can also make your scene look very different
// from how it should
const float HOW_CLOSE_IS_CLOSE_ENOUGH = 0.0001;
// This is basically how big our scene is. each ray will be shot forward
// until it reaches this distance. the smaller it is, the quicker the
// ray will reach the edge, which should help speed up this function
const float FURTHEST_OUR_RAY_CAN_REACH = 10.75;
// This is how may steps our ray can take. Hopefully for this
// simple of a world, it will very quickly get to the 'close enough' value
// and stop the iteration, but for more complex scenes, this value
// will dramatically change not only how good the scene looks
// but how fast teh scene can render.
// remember that for each pixel we are displaying, the 'mapTheWorld' function
// could be called this many times! Thats ALOT of calculations!!!
const int HOW_MANY_STEPS_CAN_OUR_RAY_TAKE = 2000;
vec2 checkRayHit( in vec3 eyePosition , in vec3 rayDirection ){
//First we set some default values
// our distance to surface will get overwritten every step,
// so all that is important is that it is greater than our
// 'how close is close enough' value
float distanceToSurface = HOW_CLOSE_IS_CLOSE_ENOUGH * 2.;
// The total distance traveled by the ray obviously should start at 0
float totalDistanceTraveledByRay = 0.;
// if we hit something, this value will be overwritten by the
// totalDistance traveled, and if we don't hit something it will
// be overwritten by the furthest our ray can reach,
// so it can be whatever!
float finalDistanceTraveledByRay = -1.;
// if our id is less that 0. , it means we haven't hit anything
// so lets start by saying we haven't hit anything!
float finalID = -1.;
//here is the loop where the magic happens
for( int i = 0; i < HOW_MANY_STEPS_CAN_OUR_RAY_TAKE; i++ ){
// First off, stop the iteration, if we are close enough to the surface!
if( distanceToSurface < HOW_CLOSE_IS_CLOSE_ENOUGH ) break;
// Second off, stop the iteration, if we have reached the end of our scene!
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ) break;
// To check how close we are to things in the world,
// we need to get a position in the scene. to do this,
// we start at the rays origin, AKA the eye
// and move along the ray direction, the amount we have already traveled.
vec3 currentPositionOfRay = eyePosition + rayDirection * totalDistanceTraveledByRay;
// Distance to and ID of things in the world
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
vec2 distanceAndIDOfThingsInTheWorld = mapTheWorld( currentPositionOfRay );
// we get out the results from our mapping of the world
// I am reassigning them for clarity
float distanceToThingsInTheWorld = distanceAndIDOfThingsInTheWorld.x;
float idOfClosestThingInTheWorld = distanceAndIDOfThingsInTheWorld.y;
// We save out the distance to the surface, so that
// next iteration we can check to see if we are close enough
// to stop all this silly iteration
distanceToSurface = distanceToThingsInTheWorld;
// We are also finalID to the current closest id,
// because if we hit something, we will have the proper
// id, and we can skip reassigning it later!
finalID = idOfClosestThingInTheWorld;
// ATTENTION: THIS THING IS AWESOME!
// This last little calculation is probably the coolest hack
// of this entire tutorial. If we wanted too, we could basically
// step through the field at a constant amount, and at every step
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// that would take FOREVER, and get really annoying.
// Instead what we say is 'How far until we are there?'
// and move forward by that amount. This means that if
// we are really far away from everything, we can make large
// movements towards the surface, and if we are closer
// we can make more precise movements. making our marching functino
// faster, and ideally more precise!!
// WOW!
totalDistanceTraveledByRay += 0.05 * distanceToThingsInTheWorld; //0.001 + distanceToThingsInTheWorld * abs(sin(iTime)); //distanceToThingsInTheWorld;
}
// if we hit something set the finalDirastnce traveled by
// ray to that distance!
if( totalDistanceTraveledByRay < FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = totalDistanceTraveledByRay;
}
// If the total distance traveled by the ray is further than
// the ray can reach, that means that we've hit the edge of the scene
// Set the final distance to be the edge of the scene
// and the id to -1 to make sure we know we haven't hit anything
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = FURTHEST_OUR_RAY_CAN_REACH;
finalID = -1.;
}
return vec2( finalDistanceTraveledByRay , finalID );
}
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
// Here we are calcuting the normal of the surface
// Although it looks like alot of code, it actually
// is just trying to do something very simple, which
// is to figure out in what direction the SDF is increasing.
// What is amazing, is that this value is the same thing
// as telling you what direction the surface faces, AKA the
// normal of the surface.
vec3 getNormalOfSurface( in vec3 positionOfHit ){
vec3 tinyChangeX = vec3( 0.001, 0.0, 0.0 );
vec3 tinyChangeY = vec3( 0.0 , 0.001 , 0.0 );
vec3 tinyChangeZ = vec3( 0.0 , 0.0 , 0.001 );
float upTinyChangeInX = mapTheWorld( positionOfHit + tinyChangeX ).x;
float downTinyChangeInX = mapTheWorld( positionOfHit - tinyChangeX ).x;
float tinyChangeInX = upTinyChangeInX - downTinyChangeInX;
float upTinyChangeInY = mapTheWorld( positionOfHit + tinyChangeY ).x;
float downTinyChangeInY = mapTheWorld( positionOfHit - tinyChangeY ).x;
float tinyChangeInY = upTinyChangeInY - downTinyChangeInY;
float upTinyChangeInZ = mapTheWorld( positionOfHit + tinyChangeZ ).x;
float downTinyChangeInZ = mapTheWorld( positionOfHit - tinyChangeZ ).x;
float tinyChangeInZ = upTinyChangeInZ - downTinyChangeInZ;
vec3 normal = vec3(
tinyChangeInX,
tinyChangeInY,
tinyChangeInZ
);
return normalize(normal);
}
// doing our background color is easy enough,
// just make it pure black. like my soul.
vec3 doBackgroundColor(){
return vec3( 0.75 );
}
vec3 doBalloonColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 balloonColor = vec3( 1. , 0. , 0. );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = balloonColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
vec3 doTorusColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 torusColor = vec3( 0.25 , 0.95 , 0.25 );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = torusColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
// Here we are using the normal of the surface,
// and mapping it to color, to show you just how cool
// normals can be!
vec3 doBoxColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 color = vec3( normalOfSurface.x , normalOfSurface.y , normalOfSurface.z );
//could also just write color = normalOfSurce
//but trying to be explicit.
return color;
}
// This is where we decide
// what color the world will be!
// and what marvelous colors it will be!
vec3 colorTheWorld( vec2 rayHitInfo , vec3 eyePosition , vec3 rayDirection ){
// remember for color
// x = red , y = green , z = blue
vec3 color;
// THE LIL RAY WENT ALL THE WAY
// TO THE EDGE OF THE WORLD,
// AND DIDN'T HIT ANYTHING
if( rayHitInfo.y < 0.0 ){
color = doBackgroundColor();
// THE LIL RAY HIT SOMETHING!!!!
}else{
// If we hit something,
// we also know how far the ray has to travel to hit it
// and because we know the direction of the ray, we can
// get the exact position of where we hit the surface
// by following the ray from the eye, along its direction
// for the however far it had to travel to hit something
vec3 positionOfHit = eyePosition + rayHitInfo.x * rayDirection;
// We can then use this information to tell what direction
// the surface faces in
vec3 normalOfSurface = getNormalOfSurface( positionOfHit );
// 1.0 is the Balloon ID
if( rayHitInfo.y == 1.0 ){
color = doBalloonColor( positionOfHit , normalOfSurface );
// 2.0 is the Box ID
}else if( rayHitInfo.y == 2.0 ){
color = doBoxColor( positionOfHit , normalOfSurface );
}
else if( rayHitInfo.y == 3.0)
{
color = doTorusColor( positionOfHit , normalOfSurface );
}
}
return color;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
// Here we are getting our 'Position' of each pixel
// This section is important, because if we didn't
// divied by the resolution, our values would be masssive
// as fragCoord returns the value of how many pixels over we
// are. which is alot :)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// thats a super long name, so maybe we will
// keep on using uv, but im explicitly defining it
// so you can see exactly what those two letters mean
vec2 xyPositionOfPixelInWindow = p;
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// We use the eye position to tell use where the viewer is
float camRotSpeed = 0.5;
float rotRadius = 2.75;
float eyePosX = rotRadius * cos( camRotSpeed * iTime);
float eyePosZ = rotRadius * sin( camRotSpeed * iTime);
vec3 eyePosition = vec3( eyePosX, 0.5, eyePosZ); //vec3( 0., 0.5, 2.);
// This is the point the view is looking at.
// The window will be placed between the eye, and the
// position the eye is looking at!
vec3 pointWeAreLookingAt = vec3( 0. , 0. , 0. );
// This is where the magic of actual mathematics
// gives a way to actually place the window.
// the 0. at the end there gives the 'roll' of the transformation
// AKA we would be standing so up is up, but up could be changing
// like if we were one of those creepy dolls whos rotate their head
// all the way around along the z axis
mat3 eyeTransformationMatrix = calculateEyeRayTransformationMatrix( eyePosition , pointWeAreLookingAt , 0. );
// Here we get the actual ray that goes out of the eye
// and through the individual pixel! This basically the only thing
// that is different between the pixels, but is also the bread and butter
// of ray tracing. It should be since it has the word 'ray' in its variable name...
// the 2. at the end is the 'lens length' . I don't know how to best
// describe this, but once the full scene is built, tryin playing with it
// to understand inherently how it works
vec3 rayComingOutOfEyeDirection = normalize( eyeTransformationMatrix * vec3( p.xy , 2. ) );
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
vec2 rayHitInfo = checkRayHit( eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
vec3 color = colorTheWorld( rayHitInfo , eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
fragColor = vec4(color,1.0);
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
}
| cc0-1.0 | [
20613,
20765,
20809,
20809,
21118
] | [
[
15590,
15992,
16075,
16075,
16253
],
[
16457,
16474,
16517,
16517,
17738
],
[
17740,
17740,
17773,
17773,
17838
],
[
17840,
17840,
17884,
17884,
18130
],
[
18132,
18132,
18169,
18169,
18519
],
[
18521,
18521,
18552,
18552,
18668
],
[
18670,
18670,
18706,
18770,
18799
],
[
18802,
18802,
18841,
18882,
19967
],
[
19970,
20165,
20221,
20221,
20605
],
[
20613,
20765,
20809,
20809,
21118
],
[
22490,
22490,
22553,
22758,
27037
],
[
27214,
27576,
27625,
27625,
28622
],
[
28628,
28716,
28741,
28741,
28765
],
[
28770,
28770,
28834,
28834,
29925
],
[
29929,
29929,
29991,
29991,
31084
],
[
31087,
31208,
31268,
31268,
31467
],
[
31472,
31573,
31650,
31714,
33042
],
[
33046,
33046,
33103,
33547,
36672
]
] | // Takes in the position of the ray, and feeds back
// 2 values of how close it is to things in the world
// what thing it is closest two in the world.
| vec2 mapTheWorld( vec3 currentRayPosition ){ |
vec2 result;
vec2 balloon = sdfBalloon( currentRayPosition );
//vec2 box = sdfBox( currentRayPosition );
vec2 torus = sdfTorus( currentRayPosition );
result = whichThingAmICloserTo( balloon , torus); //box );
result.x = opBlend( balloon.x, torus.x);
return result;
} | // Takes in the position of the ray, and feeds back
// 2 values of how close it is to things in the world
// what thing it is closest two in the world.
vec2 mapTheWorld( vec3 currentRayPosition ){ | 1 | 3 |
4d33z4 | sagarpatel | 2015-11-23T08:44:22 | // @sagzorz
// My first shader on ShaderToy!
// The stuff below is pretty much all of the amazing @cabbibo's SDF tutorial
// https://www.shadertoy.com/view/Xl2XWt
// I read thorugh it then looked at IQ's page on distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// got inspired and remixed stuff in really messy code
// my only excuse was that I was in a rush since I did the tutorial and my hack all in a bus ride
// from Ha Long Bay to Hanoi and batteries were starting to run out :/
/*
CC0 1.0
@vrtree
who@tree.is
http://tree.is
I dont know if this is going to work, or be interesting,
or even understandable, But hey! Why not try!
To start, get inspired by some MAGICAL creations made by raytracing:
Volcanic by IQ
https://www.shadertoy.com/view/XsX3RB
Remnant X by Dave_Hoskins ( Audio Autoplay warnings )
https://www.shadertoy.com/view/4sjSW1
Cloud Ten by Nimitz
https://www.shadertoy.com/view/XtS3DD
Spectacles by MEEEEEE
https://www.shadertoy.com/view/4lBXWt
[2TC 15] Mystery Mountains by Dave_Hoskins
https://www.shadertoy.com/view/llsGW7
Raytracing graphics is kinda like baking cakes.
I want yall to first see how magical
the cake can be before trying to learn how to make it, because the thing we
make at first isn't going to be one of those crazy 10 story wedding cakes. its just
going to be some burnt sugar bread.
Making art using code can be so fufilling, and so infinite, but to get there you
need to learn some techniques that might not seem that inspiring. To bake a cake,
you first need to turn on an oven, and need to know what an oven even is. In this
tutorial we are going to be learning how to make the oven, how to turn it on,
and how to mix ingredients. as you can see on our left, our cake isn't very pretty
but it is a cake. and thats pretty crazy for just one tutorial!
Once you have gone through this tutorial, you can see a 'minimized' version
here: https://www.shadertoy.com/view/Xt2XDt
where I've rewritten it using the varibles and functions that
are used alot throughout shadertoy. The inspiration examples above
probably seem completely insane, because of all the single letter variable
names, but keep in mind, that they all start with most of the same ingredients
and overn that we will learn about right now!
I've tried to break up the code into 'sections'
which have the 'SECTION 'BLAH'' label above them. Not sure
if thats gonna help or not, but please leave comments
if you think something works or doesn't work, slash you
have any questions!!!
or contact me at @vrtree || @cabbibo
Cheat sheet for vectors:
x = left / right
y = up / down
z = forwards / backwards
also, for vectors labeled 'color'
x = red
y = green
z = blue
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
The best metaphor that I can think of for raytracing is
that the rectangle to our left is actually just a small window
into a fantastic world. We need to describe that world,
so that we can see it. BUT HOW ?!?!?!
What we are doing below is describing what color each pixel
of the window is, however because of the way that shader
programs work, we need to give the same instruction to every
single PIXEL ( or in shadertoy terms, FRAGMENT )
in the window. This is where the term SIMD comes
from : Same Instruction Multiple Data
In this case, the same instruction is the program below,
and the multiple data is the marvelous little piece of magic
called 'fragCoord' which is just the position of the pixel in
window. lets rename some things to look prettier.
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
If you think about what happens with an actual window, you
can begin to get an idea of how the magic of raytracing works
basically a bunch of rays come from the sun ( and or other
light sources ) , bounce around a bunch ( or a little ), and
eventually make it through the window, and into our eyes.
Now the number of rays are masssiveeee that come from the sun
and alot of them that are bouncing around, will end up going
directions that aren't even close to the window, or maybe
will hit the wall instead of the window.
We only care about the rays that go through the window
and make it to our eyeballs!
This means that we can be a bit intelligent. Instead of
figuring out the rays that come from the sun and bounce around
lets start with out eyes, and work backwards!!!!
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
After setting up all the neccesary ray information,
we FINALLY get to start building the scene. Up to this point,
we've only built up the window, and the rays that go from our
eyes through the window, but now we need to describe to the rays
if they hit anything and what they hit!
Now this part has some pretty scary code in it ( whenever I look
at it at least, my eyes glaze over ), so feel free to skip over
the checkRayHit function. I tried to explain it as best as I could
down below, and you might want to come back to it after going
throught the rest of the tutorial, but the important thing to
remember is the following:
These 'rays' that we've been talking about will move through the
scene along their direction. They do this iteratively, and at each
step will basically ask the question :
'HOW CLOSE AM I TO THINGS IN THE WORLD???'
because well, rays are lonely, and want to be closer to things in
the world. We provide them an answer to that question using our
description of the world, and they use this information to tell
them how much further along their path they should move. If the
answer to the question is:
'Lovely little ray, you are actually touching a thing in the world!'
We know what that the ray hit something, and can begin with our next
step!
The tricky part about this is that we have to as accuratly as
possible provide them an answer to their question 'how close??!!'
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
To answer the above concept, we are going to use this magical
concept called:
'Signed Distance Fields'
-----------------------
These things are the best, and very basically can be describe as
a function that takes in a position, and feeds back a value of
how close you are to a thing. If the value of this distance is negative
you are inside the thing, if it is positive, you are outside the thing
and if its 0 you are at the surface of the thing! This positive or negative
gives us the 'Signed' in 'Signed Distance Field'
For a super intensive description of many of the SDFs out there
check out Inigo Quilez's site:
http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
Also, if you want a deep dive into why these functions are the
ultimate magic, check out this crazy paper by the geniouses
over at Media Molecule about their new game: 'DREAMS'
http://media.lolrus.mediamolecule.com/AlexEvans_SIGGRAPH-2015.pdf
Needless to say, these lil puppies are super amazing, and are
here to free us from the tyranny of polygons.
---------
We are going to put all of our SDFs into a single function called
'mapTheWorld'
which will take in a position, and feed back two values.
The first value is the Distance of Signed Distance Field, and the
second value will tell us what we are closest too, so that if
we actually hit something, we can tell what it is. We will denote this
by an 'ID' value.
The hardest part for me to wrap my head around for this was the fact that
these fields do not just describe where the surface of an object is,
they actually describe how far you are from the object from ANYWHERE
in the world.
For example, if I was hitting a round ballon ( AKA a sphere :) )
I wouldn't just know if I was on the surface of the ballon, I would have
to know how close I was to the balloon from anywhere in space.
Check out the 'TAG : BALLOON' in the mapTheWorld function for more detail :)
I've also made a function for a box, that is slightly more complex, and to be
honest, I don't exactly understand the math of it, but the beauty of programming
is that someone else ( AKA Inigo ) does, and I can steal his knowledge, just by
looking at the functions from his website!
---------
One of the magical properties of SDFs is how easily they can be combined
contorted, and manipulated. They are just these lil functions that take
in a position and give back a distance value, so we can do things like play with the
input position, play with the output distance value, or just about anything
else.
We'll start by combining two SDFs by asking the simple question
'Which thing am I closer to?'
which is as simple as a '>' because we already know exactly how close we are
to each thing!
check out 'TAG : WHICH AM I CLOSER TO?' for more enough
We use these function to create a map of the world for the rays to navigate,
and than pass that map to the checkRayHit, which propates the rays throughout
the world and tells us what they hit.
Once they know that, we can FINALLY do our last step:
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD!
//--------------------------------------------------------------
At the end of our checkRayHit function we return a vec2 with two values:
.x is the distance that our ray traveled before hitting
.y is the ID of the thing that we hit.
if .y is less that 0.0 that means that our ray went as far as we allowed it
to go without hitting anything. thats one lonely ray :(
however, that doesn't mean that the ray didn't hit anything. It just meant
that it is part of the background.
Thanks little ray!
You told us important information about our scene,
and your hard work is helping to create the world!
We can get reallly crazy with how we color the background of the scene,
but for this tutorial lets just keep it black, because who doesn't love
the void.
we will use the function 'doBackgroundColor' to accomplish this task!
That tells us about the background, but what if .y is greater than 0.0?
then we get to make some stuff in the scene!
if the ID is equal to balloon id, then we 'doBalloonColor'
and if the ID is equal to the box , then we 'doBoxColor'
This is all that we need if we want to color simple solid objects,
but what if we want to add some shading, by doing what we originally
talked about, that is, following the ray to the sun?
For this first tutorial, we will keep it to a very naive approach,
but once you get the basics of sections A - D, we can get SUPER crazy
with this 'color' the world section.
For example, we could reflect the
ray off the surface, and than repeat the checkRayHit with this new information
continuing to follow this ray through more and more of the world. we could
repeat this process again and again, and even though our gpu would hate us
we could continue bouncing around until we got to a light source!
In a later tutorial we will do exactly this, but for now,
we are going to do 1 simple task:
See how much the surface that we hit, faces the sun.
to do that we need to do 2 things.
First, determine which way the surface faces
Second, determine which way rays go from the surface to get to the sun
1) To determine the way that the surface faces, we will use a function called
'getNormalOfSurface' This function will either make 100% sense, or 0% sense
depending on how often you have played with fields, but it made 0% sense to me
for many years, so don't worry if you don't get it! Whats important is that
it gives us the direction that the surface faces, which we call its 'Normal'
You can think of it as a vector that is perpendicular to the surface at a specific point
So that it is easier to understand what this value is, we are actually going to color our
box based on this value. We will map the X value of the normal to red, the Y value of the
normal to green and the Z value of the normal to blue. You can see this more in the
'doBoxColor' function
2) To get the direction the rays go to get to the sun, we just need to subtract the sun
position from the position of where we hit. This will provide us a direction from the sun
to the position. Look inside the doBalloonColor to see this calculation happen.
this will give us the direction of the rays from the sun to the surface!
Now that we have these 2 pieces of information, the last thing we need to do is see
how much the two vectors ( the normal and the light direction ) 'Face' each other.
that word 'Face', might not make much sense in this context, but think about it this way.
If you have a table, and a light above the table, the top of the table will 'Face',
the light, and the bottom of the table will 'Face' away from the light. The surface
that 'Faces' the light will get hit by the rays from the light, while the surface
that 'Faces' away from the light will be totally dark!
so how do we get this 'Face' value ( pun intended :p ) ?
There is a magical function called a 'dot product' which does exactly this. you
can read more here:
https://en.wikipedia.org/wiki/Dot_product
basically this function takes in 2 vectors, and feeds back a value from -1 -> 1.
if the value is -1 , the two vectors face in exact opposite directions, and if
the value is 1 , the two vectors face in exactly the same direction. if the value is
0, than they are perpendicular!
By using the dot product, we take get the ballon's 'Face' value and color it depending
on this value!
check out the doBallonColor to see all this craziness in action
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
What a journey it has been. Remember back when we were talking about
sending rays through the window? Remember them moving all through the
world trying to be closer to things?
So much has happened, and at the end of that journey, we got a color for each ray!
now all we need to do is output that color onto the screen , which is a single call,
and we've made our world.
I know this stuff might seem too dry or too complex at times, too confusing,
too frustrating, but I promise, if you stick with it, you'll soon be making some of the
other magical structures you see throughout the rest of this site.
I'll be trying to do some more of these tutorials, and you'll see that VERY
quickly, you get from this hideous monstrosity to our left, to marvelous worlds
filled with lights, colors, and love.
Thanks for staying around, and please contact me:
@vrtree , @cabbibo with questions, concerns , and improvments. Or just comment!
*/
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// Most of this is taken from many of the shaders
// that @iq have worked on. Make sure to check out
// more of his magic!!!
// This calculation basically gets a way for us to
// transform the rays coming out of our eyes and going through the window.
// If it doesn't make sense, thats ok. It doesn't make sense to me either :)
// Whats important to remember is that this basically gives us a way to position
// our window. We could you it to make the window look north, south, east, west, up, down
// or ANYWHERE in between!
mat3 calculateEyeRayTransformationMatrix( in vec3 ro, in vec3 ta, in float roll )
{
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(sin(roll),cos(roll),0.0) ) );
vec3 vv = normalize( cross(uu,ww));
return mat3( uu, vv, ww );
}
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
//'TAG: BALLOON'
vec2 sdfBalloon( vec3 currentRayPosition ){
float ballOrbitSpeed = 0.85;
float ballOrbitRadius = 1.0;
vec3 ballOrbitOffset = vec3(1.0,0,0);
float balloonPosX = ballOrbitRadius * cos( ballOrbitSpeed * iTime);
float balloonPosY = ballOrbitRadius * sin( ballOrbitSpeed * iTime);
// First we define our balloon position
vec3 balloonPosition = ballOrbitOffset + vec3(balloonPosX,balloonPosY,0); //vec3( -1.3 , .3 , -0.4 );
// than we define our balloon radius
float balloonRadius = 0.51;
// Here we get the distance to the surface of the balloon
float distanceToBalloon = length( currentRayPosition - balloonPosition );
// finally we get the distance to the balloon surface
// by substacting the balloon radius. This means that if
// the distance to the balloon is less than the balloon radius
// the value we get will be negative! giving us the 'Signed' in
// Signed Distance Field!
float distanceToBalloonSurface = distanceToBalloon - balloonRadius;
// Finally we build the full balloon information, by giving it an ID
float balloonID = 1.;
// And there we have it! A fully described balloon!
vec2 balloon = vec2( distanceToBalloonSurface, balloonID );
return balloon;
}
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
float opTwist_Torus( vec3 p , vec2 torusS)
{
float twistSpedd = 0.35;
float c = cos( 15.0 * (sin( twistSpedd * iTime)) *p.y );
float s = sin( 15.0 * (sin( twistSpedd * iTime)) *p.y );
mat2 m = mat2(c,-s,s,c);
vec3 q = vec3(m*p.xz,p.y);
return sdTorus(q, torusS);
}
vec2 sdfTorus( vec3 currentRayPos )
{
vec3 torusPos = vec3( 0.0, 0.0, 0.0);
vec2 torusSpec = vec2(0.6, 0.23);
vec3 adjustedRayPos = currentRayPos - torusPos;
float distToTorusSurface = opTwist_Torus(adjustedRayPos, torusSpec); //sdTorus(adjustedRayPos, torusSpec);
float torusID = 3.;
vec2 torus = vec2( distToTorusSurface, torusID);
return torus;
}
float smin( float a, float b)
{
float k = 0.77521;
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
float opBlend( float d1, float d2)
{
//float d1 = primitiveA(p);
//float d2 = primitiveB(p);
return smin( d1, d2 );
}
vec2 sdfBox( vec3 currentRayPosition ){
// First we define our box position
vec3 boxPosition = vec3( -.8 , -.4 , 0.2 );
// than we define our box dimensions using x , y and z
vec3 boxSize = vec3( .4 , .3 , .2 );
// Here we get the 'adjusted ray position' which is just
// writing the point of the ray as if the origin of the
// space was where the box was positioned, instead of
// at 0,0,0 . AKA the difference between the vectors in
// vector format.
vec3 adjustedRayPosition = currentRayPosition - boxPosition;
// finally we get the distance to the box surface.
// I don't get this part very much, but I bet Inigo does!
// Thanks for making code for us IQ !
vec3 distanceVec = abs( adjustedRayPosition ) - boxSize;
float maxDistance = max( distanceVec.x , max( distanceVec.y , distanceVec.z ) );
float distanceToBoxSurface = min( maxDistance , 0.0 ) + length( max( distanceVec , 0.0 ) );
// Finally we build the full box information, by giving it an ID
float boxID = 2.;
// And there we have it! A fully described box!
vec2 box = vec2( distanceToBoxSurface, boxID );
return box;
}
// 'TAG : WHICH AM I CLOSER TO?'
// This function takes in two things
// and says which is closer by using the
// distance to each thing, comparing them
// and returning the one that is closer!
vec2 whichThingAmICloserTo( vec2 thing1 , vec2 thing2 ){
vec2 closestThing;
// Check out the balloon function
// and remember how the x of the returned
// information is the distance, and the y
// is the id of the thing!
if( thing1.x <= thing2.x ){
closestThing = thing1;
}else if( thing2.x < thing1.x ){
closestThing = thing2;
}
return closestThing;
}
// Takes in the position of the ray, and feeds back
// 2 values of how close it is to things in the world
// what thing it is closest two in the world.
vec2 mapTheWorld( vec3 currentRayPosition ){
vec2 result;
vec2 balloon = sdfBalloon( currentRayPosition );
//vec2 box = sdfBox( currentRayPosition );
vec2 torus = sdfTorus( currentRayPosition );
result = whichThingAmICloserTo( balloon , torus); //box );
result.x = opBlend( balloon.x, torus.x);
return result;
}
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
// We want to know when the closeness to things in the world is
// 0.0 , but if we wanted to get exactly to 0 it would take us
// alot of time to be that precise. Here we define the laziness
// our navigation function. try chaning the value to see what it does!
// if you are getting too low of framerates, this value will help alot,
// but can also make your scene look very different
// from how it should
const float HOW_CLOSE_IS_CLOSE_ENOUGH = 0.0001;
// This is basically how big our scene is. each ray will be shot forward
// until it reaches this distance. the smaller it is, the quicker the
// ray will reach the edge, which should help speed up this function
const float FURTHEST_OUR_RAY_CAN_REACH = 10.75;
// This is how may steps our ray can take. Hopefully for this
// simple of a world, it will very quickly get to the 'close enough' value
// and stop the iteration, but for more complex scenes, this value
// will dramatically change not only how good the scene looks
// but how fast teh scene can render.
// remember that for each pixel we are displaying, the 'mapTheWorld' function
// could be called this many times! Thats ALOT of calculations!!!
const int HOW_MANY_STEPS_CAN_OUR_RAY_TAKE = 2000;
vec2 checkRayHit( in vec3 eyePosition , in vec3 rayDirection ){
//First we set some default values
// our distance to surface will get overwritten every step,
// so all that is important is that it is greater than our
// 'how close is close enough' value
float distanceToSurface = HOW_CLOSE_IS_CLOSE_ENOUGH * 2.;
// The total distance traveled by the ray obviously should start at 0
float totalDistanceTraveledByRay = 0.;
// if we hit something, this value will be overwritten by the
// totalDistance traveled, and if we don't hit something it will
// be overwritten by the furthest our ray can reach,
// so it can be whatever!
float finalDistanceTraveledByRay = -1.;
// if our id is less that 0. , it means we haven't hit anything
// so lets start by saying we haven't hit anything!
float finalID = -1.;
//here is the loop where the magic happens
for( int i = 0; i < HOW_MANY_STEPS_CAN_OUR_RAY_TAKE; i++ ){
// First off, stop the iteration, if we are close enough to the surface!
if( distanceToSurface < HOW_CLOSE_IS_CLOSE_ENOUGH ) break;
// Second off, stop the iteration, if we have reached the end of our scene!
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ) break;
// To check how close we are to things in the world,
// we need to get a position in the scene. to do this,
// we start at the rays origin, AKA the eye
// and move along the ray direction, the amount we have already traveled.
vec3 currentPositionOfRay = eyePosition + rayDirection * totalDistanceTraveledByRay;
// Distance to and ID of things in the world
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
vec2 distanceAndIDOfThingsInTheWorld = mapTheWorld( currentPositionOfRay );
// we get out the results from our mapping of the world
// I am reassigning them for clarity
float distanceToThingsInTheWorld = distanceAndIDOfThingsInTheWorld.x;
float idOfClosestThingInTheWorld = distanceAndIDOfThingsInTheWorld.y;
// We save out the distance to the surface, so that
// next iteration we can check to see if we are close enough
// to stop all this silly iteration
distanceToSurface = distanceToThingsInTheWorld;
// We are also finalID to the current closest id,
// because if we hit something, we will have the proper
// id, and we can skip reassigning it later!
finalID = idOfClosestThingInTheWorld;
// ATTENTION: THIS THING IS AWESOME!
// This last little calculation is probably the coolest hack
// of this entire tutorial. If we wanted too, we could basically
// step through the field at a constant amount, and at every step
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// that would take FOREVER, and get really annoying.
// Instead what we say is 'How far until we are there?'
// and move forward by that amount. This means that if
// we are really far away from everything, we can make large
// movements towards the surface, and if we are closer
// we can make more precise movements. making our marching functino
// faster, and ideally more precise!!
// WOW!
totalDistanceTraveledByRay += 0.05 * distanceToThingsInTheWorld; //0.001 + distanceToThingsInTheWorld * abs(sin(iTime)); //distanceToThingsInTheWorld;
}
// if we hit something set the finalDirastnce traveled by
// ray to that distance!
if( totalDistanceTraveledByRay < FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = totalDistanceTraveledByRay;
}
// If the total distance traveled by the ray is further than
// the ray can reach, that means that we've hit the edge of the scene
// Set the final distance to be the edge of the scene
// and the id to -1 to make sure we know we haven't hit anything
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = FURTHEST_OUR_RAY_CAN_REACH;
finalID = -1.;
}
return vec2( finalDistanceTraveledByRay , finalID );
}
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
// Here we are calcuting the normal of the surface
// Although it looks like alot of code, it actually
// is just trying to do something very simple, which
// is to figure out in what direction the SDF is increasing.
// What is amazing, is that this value is the same thing
// as telling you what direction the surface faces, AKA the
// normal of the surface.
vec3 getNormalOfSurface( in vec3 positionOfHit ){
vec3 tinyChangeX = vec3( 0.001, 0.0, 0.0 );
vec3 tinyChangeY = vec3( 0.0 , 0.001 , 0.0 );
vec3 tinyChangeZ = vec3( 0.0 , 0.0 , 0.001 );
float upTinyChangeInX = mapTheWorld( positionOfHit + tinyChangeX ).x;
float downTinyChangeInX = mapTheWorld( positionOfHit - tinyChangeX ).x;
float tinyChangeInX = upTinyChangeInX - downTinyChangeInX;
float upTinyChangeInY = mapTheWorld( positionOfHit + tinyChangeY ).x;
float downTinyChangeInY = mapTheWorld( positionOfHit - tinyChangeY ).x;
float tinyChangeInY = upTinyChangeInY - downTinyChangeInY;
float upTinyChangeInZ = mapTheWorld( positionOfHit + tinyChangeZ ).x;
float downTinyChangeInZ = mapTheWorld( positionOfHit - tinyChangeZ ).x;
float tinyChangeInZ = upTinyChangeInZ - downTinyChangeInZ;
vec3 normal = vec3(
tinyChangeInX,
tinyChangeInY,
tinyChangeInZ
);
return normalize(normal);
}
// doing our background color is easy enough,
// just make it pure black. like my soul.
vec3 doBackgroundColor(){
return vec3( 0.75 );
}
vec3 doBalloonColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 balloonColor = vec3( 1. , 0. , 0. );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = balloonColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
vec3 doTorusColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 torusColor = vec3( 0.25 , 0.95 , 0.25 );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = torusColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
// Here we are using the normal of the surface,
// and mapping it to color, to show you just how cool
// normals can be!
vec3 doBoxColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 color = vec3( normalOfSurface.x , normalOfSurface.y , normalOfSurface.z );
//could also just write color = normalOfSurce
//but trying to be explicit.
return color;
}
// This is where we decide
// what color the world will be!
// and what marvelous colors it will be!
vec3 colorTheWorld( vec2 rayHitInfo , vec3 eyePosition , vec3 rayDirection ){
// remember for color
// x = red , y = green , z = blue
vec3 color;
// THE LIL RAY WENT ALL THE WAY
// TO THE EDGE OF THE WORLD,
// AND DIDN'T HIT ANYTHING
if( rayHitInfo.y < 0.0 ){
color = doBackgroundColor();
// THE LIL RAY HIT SOMETHING!!!!
}else{
// If we hit something,
// we also know how far the ray has to travel to hit it
// and because we know the direction of the ray, we can
// get the exact position of where we hit the surface
// by following the ray from the eye, along its direction
// for the however far it had to travel to hit something
vec3 positionOfHit = eyePosition + rayHitInfo.x * rayDirection;
// We can then use this information to tell what direction
// the surface faces in
vec3 normalOfSurface = getNormalOfSurface( positionOfHit );
// 1.0 is the Balloon ID
if( rayHitInfo.y == 1.0 ){
color = doBalloonColor( positionOfHit , normalOfSurface );
// 2.0 is the Box ID
}else if( rayHitInfo.y == 2.0 ){
color = doBoxColor( positionOfHit , normalOfSurface );
}
else if( rayHitInfo.y == 3.0)
{
color = doTorusColor( positionOfHit , normalOfSurface );
}
}
return color;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
// Here we are getting our 'Position' of each pixel
// This section is important, because if we didn't
// divied by the resolution, our values would be masssive
// as fragCoord returns the value of how many pixels over we
// are. which is alot :)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// thats a super long name, so maybe we will
// keep on using uv, but im explicitly defining it
// so you can see exactly what those two letters mean
vec2 xyPositionOfPixelInWindow = p;
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// We use the eye position to tell use where the viewer is
float camRotSpeed = 0.5;
float rotRadius = 2.75;
float eyePosX = rotRadius * cos( camRotSpeed * iTime);
float eyePosZ = rotRadius * sin( camRotSpeed * iTime);
vec3 eyePosition = vec3( eyePosX, 0.5, eyePosZ); //vec3( 0., 0.5, 2.);
// This is the point the view is looking at.
// The window will be placed between the eye, and the
// position the eye is looking at!
vec3 pointWeAreLookingAt = vec3( 0. , 0. , 0. );
// This is where the magic of actual mathematics
// gives a way to actually place the window.
// the 0. at the end there gives the 'roll' of the transformation
// AKA we would be standing so up is up, but up could be changing
// like if we were one of those creepy dolls whos rotate their head
// all the way around along the z axis
mat3 eyeTransformationMatrix = calculateEyeRayTransformationMatrix( eyePosition , pointWeAreLookingAt , 0. );
// Here we get the actual ray that goes out of the eye
// and through the individual pixel! This basically the only thing
// that is different between the pixels, but is also the bread and butter
// of ray tracing. It should be since it has the word 'ray' in its variable name...
// the 2. at the end is the 'lens length' . I don't know how to best
// describe this, but once the full scene is built, tryin playing with it
// to understand inherently how it works
vec3 rayComingOutOfEyeDirection = normalize( eyeTransformationMatrix * vec3( p.xy , 2. ) );
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
vec2 rayHitInfo = checkRayHit( eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
vec3 color = colorTheWorld( rayHitInfo , eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
fragColor = vec4(color,1.0);
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
}
| cc0-1.0 | [
27214,
27576,
27625,
27625,
28622
] | [
[
15590,
15992,
16075,
16075,
16253
],
[
16457,
16474,
16517,
16517,
17738
],
[
17740,
17740,
17773,
17773,
17838
],
[
17840,
17840,
17884,
17884,
18130
],
[
18132,
18132,
18169,
18169,
18519
],
[
18521,
18521,
18552,
18552,
18668
],
[
18670,
18670,
18706,
18770,
18799
],
[
18802,
18802,
18841,
18882,
19967
],
[
19970,
20165,
20221,
20221,
20605
],
[
20613,
20765,
20809,
20809,
21118
],
[
22490,
22490,
22553,
22758,
27037
],
[
27214,
27576,
27625,
27625,
28622
],
[
28628,
28716,
28741,
28741,
28765
],
[
28770,
28770,
28834,
28834,
29925
],
[
29929,
29929,
29991,
29991,
31084
],
[
31087,
31208,
31268,
31268,
31467
],
[
31472,
31573,
31650,
31714,
33042
],
[
33046,
33046,
33103,
33547,
36672
]
] | // Here we are calcuting the normal of the surface
// Although it looks like alot of code, it actually
// is just trying to do something very simple, which
// is to figure out in what direction the SDF is increasing.
// What is amazing, is that this value is the same thing
// as telling you what direction the surface faces, AKA the
// normal of the surface.
| vec3 getNormalOfSurface( in vec3 positionOfHit ){ |
vec3 tinyChangeX = vec3( 0.001, 0.0, 0.0 );
vec3 tinyChangeY = vec3( 0.0 , 0.001 , 0.0 );
vec3 tinyChangeZ = vec3( 0.0 , 0.0 , 0.001 );
float upTinyChangeInX = mapTheWorld( positionOfHit + tinyChangeX ).x;
float downTinyChangeInX = mapTheWorld( positionOfHit - tinyChangeX ).x;
float tinyChangeInX = upTinyChangeInX - downTinyChangeInX;
float upTinyChangeInY = mapTheWorld( positionOfHit + tinyChangeY ).x;
float downTinyChangeInY = mapTheWorld( positionOfHit - tinyChangeY ).x;
float tinyChangeInY = upTinyChangeInY - downTinyChangeInY;
float upTinyChangeInZ = mapTheWorld( positionOfHit + tinyChangeZ ).x;
float downTinyChangeInZ = mapTheWorld( positionOfHit - tinyChangeZ ).x;
float tinyChangeInZ = upTinyChangeInZ - downTinyChangeInZ;
vec3 normal = vec3(
tinyChangeInX,
tinyChangeInY,
tinyChangeInZ
);
return normalize(normal);
} | // Here we are calcuting the normal of the surface
// Although it looks like alot of code, it actually
// is just trying to do something very simple, which
// is to figure out in what direction the SDF is increasing.
// What is amazing, is that this value is the same thing
// as telling you what direction the surface faces, AKA the
// normal of the surface.
vec3 getNormalOfSurface( in vec3 positionOfHit ){ | 3 | 3 |
4d33z4 | sagarpatel | 2015-11-23T08:44:22 | // @sagzorz
// My first shader on ShaderToy!
// The stuff below is pretty much all of the amazing @cabbibo's SDF tutorial
// https://www.shadertoy.com/view/Xl2XWt
// I read thorugh it then looked at IQ's page on distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// got inspired and remixed stuff in really messy code
// my only excuse was that I was in a rush since I did the tutorial and my hack all in a bus ride
// from Ha Long Bay to Hanoi and batteries were starting to run out :/
/*
CC0 1.0
@vrtree
who@tree.is
http://tree.is
I dont know if this is going to work, or be interesting,
or even understandable, But hey! Why not try!
To start, get inspired by some MAGICAL creations made by raytracing:
Volcanic by IQ
https://www.shadertoy.com/view/XsX3RB
Remnant X by Dave_Hoskins ( Audio Autoplay warnings )
https://www.shadertoy.com/view/4sjSW1
Cloud Ten by Nimitz
https://www.shadertoy.com/view/XtS3DD
Spectacles by MEEEEEE
https://www.shadertoy.com/view/4lBXWt
[2TC 15] Mystery Mountains by Dave_Hoskins
https://www.shadertoy.com/view/llsGW7
Raytracing graphics is kinda like baking cakes.
I want yall to first see how magical
the cake can be before trying to learn how to make it, because the thing we
make at first isn't going to be one of those crazy 10 story wedding cakes. its just
going to be some burnt sugar bread.
Making art using code can be so fufilling, and so infinite, but to get there you
need to learn some techniques that might not seem that inspiring. To bake a cake,
you first need to turn on an oven, and need to know what an oven even is. In this
tutorial we are going to be learning how to make the oven, how to turn it on,
and how to mix ingredients. as you can see on our left, our cake isn't very pretty
but it is a cake. and thats pretty crazy for just one tutorial!
Once you have gone through this tutorial, you can see a 'minimized' version
here: https://www.shadertoy.com/view/Xt2XDt
where I've rewritten it using the varibles and functions that
are used alot throughout shadertoy. The inspiration examples above
probably seem completely insane, because of all the single letter variable
names, but keep in mind, that they all start with most of the same ingredients
and overn that we will learn about right now!
I've tried to break up the code into 'sections'
which have the 'SECTION 'BLAH'' label above them. Not sure
if thats gonna help or not, but please leave comments
if you think something works or doesn't work, slash you
have any questions!!!
or contact me at @vrtree || @cabbibo
Cheat sheet for vectors:
x = left / right
y = up / down
z = forwards / backwards
also, for vectors labeled 'color'
x = red
y = green
z = blue
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
The best metaphor that I can think of for raytracing is
that the rectangle to our left is actually just a small window
into a fantastic world. We need to describe that world,
so that we can see it. BUT HOW ?!?!?!
What we are doing below is describing what color each pixel
of the window is, however because of the way that shader
programs work, we need to give the same instruction to every
single PIXEL ( or in shadertoy terms, FRAGMENT )
in the window. This is where the term SIMD comes
from : Same Instruction Multiple Data
In this case, the same instruction is the program below,
and the multiple data is the marvelous little piece of magic
called 'fragCoord' which is just the position of the pixel in
window. lets rename some things to look prettier.
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
If you think about what happens with an actual window, you
can begin to get an idea of how the magic of raytracing works
basically a bunch of rays come from the sun ( and or other
light sources ) , bounce around a bunch ( or a little ), and
eventually make it through the window, and into our eyes.
Now the number of rays are masssiveeee that come from the sun
and alot of them that are bouncing around, will end up going
directions that aren't even close to the window, or maybe
will hit the wall instead of the window.
We only care about the rays that go through the window
and make it to our eyeballs!
This means that we can be a bit intelligent. Instead of
figuring out the rays that come from the sun and bounce around
lets start with out eyes, and work backwards!!!!
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
After setting up all the neccesary ray information,
we FINALLY get to start building the scene. Up to this point,
we've only built up the window, and the rays that go from our
eyes through the window, but now we need to describe to the rays
if they hit anything and what they hit!
Now this part has some pretty scary code in it ( whenever I look
at it at least, my eyes glaze over ), so feel free to skip over
the checkRayHit function. I tried to explain it as best as I could
down below, and you might want to come back to it after going
throught the rest of the tutorial, but the important thing to
remember is the following:
These 'rays' that we've been talking about will move through the
scene along their direction. They do this iteratively, and at each
step will basically ask the question :
'HOW CLOSE AM I TO THINGS IN THE WORLD???'
because well, rays are lonely, and want to be closer to things in
the world. We provide them an answer to that question using our
description of the world, and they use this information to tell
them how much further along their path they should move. If the
answer to the question is:
'Lovely little ray, you are actually touching a thing in the world!'
We know what that the ray hit something, and can begin with our next
step!
The tricky part about this is that we have to as accuratly as
possible provide them an answer to their question 'how close??!!'
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
To answer the above concept, we are going to use this magical
concept called:
'Signed Distance Fields'
-----------------------
These things are the best, and very basically can be describe as
a function that takes in a position, and feeds back a value of
how close you are to a thing. If the value of this distance is negative
you are inside the thing, if it is positive, you are outside the thing
and if its 0 you are at the surface of the thing! This positive or negative
gives us the 'Signed' in 'Signed Distance Field'
For a super intensive description of many of the SDFs out there
check out Inigo Quilez's site:
http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
Also, if you want a deep dive into why these functions are the
ultimate magic, check out this crazy paper by the geniouses
over at Media Molecule about their new game: 'DREAMS'
http://media.lolrus.mediamolecule.com/AlexEvans_SIGGRAPH-2015.pdf
Needless to say, these lil puppies are super amazing, and are
here to free us from the tyranny of polygons.
---------
We are going to put all of our SDFs into a single function called
'mapTheWorld'
which will take in a position, and feed back two values.
The first value is the Distance of Signed Distance Field, and the
second value will tell us what we are closest too, so that if
we actually hit something, we can tell what it is. We will denote this
by an 'ID' value.
The hardest part for me to wrap my head around for this was the fact that
these fields do not just describe where the surface of an object is,
they actually describe how far you are from the object from ANYWHERE
in the world.
For example, if I was hitting a round ballon ( AKA a sphere :) )
I wouldn't just know if I was on the surface of the ballon, I would have
to know how close I was to the balloon from anywhere in space.
Check out the 'TAG : BALLOON' in the mapTheWorld function for more detail :)
I've also made a function for a box, that is slightly more complex, and to be
honest, I don't exactly understand the math of it, but the beauty of programming
is that someone else ( AKA Inigo ) does, and I can steal his knowledge, just by
looking at the functions from his website!
---------
One of the magical properties of SDFs is how easily they can be combined
contorted, and manipulated. They are just these lil functions that take
in a position and give back a distance value, so we can do things like play with the
input position, play with the output distance value, or just about anything
else.
We'll start by combining two SDFs by asking the simple question
'Which thing am I closer to?'
which is as simple as a '>' because we already know exactly how close we are
to each thing!
check out 'TAG : WHICH AM I CLOSER TO?' for more enough
We use these function to create a map of the world for the rays to navigate,
and than pass that map to the checkRayHit, which propates the rays throughout
the world and tells us what they hit.
Once they know that, we can FINALLY do our last step:
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD!
//--------------------------------------------------------------
At the end of our checkRayHit function we return a vec2 with two values:
.x is the distance that our ray traveled before hitting
.y is the ID of the thing that we hit.
if .y is less that 0.0 that means that our ray went as far as we allowed it
to go without hitting anything. thats one lonely ray :(
however, that doesn't mean that the ray didn't hit anything. It just meant
that it is part of the background.
Thanks little ray!
You told us important information about our scene,
and your hard work is helping to create the world!
We can get reallly crazy with how we color the background of the scene,
but for this tutorial lets just keep it black, because who doesn't love
the void.
we will use the function 'doBackgroundColor' to accomplish this task!
That tells us about the background, but what if .y is greater than 0.0?
then we get to make some stuff in the scene!
if the ID is equal to balloon id, then we 'doBalloonColor'
and if the ID is equal to the box , then we 'doBoxColor'
This is all that we need if we want to color simple solid objects,
but what if we want to add some shading, by doing what we originally
talked about, that is, following the ray to the sun?
For this first tutorial, we will keep it to a very naive approach,
but once you get the basics of sections A - D, we can get SUPER crazy
with this 'color' the world section.
For example, we could reflect the
ray off the surface, and than repeat the checkRayHit with this new information
continuing to follow this ray through more and more of the world. we could
repeat this process again and again, and even though our gpu would hate us
we could continue bouncing around until we got to a light source!
In a later tutorial we will do exactly this, but for now,
we are going to do 1 simple task:
See how much the surface that we hit, faces the sun.
to do that we need to do 2 things.
First, determine which way the surface faces
Second, determine which way rays go from the surface to get to the sun
1) To determine the way that the surface faces, we will use a function called
'getNormalOfSurface' This function will either make 100% sense, or 0% sense
depending on how often you have played with fields, but it made 0% sense to me
for many years, so don't worry if you don't get it! Whats important is that
it gives us the direction that the surface faces, which we call its 'Normal'
You can think of it as a vector that is perpendicular to the surface at a specific point
So that it is easier to understand what this value is, we are actually going to color our
box based on this value. We will map the X value of the normal to red, the Y value of the
normal to green and the Z value of the normal to blue. You can see this more in the
'doBoxColor' function
2) To get the direction the rays go to get to the sun, we just need to subtract the sun
position from the position of where we hit. This will provide us a direction from the sun
to the position. Look inside the doBalloonColor to see this calculation happen.
this will give us the direction of the rays from the sun to the surface!
Now that we have these 2 pieces of information, the last thing we need to do is see
how much the two vectors ( the normal and the light direction ) 'Face' each other.
that word 'Face', might not make much sense in this context, but think about it this way.
If you have a table, and a light above the table, the top of the table will 'Face',
the light, and the bottom of the table will 'Face' away from the light. The surface
that 'Faces' the light will get hit by the rays from the light, while the surface
that 'Faces' away from the light will be totally dark!
so how do we get this 'Face' value ( pun intended :p ) ?
There is a magical function called a 'dot product' which does exactly this. you
can read more here:
https://en.wikipedia.org/wiki/Dot_product
basically this function takes in 2 vectors, and feeds back a value from -1 -> 1.
if the value is -1 , the two vectors face in exact opposite directions, and if
the value is 1 , the two vectors face in exactly the same direction. if the value is
0, than they are perpendicular!
By using the dot product, we take get the ballon's 'Face' value and color it depending
on this value!
check out the doBallonColor to see all this craziness in action
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
What a journey it has been. Remember back when we were talking about
sending rays through the window? Remember them moving all through the
world trying to be closer to things?
So much has happened, and at the end of that journey, we got a color for each ray!
now all we need to do is output that color onto the screen , which is a single call,
and we've made our world.
I know this stuff might seem too dry or too complex at times, too confusing,
too frustrating, but I promise, if you stick with it, you'll soon be making some of the
other magical structures you see throughout the rest of this site.
I'll be trying to do some more of these tutorials, and you'll see that VERY
quickly, you get from this hideous monstrosity to our left, to marvelous worlds
filled with lights, colors, and love.
Thanks for staying around, and please contact me:
@vrtree , @cabbibo with questions, concerns , and improvments. Or just comment!
*/
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// Most of this is taken from many of the shaders
// that @iq have worked on. Make sure to check out
// more of his magic!!!
// This calculation basically gets a way for us to
// transform the rays coming out of our eyes and going through the window.
// If it doesn't make sense, thats ok. It doesn't make sense to me either :)
// Whats important to remember is that this basically gives us a way to position
// our window. We could you it to make the window look north, south, east, west, up, down
// or ANYWHERE in between!
mat3 calculateEyeRayTransformationMatrix( in vec3 ro, in vec3 ta, in float roll )
{
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(sin(roll),cos(roll),0.0) ) );
vec3 vv = normalize( cross(uu,ww));
return mat3( uu, vv, ww );
}
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
//'TAG: BALLOON'
vec2 sdfBalloon( vec3 currentRayPosition ){
float ballOrbitSpeed = 0.85;
float ballOrbitRadius = 1.0;
vec3 ballOrbitOffset = vec3(1.0,0,0);
float balloonPosX = ballOrbitRadius * cos( ballOrbitSpeed * iTime);
float balloonPosY = ballOrbitRadius * sin( ballOrbitSpeed * iTime);
// First we define our balloon position
vec3 balloonPosition = ballOrbitOffset + vec3(balloonPosX,balloonPosY,0); //vec3( -1.3 , .3 , -0.4 );
// than we define our balloon radius
float balloonRadius = 0.51;
// Here we get the distance to the surface of the balloon
float distanceToBalloon = length( currentRayPosition - balloonPosition );
// finally we get the distance to the balloon surface
// by substacting the balloon radius. This means that if
// the distance to the balloon is less than the balloon radius
// the value we get will be negative! giving us the 'Signed' in
// Signed Distance Field!
float distanceToBalloonSurface = distanceToBalloon - balloonRadius;
// Finally we build the full balloon information, by giving it an ID
float balloonID = 1.;
// And there we have it! A fully described balloon!
vec2 balloon = vec2( distanceToBalloonSurface, balloonID );
return balloon;
}
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
float opTwist_Torus( vec3 p , vec2 torusS)
{
float twistSpedd = 0.35;
float c = cos( 15.0 * (sin( twistSpedd * iTime)) *p.y );
float s = sin( 15.0 * (sin( twistSpedd * iTime)) *p.y );
mat2 m = mat2(c,-s,s,c);
vec3 q = vec3(m*p.xz,p.y);
return sdTorus(q, torusS);
}
vec2 sdfTorus( vec3 currentRayPos )
{
vec3 torusPos = vec3( 0.0, 0.0, 0.0);
vec2 torusSpec = vec2(0.6, 0.23);
vec3 adjustedRayPos = currentRayPos - torusPos;
float distToTorusSurface = opTwist_Torus(adjustedRayPos, torusSpec); //sdTorus(adjustedRayPos, torusSpec);
float torusID = 3.;
vec2 torus = vec2( distToTorusSurface, torusID);
return torus;
}
float smin( float a, float b)
{
float k = 0.77521;
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
float opBlend( float d1, float d2)
{
//float d1 = primitiveA(p);
//float d2 = primitiveB(p);
return smin( d1, d2 );
}
vec2 sdfBox( vec3 currentRayPosition ){
// First we define our box position
vec3 boxPosition = vec3( -.8 , -.4 , 0.2 );
// than we define our box dimensions using x , y and z
vec3 boxSize = vec3( .4 , .3 , .2 );
// Here we get the 'adjusted ray position' which is just
// writing the point of the ray as if the origin of the
// space was where the box was positioned, instead of
// at 0,0,0 . AKA the difference between the vectors in
// vector format.
vec3 adjustedRayPosition = currentRayPosition - boxPosition;
// finally we get the distance to the box surface.
// I don't get this part very much, but I bet Inigo does!
// Thanks for making code for us IQ !
vec3 distanceVec = abs( adjustedRayPosition ) - boxSize;
float maxDistance = max( distanceVec.x , max( distanceVec.y , distanceVec.z ) );
float distanceToBoxSurface = min( maxDistance , 0.0 ) + length( max( distanceVec , 0.0 ) );
// Finally we build the full box information, by giving it an ID
float boxID = 2.;
// And there we have it! A fully described box!
vec2 box = vec2( distanceToBoxSurface, boxID );
return box;
}
// 'TAG : WHICH AM I CLOSER TO?'
// This function takes in two things
// and says which is closer by using the
// distance to each thing, comparing them
// and returning the one that is closer!
vec2 whichThingAmICloserTo( vec2 thing1 , vec2 thing2 ){
vec2 closestThing;
// Check out the balloon function
// and remember how the x of the returned
// information is the distance, and the y
// is the id of the thing!
if( thing1.x <= thing2.x ){
closestThing = thing1;
}else if( thing2.x < thing1.x ){
closestThing = thing2;
}
return closestThing;
}
// Takes in the position of the ray, and feeds back
// 2 values of how close it is to things in the world
// what thing it is closest two in the world.
vec2 mapTheWorld( vec3 currentRayPosition ){
vec2 result;
vec2 balloon = sdfBalloon( currentRayPosition );
//vec2 box = sdfBox( currentRayPosition );
vec2 torus = sdfTorus( currentRayPosition );
result = whichThingAmICloserTo( balloon , torus); //box );
result.x = opBlend( balloon.x, torus.x);
return result;
}
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
// We want to know when the closeness to things in the world is
// 0.0 , but if we wanted to get exactly to 0 it would take us
// alot of time to be that precise. Here we define the laziness
// our navigation function. try chaning the value to see what it does!
// if you are getting too low of framerates, this value will help alot,
// but can also make your scene look very different
// from how it should
const float HOW_CLOSE_IS_CLOSE_ENOUGH = 0.0001;
// This is basically how big our scene is. each ray will be shot forward
// until it reaches this distance. the smaller it is, the quicker the
// ray will reach the edge, which should help speed up this function
const float FURTHEST_OUR_RAY_CAN_REACH = 10.75;
// This is how may steps our ray can take. Hopefully for this
// simple of a world, it will very quickly get to the 'close enough' value
// and stop the iteration, but for more complex scenes, this value
// will dramatically change not only how good the scene looks
// but how fast teh scene can render.
// remember that for each pixel we are displaying, the 'mapTheWorld' function
// could be called this many times! Thats ALOT of calculations!!!
const int HOW_MANY_STEPS_CAN_OUR_RAY_TAKE = 2000;
vec2 checkRayHit( in vec3 eyePosition , in vec3 rayDirection ){
//First we set some default values
// our distance to surface will get overwritten every step,
// so all that is important is that it is greater than our
// 'how close is close enough' value
float distanceToSurface = HOW_CLOSE_IS_CLOSE_ENOUGH * 2.;
// The total distance traveled by the ray obviously should start at 0
float totalDistanceTraveledByRay = 0.;
// if we hit something, this value will be overwritten by the
// totalDistance traveled, and if we don't hit something it will
// be overwritten by the furthest our ray can reach,
// so it can be whatever!
float finalDistanceTraveledByRay = -1.;
// if our id is less that 0. , it means we haven't hit anything
// so lets start by saying we haven't hit anything!
float finalID = -1.;
//here is the loop where the magic happens
for( int i = 0; i < HOW_MANY_STEPS_CAN_OUR_RAY_TAKE; i++ ){
// First off, stop the iteration, if we are close enough to the surface!
if( distanceToSurface < HOW_CLOSE_IS_CLOSE_ENOUGH ) break;
// Second off, stop the iteration, if we have reached the end of our scene!
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ) break;
// To check how close we are to things in the world,
// we need to get a position in the scene. to do this,
// we start at the rays origin, AKA the eye
// and move along the ray direction, the amount we have already traveled.
vec3 currentPositionOfRay = eyePosition + rayDirection * totalDistanceTraveledByRay;
// Distance to and ID of things in the world
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
vec2 distanceAndIDOfThingsInTheWorld = mapTheWorld( currentPositionOfRay );
// we get out the results from our mapping of the world
// I am reassigning them for clarity
float distanceToThingsInTheWorld = distanceAndIDOfThingsInTheWorld.x;
float idOfClosestThingInTheWorld = distanceAndIDOfThingsInTheWorld.y;
// We save out the distance to the surface, so that
// next iteration we can check to see if we are close enough
// to stop all this silly iteration
distanceToSurface = distanceToThingsInTheWorld;
// We are also finalID to the current closest id,
// because if we hit something, we will have the proper
// id, and we can skip reassigning it later!
finalID = idOfClosestThingInTheWorld;
// ATTENTION: THIS THING IS AWESOME!
// This last little calculation is probably the coolest hack
// of this entire tutorial. If we wanted too, we could basically
// step through the field at a constant amount, and at every step
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// that would take FOREVER, and get really annoying.
// Instead what we say is 'How far until we are there?'
// and move forward by that amount. This means that if
// we are really far away from everything, we can make large
// movements towards the surface, and if we are closer
// we can make more precise movements. making our marching functino
// faster, and ideally more precise!!
// WOW!
totalDistanceTraveledByRay += 0.05 * distanceToThingsInTheWorld; //0.001 + distanceToThingsInTheWorld * abs(sin(iTime)); //distanceToThingsInTheWorld;
}
// if we hit something set the finalDirastnce traveled by
// ray to that distance!
if( totalDistanceTraveledByRay < FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = totalDistanceTraveledByRay;
}
// If the total distance traveled by the ray is further than
// the ray can reach, that means that we've hit the edge of the scene
// Set the final distance to be the edge of the scene
// and the id to -1 to make sure we know we haven't hit anything
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = FURTHEST_OUR_RAY_CAN_REACH;
finalID = -1.;
}
return vec2( finalDistanceTraveledByRay , finalID );
}
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
// Here we are calcuting the normal of the surface
// Although it looks like alot of code, it actually
// is just trying to do something very simple, which
// is to figure out in what direction the SDF is increasing.
// What is amazing, is that this value is the same thing
// as telling you what direction the surface faces, AKA the
// normal of the surface.
vec3 getNormalOfSurface( in vec3 positionOfHit ){
vec3 tinyChangeX = vec3( 0.001, 0.0, 0.0 );
vec3 tinyChangeY = vec3( 0.0 , 0.001 , 0.0 );
vec3 tinyChangeZ = vec3( 0.0 , 0.0 , 0.001 );
float upTinyChangeInX = mapTheWorld( positionOfHit + tinyChangeX ).x;
float downTinyChangeInX = mapTheWorld( positionOfHit - tinyChangeX ).x;
float tinyChangeInX = upTinyChangeInX - downTinyChangeInX;
float upTinyChangeInY = mapTheWorld( positionOfHit + tinyChangeY ).x;
float downTinyChangeInY = mapTheWorld( positionOfHit - tinyChangeY ).x;
float tinyChangeInY = upTinyChangeInY - downTinyChangeInY;
float upTinyChangeInZ = mapTheWorld( positionOfHit + tinyChangeZ ).x;
float downTinyChangeInZ = mapTheWorld( positionOfHit - tinyChangeZ ).x;
float tinyChangeInZ = upTinyChangeInZ - downTinyChangeInZ;
vec3 normal = vec3(
tinyChangeInX,
tinyChangeInY,
tinyChangeInZ
);
return normalize(normal);
}
// doing our background color is easy enough,
// just make it pure black. like my soul.
vec3 doBackgroundColor(){
return vec3( 0.75 );
}
vec3 doBalloonColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 balloonColor = vec3( 1. , 0. , 0. );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = balloonColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
vec3 doTorusColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 torusColor = vec3( 0.25 , 0.95 , 0.25 );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = torusColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
// Here we are using the normal of the surface,
// and mapping it to color, to show you just how cool
// normals can be!
vec3 doBoxColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 color = vec3( normalOfSurface.x , normalOfSurface.y , normalOfSurface.z );
//could also just write color = normalOfSurce
//but trying to be explicit.
return color;
}
// This is where we decide
// what color the world will be!
// and what marvelous colors it will be!
vec3 colorTheWorld( vec2 rayHitInfo , vec3 eyePosition , vec3 rayDirection ){
// remember for color
// x = red , y = green , z = blue
vec3 color;
// THE LIL RAY WENT ALL THE WAY
// TO THE EDGE OF THE WORLD,
// AND DIDN'T HIT ANYTHING
if( rayHitInfo.y < 0.0 ){
color = doBackgroundColor();
// THE LIL RAY HIT SOMETHING!!!!
}else{
// If we hit something,
// we also know how far the ray has to travel to hit it
// and because we know the direction of the ray, we can
// get the exact position of where we hit the surface
// by following the ray from the eye, along its direction
// for the however far it had to travel to hit something
vec3 positionOfHit = eyePosition + rayHitInfo.x * rayDirection;
// We can then use this information to tell what direction
// the surface faces in
vec3 normalOfSurface = getNormalOfSurface( positionOfHit );
// 1.0 is the Balloon ID
if( rayHitInfo.y == 1.0 ){
color = doBalloonColor( positionOfHit , normalOfSurface );
// 2.0 is the Box ID
}else if( rayHitInfo.y == 2.0 ){
color = doBoxColor( positionOfHit , normalOfSurface );
}
else if( rayHitInfo.y == 3.0)
{
color = doTorusColor( positionOfHit , normalOfSurface );
}
}
return color;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
// Here we are getting our 'Position' of each pixel
// This section is important, because if we didn't
// divied by the resolution, our values would be masssive
// as fragCoord returns the value of how many pixels over we
// are. which is alot :)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// thats a super long name, so maybe we will
// keep on using uv, but im explicitly defining it
// so you can see exactly what those two letters mean
vec2 xyPositionOfPixelInWindow = p;
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// We use the eye position to tell use where the viewer is
float camRotSpeed = 0.5;
float rotRadius = 2.75;
float eyePosX = rotRadius * cos( camRotSpeed * iTime);
float eyePosZ = rotRadius * sin( camRotSpeed * iTime);
vec3 eyePosition = vec3( eyePosX, 0.5, eyePosZ); //vec3( 0., 0.5, 2.);
// This is the point the view is looking at.
// The window will be placed between the eye, and the
// position the eye is looking at!
vec3 pointWeAreLookingAt = vec3( 0. , 0. , 0. );
// This is where the magic of actual mathematics
// gives a way to actually place the window.
// the 0. at the end there gives the 'roll' of the transformation
// AKA we would be standing so up is up, but up could be changing
// like if we were one of those creepy dolls whos rotate their head
// all the way around along the z axis
mat3 eyeTransformationMatrix = calculateEyeRayTransformationMatrix( eyePosition , pointWeAreLookingAt , 0. );
// Here we get the actual ray that goes out of the eye
// and through the individual pixel! This basically the only thing
// that is different between the pixels, but is also the bread and butter
// of ray tracing. It should be since it has the word 'ray' in its variable name...
// the 2. at the end is the 'lens length' . I don't know how to best
// describe this, but once the full scene is built, tryin playing with it
// to understand inherently how it works
vec3 rayComingOutOfEyeDirection = normalize( eyeTransformationMatrix * vec3( p.xy , 2. ) );
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
vec2 rayHitInfo = checkRayHit( eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
vec3 color = colorTheWorld( rayHitInfo , eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
fragColor = vec4(color,1.0);
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
}
| cc0-1.0 | [
28628,
28716,
28741,
28741,
28765
] | [
[
15590,
15992,
16075,
16075,
16253
],
[
16457,
16474,
16517,
16517,
17738
],
[
17740,
17740,
17773,
17773,
17838
],
[
17840,
17840,
17884,
17884,
18130
],
[
18132,
18132,
18169,
18169,
18519
],
[
18521,
18521,
18552,
18552,
18668
],
[
18670,
18670,
18706,
18770,
18799
],
[
18802,
18802,
18841,
18882,
19967
],
[
19970,
20165,
20221,
20221,
20605
],
[
20613,
20765,
20809,
20809,
21118
],
[
22490,
22490,
22553,
22758,
27037
],
[
27214,
27576,
27625,
27625,
28622
],
[
28628,
28716,
28741,
28741,
28765
],
[
28770,
28770,
28834,
28834,
29925
],
[
29929,
29929,
29991,
29991,
31084
],
[
31087,
31208,
31268,
31268,
31467
],
[
31472,
31573,
31650,
31714,
33042
],
[
33046,
33046,
33103,
33547,
36672
]
] | // doing our background color is easy enough,
// just make it pure black. like my soul.
| vec3 doBackgroundColor(){ |
return vec3( 0.75 );
} | // doing our background color is easy enough,
// just make it pure black. like my soul.
vec3 doBackgroundColor(){ | 1 | 3 |
4d33z4 | sagarpatel | 2015-11-23T08:44:22 | // @sagzorz
// My first shader on ShaderToy!
// The stuff below is pretty much all of the amazing @cabbibo's SDF tutorial
// https://www.shadertoy.com/view/Xl2XWt
// I read thorugh it then looked at IQ's page on distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// got inspired and remixed stuff in really messy code
// my only excuse was that I was in a rush since I did the tutorial and my hack all in a bus ride
// from Ha Long Bay to Hanoi and batteries were starting to run out :/
/*
CC0 1.0
@vrtree
who@tree.is
http://tree.is
I dont know if this is going to work, or be interesting,
or even understandable, But hey! Why not try!
To start, get inspired by some MAGICAL creations made by raytracing:
Volcanic by IQ
https://www.shadertoy.com/view/XsX3RB
Remnant X by Dave_Hoskins ( Audio Autoplay warnings )
https://www.shadertoy.com/view/4sjSW1
Cloud Ten by Nimitz
https://www.shadertoy.com/view/XtS3DD
Spectacles by MEEEEEE
https://www.shadertoy.com/view/4lBXWt
[2TC 15] Mystery Mountains by Dave_Hoskins
https://www.shadertoy.com/view/llsGW7
Raytracing graphics is kinda like baking cakes.
I want yall to first see how magical
the cake can be before trying to learn how to make it, because the thing we
make at first isn't going to be one of those crazy 10 story wedding cakes. its just
going to be some burnt sugar bread.
Making art using code can be so fufilling, and so infinite, but to get there you
need to learn some techniques that might not seem that inspiring. To bake a cake,
you first need to turn on an oven, and need to know what an oven even is. In this
tutorial we are going to be learning how to make the oven, how to turn it on,
and how to mix ingredients. as you can see on our left, our cake isn't very pretty
but it is a cake. and thats pretty crazy for just one tutorial!
Once you have gone through this tutorial, you can see a 'minimized' version
here: https://www.shadertoy.com/view/Xt2XDt
where I've rewritten it using the varibles and functions that
are used alot throughout shadertoy. The inspiration examples above
probably seem completely insane, because of all the single letter variable
names, but keep in mind, that they all start with most of the same ingredients
and overn that we will learn about right now!
I've tried to break up the code into 'sections'
which have the 'SECTION 'BLAH'' label above them. Not sure
if thats gonna help or not, but please leave comments
if you think something works or doesn't work, slash you
have any questions!!!
or contact me at @vrtree || @cabbibo
Cheat sheet for vectors:
x = left / right
y = up / down
z = forwards / backwards
also, for vectors labeled 'color'
x = red
y = green
z = blue
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
The best metaphor that I can think of for raytracing is
that the rectangle to our left is actually just a small window
into a fantastic world. We need to describe that world,
so that we can see it. BUT HOW ?!?!?!
What we are doing below is describing what color each pixel
of the window is, however because of the way that shader
programs work, we need to give the same instruction to every
single PIXEL ( or in shadertoy terms, FRAGMENT )
in the window. This is where the term SIMD comes
from : Same Instruction Multiple Data
In this case, the same instruction is the program below,
and the multiple data is the marvelous little piece of magic
called 'fragCoord' which is just the position of the pixel in
window. lets rename some things to look prettier.
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
If you think about what happens with an actual window, you
can begin to get an idea of how the magic of raytracing works
basically a bunch of rays come from the sun ( and or other
light sources ) , bounce around a bunch ( or a little ), and
eventually make it through the window, and into our eyes.
Now the number of rays are masssiveeee that come from the sun
and alot of them that are bouncing around, will end up going
directions that aren't even close to the window, or maybe
will hit the wall instead of the window.
We only care about the rays that go through the window
and make it to our eyeballs!
This means that we can be a bit intelligent. Instead of
figuring out the rays that come from the sun and bounce around
lets start with out eyes, and work backwards!!!!
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
After setting up all the neccesary ray information,
we FINALLY get to start building the scene. Up to this point,
we've only built up the window, and the rays that go from our
eyes through the window, but now we need to describe to the rays
if they hit anything and what they hit!
Now this part has some pretty scary code in it ( whenever I look
at it at least, my eyes glaze over ), so feel free to skip over
the checkRayHit function. I tried to explain it as best as I could
down below, and you might want to come back to it after going
throught the rest of the tutorial, but the important thing to
remember is the following:
These 'rays' that we've been talking about will move through the
scene along their direction. They do this iteratively, and at each
step will basically ask the question :
'HOW CLOSE AM I TO THINGS IN THE WORLD???'
because well, rays are lonely, and want to be closer to things in
the world. We provide them an answer to that question using our
description of the world, and they use this information to tell
them how much further along their path they should move. If the
answer to the question is:
'Lovely little ray, you are actually touching a thing in the world!'
We know what that the ray hit something, and can begin with our next
step!
The tricky part about this is that we have to as accuratly as
possible provide them an answer to their question 'how close??!!'
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
To answer the above concept, we are going to use this magical
concept called:
'Signed Distance Fields'
-----------------------
These things are the best, and very basically can be describe as
a function that takes in a position, and feeds back a value of
how close you are to a thing. If the value of this distance is negative
you are inside the thing, if it is positive, you are outside the thing
and if its 0 you are at the surface of the thing! This positive or negative
gives us the 'Signed' in 'Signed Distance Field'
For a super intensive description of many of the SDFs out there
check out Inigo Quilez's site:
http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
Also, if you want a deep dive into why these functions are the
ultimate magic, check out this crazy paper by the geniouses
over at Media Molecule about their new game: 'DREAMS'
http://media.lolrus.mediamolecule.com/AlexEvans_SIGGRAPH-2015.pdf
Needless to say, these lil puppies are super amazing, and are
here to free us from the tyranny of polygons.
---------
We are going to put all of our SDFs into a single function called
'mapTheWorld'
which will take in a position, and feed back two values.
The first value is the Distance of Signed Distance Field, and the
second value will tell us what we are closest too, so that if
we actually hit something, we can tell what it is. We will denote this
by an 'ID' value.
The hardest part for me to wrap my head around for this was the fact that
these fields do not just describe where the surface of an object is,
they actually describe how far you are from the object from ANYWHERE
in the world.
For example, if I was hitting a round ballon ( AKA a sphere :) )
I wouldn't just know if I was on the surface of the ballon, I would have
to know how close I was to the balloon from anywhere in space.
Check out the 'TAG : BALLOON' in the mapTheWorld function for more detail :)
I've also made a function for a box, that is slightly more complex, and to be
honest, I don't exactly understand the math of it, but the beauty of programming
is that someone else ( AKA Inigo ) does, and I can steal his knowledge, just by
looking at the functions from his website!
---------
One of the magical properties of SDFs is how easily they can be combined
contorted, and manipulated. They are just these lil functions that take
in a position and give back a distance value, so we can do things like play with the
input position, play with the output distance value, or just about anything
else.
We'll start by combining two SDFs by asking the simple question
'Which thing am I closer to?'
which is as simple as a '>' because we already know exactly how close we are
to each thing!
check out 'TAG : WHICH AM I CLOSER TO?' for more enough
We use these function to create a map of the world for the rays to navigate,
and than pass that map to the checkRayHit, which propates the rays throughout
the world and tells us what they hit.
Once they know that, we can FINALLY do our last step:
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD!
//--------------------------------------------------------------
At the end of our checkRayHit function we return a vec2 with two values:
.x is the distance that our ray traveled before hitting
.y is the ID of the thing that we hit.
if .y is less that 0.0 that means that our ray went as far as we allowed it
to go without hitting anything. thats one lonely ray :(
however, that doesn't mean that the ray didn't hit anything. It just meant
that it is part of the background.
Thanks little ray!
You told us important information about our scene,
and your hard work is helping to create the world!
We can get reallly crazy with how we color the background of the scene,
but for this tutorial lets just keep it black, because who doesn't love
the void.
we will use the function 'doBackgroundColor' to accomplish this task!
That tells us about the background, but what if .y is greater than 0.0?
then we get to make some stuff in the scene!
if the ID is equal to balloon id, then we 'doBalloonColor'
and if the ID is equal to the box , then we 'doBoxColor'
This is all that we need if we want to color simple solid objects,
but what if we want to add some shading, by doing what we originally
talked about, that is, following the ray to the sun?
For this first tutorial, we will keep it to a very naive approach,
but once you get the basics of sections A - D, we can get SUPER crazy
with this 'color' the world section.
For example, we could reflect the
ray off the surface, and than repeat the checkRayHit with this new information
continuing to follow this ray through more and more of the world. we could
repeat this process again and again, and even though our gpu would hate us
we could continue bouncing around until we got to a light source!
In a later tutorial we will do exactly this, but for now,
we are going to do 1 simple task:
See how much the surface that we hit, faces the sun.
to do that we need to do 2 things.
First, determine which way the surface faces
Second, determine which way rays go from the surface to get to the sun
1) To determine the way that the surface faces, we will use a function called
'getNormalOfSurface' This function will either make 100% sense, or 0% sense
depending on how often you have played with fields, but it made 0% sense to me
for many years, so don't worry if you don't get it! Whats important is that
it gives us the direction that the surface faces, which we call its 'Normal'
You can think of it as a vector that is perpendicular to the surface at a specific point
So that it is easier to understand what this value is, we are actually going to color our
box based on this value. We will map the X value of the normal to red, the Y value of the
normal to green and the Z value of the normal to blue. You can see this more in the
'doBoxColor' function
2) To get the direction the rays go to get to the sun, we just need to subtract the sun
position from the position of where we hit. This will provide us a direction from the sun
to the position. Look inside the doBalloonColor to see this calculation happen.
this will give us the direction of the rays from the sun to the surface!
Now that we have these 2 pieces of information, the last thing we need to do is see
how much the two vectors ( the normal and the light direction ) 'Face' each other.
that word 'Face', might not make much sense in this context, but think about it this way.
If you have a table, and a light above the table, the top of the table will 'Face',
the light, and the bottom of the table will 'Face' away from the light. The surface
that 'Faces' the light will get hit by the rays from the light, while the surface
that 'Faces' away from the light will be totally dark!
so how do we get this 'Face' value ( pun intended :p ) ?
There is a magical function called a 'dot product' which does exactly this. you
can read more here:
https://en.wikipedia.org/wiki/Dot_product
basically this function takes in 2 vectors, and feeds back a value from -1 -> 1.
if the value is -1 , the two vectors face in exact opposite directions, and if
the value is 1 , the two vectors face in exactly the same direction. if the value is
0, than they are perpendicular!
By using the dot product, we take get the ballon's 'Face' value and color it depending
on this value!
check out the doBallonColor to see all this craziness in action
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
What a journey it has been. Remember back when we were talking about
sending rays through the window? Remember them moving all through the
world trying to be closer to things?
So much has happened, and at the end of that journey, we got a color for each ray!
now all we need to do is output that color onto the screen , which is a single call,
and we've made our world.
I know this stuff might seem too dry or too complex at times, too confusing,
too frustrating, but I promise, if you stick with it, you'll soon be making some of the
other magical structures you see throughout the rest of this site.
I'll be trying to do some more of these tutorials, and you'll see that VERY
quickly, you get from this hideous monstrosity to our left, to marvelous worlds
filled with lights, colors, and love.
Thanks for staying around, and please contact me:
@vrtree , @cabbibo with questions, concerns , and improvments. Or just comment!
*/
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// Most of this is taken from many of the shaders
// that @iq have worked on. Make sure to check out
// more of his magic!!!
// This calculation basically gets a way for us to
// transform the rays coming out of our eyes and going through the window.
// If it doesn't make sense, thats ok. It doesn't make sense to me either :)
// Whats important to remember is that this basically gives us a way to position
// our window. We could you it to make the window look north, south, east, west, up, down
// or ANYWHERE in between!
mat3 calculateEyeRayTransformationMatrix( in vec3 ro, in vec3 ta, in float roll )
{
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(sin(roll),cos(roll),0.0) ) );
vec3 vv = normalize( cross(uu,ww));
return mat3( uu, vv, ww );
}
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
//'TAG: BALLOON'
vec2 sdfBalloon( vec3 currentRayPosition ){
float ballOrbitSpeed = 0.85;
float ballOrbitRadius = 1.0;
vec3 ballOrbitOffset = vec3(1.0,0,0);
float balloonPosX = ballOrbitRadius * cos( ballOrbitSpeed * iTime);
float balloonPosY = ballOrbitRadius * sin( ballOrbitSpeed * iTime);
// First we define our balloon position
vec3 balloonPosition = ballOrbitOffset + vec3(balloonPosX,balloonPosY,0); //vec3( -1.3 , .3 , -0.4 );
// than we define our balloon radius
float balloonRadius = 0.51;
// Here we get the distance to the surface of the balloon
float distanceToBalloon = length( currentRayPosition - balloonPosition );
// finally we get the distance to the balloon surface
// by substacting the balloon radius. This means that if
// the distance to the balloon is less than the balloon radius
// the value we get will be negative! giving us the 'Signed' in
// Signed Distance Field!
float distanceToBalloonSurface = distanceToBalloon - balloonRadius;
// Finally we build the full balloon information, by giving it an ID
float balloonID = 1.;
// And there we have it! A fully described balloon!
vec2 balloon = vec2( distanceToBalloonSurface, balloonID );
return balloon;
}
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
float opTwist_Torus( vec3 p , vec2 torusS)
{
float twistSpedd = 0.35;
float c = cos( 15.0 * (sin( twistSpedd * iTime)) *p.y );
float s = sin( 15.0 * (sin( twistSpedd * iTime)) *p.y );
mat2 m = mat2(c,-s,s,c);
vec3 q = vec3(m*p.xz,p.y);
return sdTorus(q, torusS);
}
vec2 sdfTorus( vec3 currentRayPos )
{
vec3 torusPos = vec3( 0.0, 0.0, 0.0);
vec2 torusSpec = vec2(0.6, 0.23);
vec3 adjustedRayPos = currentRayPos - torusPos;
float distToTorusSurface = opTwist_Torus(adjustedRayPos, torusSpec); //sdTorus(adjustedRayPos, torusSpec);
float torusID = 3.;
vec2 torus = vec2( distToTorusSurface, torusID);
return torus;
}
float smin( float a, float b)
{
float k = 0.77521;
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
float opBlend( float d1, float d2)
{
//float d1 = primitiveA(p);
//float d2 = primitiveB(p);
return smin( d1, d2 );
}
vec2 sdfBox( vec3 currentRayPosition ){
// First we define our box position
vec3 boxPosition = vec3( -.8 , -.4 , 0.2 );
// than we define our box dimensions using x , y and z
vec3 boxSize = vec3( .4 , .3 , .2 );
// Here we get the 'adjusted ray position' which is just
// writing the point of the ray as if the origin of the
// space was where the box was positioned, instead of
// at 0,0,0 . AKA the difference between the vectors in
// vector format.
vec3 adjustedRayPosition = currentRayPosition - boxPosition;
// finally we get the distance to the box surface.
// I don't get this part very much, but I bet Inigo does!
// Thanks for making code for us IQ !
vec3 distanceVec = abs( adjustedRayPosition ) - boxSize;
float maxDistance = max( distanceVec.x , max( distanceVec.y , distanceVec.z ) );
float distanceToBoxSurface = min( maxDistance , 0.0 ) + length( max( distanceVec , 0.0 ) );
// Finally we build the full box information, by giving it an ID
float boxID = 2.;
// And there we have it! A fully described box!
vec2 box = vec2( distanceToBoxSurface, boxID );
return box;
}
// 'TAG : WHICH AM I CLOSER TO?'
// This function takes in two things
// and says which is closer by using the
// distance to each thing, comparing them
// and returning the one that is closer!
vec2 whichThingAmICloserTo( vec2 thing1 , vec2 thing2 ){
vec2 closestThing;
// Check out the balloon function
// and remember how the x of the returned
// information is the distance, and the y
// is the id of the thing!
if( thing1.x <= thing2.x ){
closestThing = thing1;
}else if( thing2.x < thing1.x ){
closestThing = thing2;
}
return closestThing;
}
// Takes in the position of the ray, and feeds back
// 2 values of how close it is to things in the world
// what thing it is closest two in the world.
vec2 mapTheWorld( vec3 currentRayPosition ){
vec2 result;
vec2 balloon = sdfBalloon( currentRayPosition );
//vec2 box = sdfBox( currentRayPosition );
vec2 torus = sdfTorus( currentRayPosition );
result = whichThingAmICloserTo( balloon , torus); //box );
result.x = opBlend( balloon.x, torus.x);
return result;
}
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
// We want to know when the closeness to things in the world is
// 0.0 , but if we wanted to get exactly to 0 it would take us
// alot of time to be that precise. Here we define the laziness
// our navigation function. try chaning the value to see what it does!
// if you are getting too low of framerates, this value will help alot,
// but can also make your scene look very different
// from how it should
const float HOW_CLOSE_IS_CLOSE_ENOUGH = 0.0001;
// This is basically how big our scene is. each ray will be shot forward
// until it reaches this distance. the smaller it is, the quicker the
// ray will reach the edge, which should help speed up this function
const float FURTHEST_OUR_RAY_CAN_REACH = 10.75;
// This is how may steps our ray can take. Hopefully for this
// simple of a world, it will very quickly get to the 'close enough' value
// and stop the iteration, but for more complex scenes, this value
// will dramatically change not only how good the scene looks
// but how fast teh scene can render.
// remember that for each pixel we are displaying, the 'mapTheWorld' function
// could be called this many times! Thats ALOT of calculations!!!
const int HOW_MANY_STEPS_CAN_OUR_RAY_TAKE = 2000;
vec2 checkRayHit( in vec3 eyePosition , in vec3 rayDirection ){
//First we set some default values
// our distance to surface will get overwritten every step,
// so all that is important is that it is greater than our
// 'how close is close enough' value
float distanceToSurface = HOW_CLOSE_IS_CLOSE_ENOUGH * 2.;
// The total distance traveled by the ray obviously should start at 0
float totalDistanceTraveledByRay = 0.;
// if we hit something, this value will be overwritten by the
// totalDistance traveled, and if we don't hit something it will
// be overwritten by the furthest our ray can reach,
// so it can be whatever!
float finalDistanceTraveledByRay = -1.;
// if our id is less that 0. , it means we haven't hit anything
// so lets start by saying we haven't hit anything!
float finalID = -1.;
//here is the loop where the magic happens
for( int i = 0; i < HOW_MANY_STEPS_CAN_OUR_RAY_TAKE; i++ ){
// First off, stop the iteration, if we are close enough to the surface!
if( distanceToSurface < HOW_CLOSE_IS_CLOSE_ENOUGH ) break;
// Second off, stop the iteration, if we have reached the end of our scene!
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ) break;
// To check how close we are to things in the world,
// we need to get a position in the scene. to do this,
// we start at the rays origin, AKA the eye
// and move along the ray direction, the amount we have already traveled.
vec3 currentPositionOfRay = eyePosition + rayDirection * totalDistanceTraveledByRay;
// Distance to and ID of things in the world
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
vec2 distanceAndIDOfThingsInTheWorld = mapTheWorld( currentPositionOfRay );
// we get out the results from our mapping of the world
// I am reassigning them for clarity
float distanceToThingsInTheWorld = distanceAndIDOfThingsInTheWorld.x;
float idOfClosestThingInTheWorld = distanceAndIDOfThingsInTheWorld.y;
// We save out the distance to the surface, so that
// next iteration we can check to see if we are close enough
// to stop all this silly iteration
distanceToSurface = distanceToThingsInTheWorld;
// We are also finalID to the current closest id,
// because if we hit something, we will have the proper
// id, and we can skip reassigning it later!
finalID = idOfClosestThingInTheWorld;
// ATTENTION: THIS THING IS AWESOME!
// This last little calculation is probably the coolest hack
// of this entire tutorial. If we wanted too, we could basically
// step through the field at a constant amount, and at every step
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// that would take FOREVER, and get really annoying.
// Instead what we say is 'How far until we are there?'
// and move forward by that amount. This means that if
// we are really far away from everything, we can make large
// movements towards the surface, and if we are closer
// we can make more precise movements. making our marching functino
// faster, and ideally more precise!!
// WOW!
totalDistanceTraveledByRay += 0.05 * distanceToThingsInTheWorld; //0.001 + distanceToThingsInTheWorld * abs(sin(iTime)); //distanceToThingsInTheWorld;
}
// if we hit something set the finalDirastnce traveled by
// ray to that distance!
if( totalDistanceTraveledByRay < FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = totalDistanceTraveledByRay;
}
// If the total distance traveled by the ray is further than
// the ray can reach, that means that we've hit the edge of the scene
// Set the final distance to be the edge of the scene
// and the id to -1 to make sure we know we haven't hit anything
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = FURTHEST_OUR_RAY_CAN_REACH;
finalID = -1.;
}
return vec2( finalDistanceTraveledByRay , finalID );
}
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
// Here we are calcuting the normal of the surface
// Although it looks like alot of code, it actually
// is just trying to do something very simple, which
// is to figure out in what direction the SDF is increasing.
// What is amazing, is that this value is the same thing
// as telling you what direction the surface faces, AKA the
// normal of the surface.
vec3 getNormalOfSurface( in vec3 positionOfHit ){
vec3 tinyChangeX = vec3( 0.001, 0.0, 0.0 );
vec3 tinyChangeY = vec3( 0.0 , 0.001 , 0.0 );
vec3 tinyChangeZ = vec3( 0.0 , 0.0 , 0.001 );
float upTinyChangeInX = mapTheWorld( positionOfHit + tinyChangeX ).x;
float downTinyChangeInX = mapTheWorld( positionOfHit - tinyChangeX ).x;
float tinyChangeInX = upTinyChangeInX - downTinyChangeInX;
float upTinyChangeInY = mapTheWorld( positionOfHit + tinyChangeY ).x;
float downTinyChangeInY = mapTheWorld( positionOfHit - tinyChangeY ).x;
float tinyChangeInY = upTinyChangeInY - downTinyChangeInY;
float upTinyChangeInZ = mapTheWorld( positionOfHit + tinyChangeZ ).x;
float downTinyChangeInZ = mapTheWorld( positionOfHit - tinyChangeZ ).x;
float tinyChangeInZ = upTinyChangeInZ - downTinyChangeInZ;
vec3 normal = vec3(
tinyChangeInX,
tinyChangeInY,
tinyChangeInZ
);
return normalize(normal);
}
// doing our background color is easy enough,
// just make it pure black. like my soul.
vec3 doBackgroundColor(){
return vec3( 0.75 );
}
vec3 doBalloonColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 balloonColor = vec3( 1. , 0. , 0. );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = balloonColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
vec3 doTorusColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 torusColor = vec3( 0.25 , 0.95 , 0.25 );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = torusColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
// Here we are using the normal of the surface,
// and mapping it to color, to show you just how cool
// normals can be!
vec3 doBoxColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 color = vec3( normalOfSurface.x , normalOfSurface.y , normalOfSurface.z );
//could also just write color = normalOfSurce
//but trying to be explicit.
return color;
}
// This is where we decide
// what color the world will be!
// and what marvelous colors it will be!
vec3 colorTheWorld( vec2 rayHitInfo , vec3 eyePosition , vec3 rayDirection ){
// remember for color
// x = red , y = green , z = blue
vec3 color;
// THE LIL RAY WENT ALL THE WAY
// TO THE EDGE OF THE WORLD,
// AND DIDN'T HIT ANYTHING
if( rayHitInfo.y < 0.0 ){
color = doBackgroundColor();
// THE LIL RAY HIT SOMETHING!!!!
}else{
// If we hit something,
// we also know how far the ray has to travel to hit it
// and because we know the direction of the ray, we can
// get the exact position of where we hit the surface
// by following the ray from the eye, along its direction
// for the however far it had to travel to hit something
vec3 positionOfHit = eyePosition + rayHitInfo.x * rayDirection;
// We can then use this information to tell what direction
// the surface faces in
vec3 normalOfSurface = getNormalOfSurface( positionOfHit );
// 1.0 is the Balloon ID
if( rayHitInfo.y == 1.0 ){
color = doBalloonColor( positionOfHit , normalOfSurface );
// 2.0 is the Box ID
}else if( rayHitInfo.y == 2.0 ){
color = doBoxColor( positionOfHit , normalOfSurface );
}
else if( rayHitInfo.y == 3.0)
{
color = doTorusColor( positionOfHit , normalOfSurface );
}
}
return color;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
// Here we are getting our 'Position' of each pixel
// This section is important, because if we didn't
// divied by the resolution, our values would be masssive
// as fragCoord returns the value of how many pixels over we
// are. which is alot :)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// thats a super long name, so maybe we will
// keep on using uv, but im explicitly defining it
// so you can see exactly what those two letters mean
vec2 xyPositionOfPixelInWindow = p;
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// We use the eye position to tell use where the viewer is
float camRotSpeed = 0.5;
float rotRadius = 2.75;
float eyePosX = rotRadius * cos( camRotSpeed * iTime);
float eyePosZ = rotRadius * sin( camRotSpeed * iTime);
vec3 eyePosition = vec3( eyePosX, 0.5, eyePosZ); //vec3( 0., 0.5, 2.);
// This is the point the view is looking at.
// The window will be placed between the eye, and the
// position the eye is looking at!
vec3 pointWeAreLookingAt = vec3( 0. , 0. , 0. );
// This is where the magic of actual mathematics
// gives a way to actually place the window.
// the 0. at the end there gives the 'roll' of the transformation
// AKA we would be standing so up is up, but up could be changing
// like if we were one of those creepy dolls whos rotate their head
// all the way around along the z axis
mat3 eyeTransformationMatrix = calculateEyeRayTransformationMatrix( eyePosition , pointWeAreLookingAt , 0. );
// Here we get the actual ray that goes out of the eye
// and through the individual pixel! This basically the only thing
// that is different between the pixels, but is also the bread and butter
// of ray tracing. It should be since it has the word 'ray' in its variable name...
// the 2. at the end is the 'lens length' . I don't know how to best
// describe this, but once the full scene is built, tryin playing with it
// to understand inherently how it works
vec3 rayComingOutOfEyeDirection = normalize( eyeTransformationMatrix * vec3( p.xy , 2. ) );
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
vec2 rayHitInfo = checkRayHit( eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
vec3 color = colorTheWorld( rayHitInfo , eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
fragColor = vec4(color,1.0);
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
}
| cc0-1.0 | [
31087,
31208,
31268,
31268,
31467
] | [
[
15590,
15992,
16075,
16075,
16253
],
[
16457,
16474,
16517,
16517,
17738
],
[
17740,
17740,
17773,
17773,
17838
],
[
17840,
17840,
17884,
17884,
18130
],
[
18132,
18132,
18169,
18169,
18519
],
[
18521,
18521,
18552,
18552,
18668
],
[
18670,
18670,
18706,
18770,
18799
],
[
18802,
18802,
18841,
18882,
19967
],
[
19970,
20165,
20221,
20221,
20605
],
[
20613,
20765,
20809,
20809,
21118
],
[
22490,
22490,
22553,
22758,
27037
],
[
27214,
27576,
27625,
27625,
28622
],
[
28628,
28716,
28741,
28741,
28765
],
[
28770,
28770,
28834,
28834,
29925
],
[
29929,
29929,
29991,
29991,
31084
],
[
31087,
31208,
31268,
31268,
31467
],
[
31472,
31573,
31650,
31714,
33042
],
[
33046,
33046,
33103,
33547,
36672
]
] | // Here we are using the normal of the surface,
// and mapping it to color, to show you just how cool
// normals can be!
| vec3 doBoxColor(vec3 positionOfHit , vec3 normalOfSurface ){ |
vec3 color = vec3( normalOfSurface.x , normalOfSurface.y , normalOfSurface.z );
//could also just write color = normalOfSurce
//but trying to be explicit.
return color;
} | // Here we are using the normal of the surface,
// and mapping it to color, to show you just how cool
// normals can be!
vec3 doBoxColor(vec3 positionOfHit , vec3 normalOfSurface ){ | 3 | 3 |
4d33z4 | sagarpatel | 2015-11-23T08:44:22 | // @sagzorz
// My first shader on ShaderToy!
// The stuff below is pretty much all of the amazing @cabbibo's SDF tutorial
// https://www.shadertoy.com/view/Xl2XWt
// I read thorugh it then looked at IQ's page on distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// got inspired and remixed stuff in really messy code
// my only excuse was that I was in a rush since I did the tutorial and my hack all in a bus ride
// from Ha Long Bay to Hanoi and batteries were starting to run out :/
/*
CC0 1.0
@vrtree
who@tree.is
http://tree.is
I dont know if this is going to work, or be interesting,
or even understandable, But hey! Why not try!
To start, get inspired by some MAGICAL creations made by raytracing:
Volcanic by IQ
https://www.shadertoy.com/view/XsX3RB
Remnant X by Dave_Hoskins ( Audio Autoplay warnings )
https://www.shadertoy.com/view/4sjSW1
Cloud Ten by Nimitz
https://www.shadertoy.com/view/XtS3DD
Spectacles by MEEEEEE
https://www.shadertoy.com/view/4lBXWt
[2TC 15] Mystery Mountains by Dave_Hoskins
https://www.shadertoy.com/view/llsGW7
Raytracing graphics is kinda like baking cakes.
I want yall to first see how magical
the cake can be before trying to learn how to make it, because the thing we
make at first isn't going to be one of those crazy 10 story wedding cakes. its just
going to be some burnt sugar bread.
Making art using code can be so fufilling, and so infinite, but to get there you
need to learn some techniques that might not seem that inspiring. To bake a cake,
you first need to turn on an oven, and need to know what an oven even is. In this
tutorial we are going to be learning how to make the oven, how to turn it on,
and how to mix ingredients. as you can see on our left, our cake isn't very pretty
but it is a cake. and thats pretty crazy for just one tutorial!
Once you have gone through this tutorial, you can see a 'minimized' version
here: https://www.shadertoy.com/view/Xt2XDt
where I've rewritten it using the varibles and functions that
are used alot throughout shadertoy. The inspiration examples above
probably seem completely insane, because of all the single letter variable
names, but keep in mind, that they all start with most of the same ingredients
and overn that we will learn about right now!
I've tried to break up the code into 'sections'
which have the 'SECTION 'BLAH'' label above them. Not sure
if thats gonna help or not, but please leave comments
if you think something works or doesn't work, slash you
have any questions!!!
or contact me at @vrtree || @cabbibo
Cheat sheet for vectors:
x = left / right
y = up / down
z = forwards / backwards
also, for vectors labeled 'color'
x = red
y = green
z = blue
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
The best metaphor that I can think of for raytracing is
that the rectangle to our left is actually just a small window
into a fantastic world. We need to describe that world,
so that we can see it. BUT HOW ?!?!?!
What we are doing below is describing what color each pixel
of the window is, however because of the way that shader
programs work, we need to give the same instruction to every
single PIXEL ( or in shadertoy terms, FRAGMENT )
in the window. This is where the term SIMD comes
from : Same Instruction Multiple Data
In this case, the same instruction is the program below,
and the multiple data is the marvelous little piece of magic
called 'fragCoord' which is just the position of the pixel in
window. lets rename some things to look prettier.
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
If you think about what happens with an actual window, you
can begin to get an idea of how the magic of raytracing works
basically a bunch of rays come from the sun ( and or other
light sources ) , bounce around a bunch ( or a little ), and
eventually make it through the window, and into our eyes.
Now the number of rays are masssiveeee that come from the sun
and alot of them that are bouncing around, will end up going
directions that aren't even close to the window, or maybe
will hit the wall instead of the window.
We only care about the rays that go through the window
and make it to our eyeballs!
This means that we can be a bit intelligent. Instead of
figuring out the rays that come from the sun and bounce around
lets start with out eyes, and work backwards!!!!
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
After setting up all the neccesary ray information,
we FINALLY get to start building the scene. Up to this point,
we've only built up the window, and the rays that go from our
eyes through the window, but now we need to describe to the rays
if they hit anything and what they hit!
Now this part has some pretty scary code in it ( whenever I look
at it at least, my eyes glaze over ), so feel free to skip over
the checkRayHit function. I tried to explain it as best as I could
down below, and you might want to come back to it after going
throught the rest of the tutorial, but the important thing to
remember is the following:
These 'rays' that we've been talking about will move through the
scene along their direction. They do this iteratively, and at each
step will basically ask the question :
'HOW CLOSE AM I TO THINGS IN THE WORLD???'
because well, rays are lonely, and want to be closer to things in
the world. We provide them an answer to that question using our
description of the world, and they use this information to tell
them how much further along their path they should move. If the
answer to the question is:
'Lovely little ray, you are actually touching a thing in the world!'
We know what that the ray hit something, and can begin with our next
step!
The tricky part about this is that we have to as accuratly as
possible provide them an answer to their question 'how close??!!'
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
To answer the above concept, we are going to use this magical
concept called:
'Signed Distance Fields'
-----------------------
These things are the best, and very basically can be describe as
a function that takes in a position, and feeds back a value of
how close you are to a thing. If the value of this distance is negative
you are inside the thing, if it is positive, you are outside the thing
and if its 0 you are at the surface of the thing! This positive or negative
gives us the 'Signed' in 'Signed Distance Field'
For a super intensive description of many of the SDFs out there
check out Inigo Quilez's site:
http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm
Also, if you want a deep dive into why these functions are the
ultimate magic, check out this crazy paper by the geniouses
over at Media Molecule about their new game: 'DREAMS'
http://media.lolrus.mediamolecule.com/AlexEvans_SIGGRAPH-2015.pdf
Needless to say, these lil puppies are super amazing, and are
here to free us from the tyranny of polygons.
---------
We are going to put all of our SDFs into a single function called
'mapTheWorld'
which will take in a position, and feed back two values.
The first value is the Distance of Signed Distance Field, and the
second value will tell us what we are closest too, so that if
we actually hit something, we can tell what it is. We will denote this
by an 'ID' value.
The hardest part for me to wrap my head around for this was the fact that
these fields do not just describe where the surface of an object is,
they actually describe how far you are from the object from ANYWHERE
in the world.
For example, if I was hitting a round ballon ( AKA a sphere :) )
I wouldn't just know if I was on the surface of the ballon, I would have
to know how close I was to the balloon from anywhere in space.
Check out the 'TAG : BALLOON' in the mapTheWorld function for more detail :)
I've also made a function for a box, that is slightly more complex, and to be
honest, I don't exactly understand the math of it, but the beauty of programming
is that someone else ( AKA Inigo ) does, and I can steal his knowledge, just by
looking at the functions from his website!
---------
One of the magical properties of SDFs is how easily they can be combined
contorted, and manipulated. They are just these lil functions that take
in a position and give back a distance value, so we can do things like play with the
input position, play with the output distance value, or just about anything
else.
We'll start by combining two SDFs by asking the simple question
'Which thing am I closer to?'
which is as simple as a '>' because we already know exactly how close we are
to each thing!
check out 'TAG : WHICH AM I CLOSER TO?' for more enough
We use these function to create a map of the world for the rays to navigate,
and than pass that map to the checkRayHit, which propates the rays throughout
the world and tells us what they hit.
Once they know that, we can FINALLY do our last step:
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD!
//--------------------------------------------------------------
At the end of our checkRayHit function we return a vec2 with two values:
.x is the distance that our ray traveled before hitting
.y is the ID of the thing that we hit.
if .y is less that 0.0 that means that our ray went as far as we allowed it
to go without hitting anything. thats one lonely ray :(
however, that doesn't mean that the ray didn't hit anything. It just meant
that it is part of the background.
Thanks little ray!
You told us important information about our scene,
and your hard work is helping to create the world!
We can get reallly crazy with how we color the background of the scene,
but for this tutorial lets just keep it black, because who doesn't love
the void.
we will use the function 'doBackgroundColor' to accomplish this task!
That tells us about the background, but what if .y is greater than 0.0?
then we get to make some stuff in the scene!
if the ID is equal to balloon id, then we 'doBalloonColor'
and if the ID is equal to the box , then we 'doBoxColor'
This is all that we need if we want to color simple solid objects,
but what if we want to add some shading, by doing what we originally
talked about, that is, following the ray to the sun?
For this first tutorial, we will keep it to a very naive approach,
but once you get the basics of sections A - D, we can get SUPER crazy
with this 'color' the world section.
For example, we could reflect the
ray off the surface, and than repeat the checkRayHit with this new information
continuing to follow this ray through more and more of the world. we could
repeat this process again and again, and even though our gpu would hate us
we could continue bouncing around until we got to a light source!
In a later tutorial we will do exactly this, but for now,
we are going to do 1 simple task:
See how much the surface that we hit, faces the sun.
to do that we need to do 2 things.
First, determine which way the surface faces
Second, determine which way rays go from the surface to get to the sun
1) To determine the way that the surface faces, we will use a function called
'getNormalOfSurface' This function will either make 100% sense, or 0% sense
depending on how often you have played with fields, but it made 0% sense to me
for many years, so don't worry if you don't get it! Whats important is that
it gives us the direction that the surface faces, which we call its 'Normal'
You can think of it as a vector that is perpendicular to the surface at a specific point
So that it is easier to understand what this value is, we are actually going to color our
box based on this value. We will map the X value of the normal to red, the Y value of the
normal to green and the Z value of the normal to blue. You can see this more in the
'doBoxColor' function
2) To get the direction the rays go to get to the sun, we just need to subtract the sun
position from the position of where we hit. This will provide us a direction from the sun
to the position. Look inside the doBalloonColor to see this calculation happen.
this will give us the direction of the rays from the sun to the surface!
Now that we have these 2 pieces of information, the last thing we need to do is see
how much the two vectors ( the normal and the light direction ) 'Face' each other.
that word 'Face', might not make much sense in this context, but think about it this way.
If you have a table, and a light above the table, the top of the table will 'Face',
the light, and the bottom of the table will 'Face' away from the light. The surface
that 'Faces' the light will get hit by the rays from the light, while the surface
that 'Faces' away from the light will be totally dark!
so how do we get this 'Face' value ( pun intended :p ) ?
There is a magical function called a 'dot product' which does exactly this. you
can read more here:
https://en.wikipedia.org/wiki/Dot_product
basically this function takes in 2 vectors, and feeds back a value from -1 -> 1.
if the value is -1 , the two vectors face in exact opposite directions, and if
the value is 1 , the two vectors face in exactly the same direction. if the value is
0, than they are perpendicular!
By using the dot product, we take get the ballon's 'Face' value and color it depending
on this value!
check out the doBallonColor to see all this craziness in action
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
What a journey it has been. Remember back when we were talking about
sending rays through the window? Remember them moving all through the
world trying to be closer to things?
So much has happened, and at the end of that journey, we got a color for each ray!
now all we need to do is output that color onto the screen , which is a single call,
and we've made our world.
I know this stuff might seem too dry or too complex at times, too confusing,
too frustrating, but I promise, if you stick with it, you'll soon be making some of the
other magical structures you see throughout the rest of this site.
I'll be trying to do some more of these tutorials, and you'll see that VERY
quickly, you get from this hideous monstrosity to our left, to marvelous worlds
filled with lights, colors, and love.
Thanks for staying around, and please contact me:
@vrtree , @cabbibo with questions, concerns , and improvments. Or just comment!
*/
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// Most of this is taken from many of the shaders
// that @iq have worked on. Make sure to check out
// more of his magic!!!
// This calculation basically gets a way for us to
// transform the rays coming out of our eyes and going through the window.
// If it doesn't make sense, thats ok. It doesn't make sense to me either :)
// Whats important to remember is that this basically gives us a way to position
// our window. We could you it to make the window look north, south, east, west, up, down
// or ANYWHERE in between!
mat3 calculateEyeRayTransformationMatrix( in vec3 ro, in vec3 ta, in float roll )
{
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(sin(roll),cos(roll),0.0) ) );
vec3 vv = normalize( cross(uu,ww));
return mat3( uu, vv, ww );
}
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
//'TAG: BALLOON'
vec2 sdfBalloon( vec3 currentRayPosition ){
float ballOrbitSpeed = 0.85;
float ballOrbitRadius = 1.0;
vec3 ballOrbitOffset = vec3(1.0,0,0);
float balloonPosX = ballOrbitRadius * cos( ballOrbitSpeed * iTime);
float balloonPosY = ballOrbitRadius * sin( ballOrbitSpeed * iTime);
// First we define our balloon position
vec3 balloonPosition = ballOrbitOffset + vec3(balloonPosX,balloonPosY,0); //vec3( -1.3 , .3 , -0.4 );
// than we define our balloon radius
float balloonRadius = 0.51;
// Here we get the distance to the surface of the balloon
float distanceToBalloon = length( currentRayPosition - balloonPosition );
// finally we get the distance to the balloon surface
// by substacting the balloon radius. This means that if
// the distance to the balloon is less than the balloon radius
// the value we get will be negative! giving us the 'Signed' in
// Signed Distance Field!
float distanceToBalloonSurface = distanceToBalloon - balloonRadius;
// Finally we build the full balloon information, by giving it an ID
float balloonID = 1.;
// And there we have it! A fully described balloon!
vec2 balloon = vec2( distanceToBalloonSurface, balloonID );
return balloon;
}
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
float opTwist_Torus( vec3 p , vec2 torusS)
{
float twistSpedd = 0.35;
float c = cos( 15.0 * (sin( twistSpedd * iTime)) *p.y );
float s = sin( 15.0 * (sin( twistSpedd * iTime)) *p.y );
mat2 m = mat2(c,-s,s,c);
vec3 q = vec3(m*p.xz,p.y);
return sdTorus(q, torusS);
}
vec2 sdfTorus( vec3 currentRayPos )
{
vec3 torusPos = vec3( 0.0, 0.0, 0.0);
vec2 torusSpec = vec2(0.6, 0.23);
vec3 adjustedRayPos = currentRayPos - torusPos;
float distToTorusSurface = opTwist_Torus(adjustedRayPos, torusSpec); //sdTorus(adjustedRayPos, torusSpec);
float torusID = 3.;
vec2 torus = vec2( distToTorusSurface, torusID);
return torus;
}
float smin( float a, float b)
{
float k = 0.77521;
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
float opBlend( float d1, float d2)
{
//float d1 = primitiveA(p);
//float d2 = primitiveB(p);
return smin( d1, d2 );
}
vec2 sdfBox( vec3 currentRayPosition ){
// First we define our box position
vec3 boxPosition = vec3( -.8 , -.4 , 0.2 );
// than we define our box dimensions using x , y and z
vec3 boxSize = vec3( .4 , .3 , .2 );
// Here we get the 'adjusted ray position' which is just
// writing the point of the ray as if the origin of the
// space was where the box was positioned, instead of
// at 0,0,0 . AKA the difference between the vectors in
// vector format.
vec3 adjustedRayPosition = currentRayPosition - boxPosition;
// finally we get the distance to the box surface.
// I don't get this part very much, but I bet Inigo does!
// Thanks for making code for us IQ !
vec3 distanceVec = abs( adjustedRayPosition ) - boxSize;
float maxDistance = max( distanceVec.x , max( distanceVec.y , distanceVec.z ) );
float distanceToBoxSurface = min( maxDistance , 0.0 ) + length( max( distanceVec , 0.0 ) );
// Finally we build the full box information, by giving it an ID
float boxID = 2.;
// And there we have it! A fully described box!
vec2 box = vec2( distanceToBoxSurface, boxID );
return box;
}
// 'TAG : WHICH AM I CLOSER TO?'
// This function takes in two things
// and says which is closer by using the
// distance to each thing, comparing them
// and returning the one that is closer!
vec2 whichThingAmICloserTo( vec2 thing1 , vec2 thing2 ){
vec2 closestThing;
// Check out the balloon function
// and remember how the x of the returned
// information is the distance, and the y
// is the id of the thing!
if( thing1.x <= thing2.x ){
closestThing = thing1;
}else if( thing2.x < thing1.x ){
closestThing = thing2;
}
return closestThing;
}
// Takes in the position of the ray, and feeds back
// 2 values of how close it is to things in the world
// what thing it is closest two in the world.
vec2 mapTheWorld( vec3 currentRayPosition ){
vec2 result;
vec2 balloon = sdfBalloon( currentRayPosition );
//vec2 box = sdfBox( currentRayPosition );
vec2 torus = sdfTorus( currentRayPosition );
result = whichThingAmICloserTo( balloon , torus); //box );
result.x = opBlend( balloon.x, torus.x);
return result;
}
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
// We want to know when the closeness to things in the world is
// 0.0 , but if we wanted to get exactly to 0 it would take us
// alot of time to be that precise. Here we define the laziness
// our navigation function. try chaning the value to see what it does!
// if you are getting too low of framerates, this value will help alot,
// but can also make your scene look very different
// from how it should
const float HOW_CLOSE_IS_CLOSE_ENOUGH = 0.0001;
// This is basically how big our scene is. each ray will be shot forward
// until it reaches this distance. the smaller it is, the quicker the
// ray will reach the edge, which should help speed up this function
const float FURTHEST_OUR_RAY_CAN_REACH = 10.75;
// This is how may steps our ray can take. Hopefully for this
// simple of a world, it will very quickly get to the 'close enough' value
// and stop the iteration, but for more complex scenes, this value
// will dramatically change not only how good the scene looks
// but how fast teh scene can render.
// remember that for each pixel we are displaying, the 'mapTheWorld' function
// could be called this many times! Thats ALOT of calculations!!!
const int HOW_MANY_STEPS_CAN_OUR_RAY_TAKE = 2000;
vec2 checkRayHit( in vec3 eyePosition , in vec3 rayDirection ){
//First we set some default values
// our distance to surface will get overwritten every step,
// so all that is important is that it is greater than our
// 'how close is close enough' value
float distanceToSurface = HOW_CLOSE_IS_CLOSE_ENOUGH * 2.;
// The total distance traveled by the ray obviously should start at 0
float totalDistanceTraveledByRay = 0.;
// if we hit something, this value will be overwritten by the
// totalDistance traveled, and if we don't hit something it will
// be overwritten by the furthest our ray can reach,
// so it can be whatever!
float finalDistanceTraveledByRay = -1.;
// if our id is less that 0. , it means we haven't hit anything
// so lets start by saying we haven't hit anything!
float finalID = -1.;
//here is the loop where the magic happens
for( int i = 0; i < HOW_MANY_STEPS_CAN_OUR_RAY_TAKE; i++ ){
// First off, stop the iteration, if we are close enough to the surface!
if( distanceToSurface < HOW_CLOSE_IS_CLOSE_ENOUGH ) break;
// Second off, stop the iteration, if we have reached the end of our scene!
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ) break;
// To check how close we are to things in the world,
// we need to get a position in the scene. to do this,
// we start at the rays origin, AKA the eye
// and move along the ray direction, the amount we have already traveled.
vec3 currentPositionOfRay = eyePosition + rayDirection * totalDistanceTraveledByRay;
// Distance to and ID of things in the world
//--------------------------------------------------------------
// SECTION 'D' : MAPPING THE WORLD , AKA 'SDFS ARE AWESOME!!!!'
//--------------------------------------------------------------
vec2 distanceAndIDOfThingsInTheWorld = mapTheWorld( currentPositionOfRay );
// we get out the results from our mapping of the world
// I am reassigning them for clarity
float distanceToThingsInTheWorld = distanceAndIDOfThingsInTheWorld.x;
float idOfClosestThingInTheWorld = distanceAndIDOfThingsInTheWorld.y;
// We save out the distance to the surface, so that
// next iteration we can check to see if we are close enough
// to stop all this silly iteration
distanceToSurface = distanceToThingsInTheWorld;
// We are also finalID to the current closest id,
// because if we hit something, we will have the proper
// id, and we can skip reassigning it later!
finalID = idOfClosestThingInTheWorld;
// ATTENTION: THIS THING IS AWESOME!
// This last little calculation is probably the coolest hack
// of this entire tutorial. If we wanted too, we could basically
// step through the field at a constant amount, and at every step
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// say 'am i there yet', than move forward a little bit, and
// that would take FOREVER, and get really annoying.
// Instead what we say is 'How far until we are there?'
// and move forward by that amount. This means that if
// we are really far away from everything, we can make large
// movements towards the surface, and if we are closer
// we can make more precise movements. making our marching functino
// faster, and ideally more precise!!
// WOW!
totalDistanceTraveledByRay += 0.05 * distanceToThingsInTheWorld; //0.001 + distanceToThingsInTheWorld * abs(sin(iTime)); //distanceToThingsInTheWorld;
}
// if we hit something set the finalDirastnce traveled by
// ray to that distance!
if( totalDistanceTraveledByRay < FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = totalDistanceTraveledByRay;
}
// If the total distance traveled by the ray is further than
// the ray can reach, that means that we've hit the edge of the scene
// Set the final distance to be the edge of the scene
// and the id to -1 to make sure we know we haven't hit anything
if( totalDistanceTraveledByRay > FURTHEST_OUR_RAY_CAN_REACH ){
finalDistanceTraveledByRay = FURTHEST_OUR_RAY_CAN_REACH;
finalID = -1.;
}
return vec2( finalDistanceTraveledByRay , finalID );
}
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
// Here we are calcuting the normal of the surface
// Although it looks like alot of code, it actually
// is just trying to do something very simple, which
// is to figure out in what direction the SDF is increasing.
// What is amazing, is that this value is the same thing
// as telling you what direction the surface faces, AKA the
// normal of the surface.
vec3 getNormalOfSurface( in vec3 positionOfHit ){
vec3 tinyChangeX = vec3( 0.001, 0.0, 0.0 );
vec3 tinyChangeY = vec3( 0.0 , 0.001 , 0.0 );
vec3 tinyChangeZ = vec3( 0.0 , 0.0 , 0.001 );
float upTinyChangeInX = mapTheWorld( positionOfHit + tinyChangeX ).x;
float downTinyChangeInX = mapTheWorld( positionOfHit - tinyChangeX ).x;
float tinyChangeInX = upTinyChangeInX - downTinyChangeInX;
float upTinyChangeInY = mapTheWorld( positionOfHit + tinyChangeY ).x;
float downTinyChangeInY = mapTheWorld( positionOfHit - tinyChangeY ).x;
float tinyChangeInY = upTinyChangeInY - downTinyChangeInY;
float upTinyChangeInZ = mapTheWorld( positionOfHit + tinyChangeZ ).x;
float downTinyChangeInZ = mapTheWorld( positionOfHit - tinyChangeZ ).x;
float tinyChangeInZ = upTinyChangeInZ - downTinyChangeInZ;
vec3 normal = vec3(
tinyChangeInX,
tinyChangeInY,
tinyChangeInZ
);
return normalize(normal);
}
// doing our background color is easy enough,
// just make it pure black. like my soul.
vec3 doBackgroundColor(){
return vec3( 0.75 );
}
vec3 doBalloonColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 balloonColor = vec3( 1. , 0. , 0. );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = balloonColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
vec3 doTorusColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 sunPosition = vec3( 1. , 4. , 3. );
// the direction of the light goes from the sun
// to the position of the hit
vec3 lightDirection = sunPosition - positionOfHit;
// Here we are 'normalizing' the light direction
// because we don't care how long it is, we
// only care what direction it is!
lightDirection = normalize( lightDirection );
// getting the value of how much the surface
// faces the light direction
float faceValue = dot( lightDirection , normalOfSurface );
// if the face value is negative, just make it 0.
// so it doesn't give back negative light values
// cuz that doesn't really make sense...
faceValue = max( 0. , faceValue );
vec3 torusColor = vec3( 0.25 , 0.95 , 0.25 );
// our final color is the balloon color multiplied
// by how much the surface faces the light
vec3 color = torusColor * faceValue;
// add in a bit of ambient color
// just so we don't get any pure black
color += vec3( .3 , .1, .2 );
return color;
}
// Here we are using the normal of the surface,
// and mapping it to color, to show you just how cool
// normals can be!
vec3 doBoxColor(vec3 positionOfHit , vec3 normalOfSurface ){
vec3 color = vec3( normalOfSurface.x , normalOfSurface.y , normalOfSurface.z );
//could also just write color = normalOfSurce
//but trying to be explicit.
return color;
}
// This is where we decide
// what color the world will be!
// and what marvelous colors it will be!
vec3 colorTheWorld( vec2 rayHitInfo , vec3 eyePosition , vec3 rayDirection ){
// remember for color
// x = red , y = green , z = blue
vec3 color;
// THE LIL RAY WENT ALL THE WAY
// TO THE EDGE OF THE WORLD,
// AND DIDN'T HIT ANYTHING
if( rayHitInfo.y < 0.0 ){
color = doBackgroundColor();
// THE LIL RAY HIT SOMETHING!!!!
}else{
// If we hit something,
// we also know how far the ray has to travel to hit it
// and because we know the direction of the ray, we can
// get the exact position of where we hit the surface
// by following the ray from the eye, along its direction
// for the however far it had to travel to hit something
vec3 positionOfHit = eyePosition + rayHitInfo.x * rayDirection;
// We can then use this information to tell what direction
// the surface faces in
vec3 normalOfSurface = getNormalOfSurface( positionOfHit );
// 1.0 is the Balloon ID
if( rayHitInfo.y == 1.0 ){
color = doBalloonColor( positionOfHit , normalOfSurface );
// 2.0 is the Box ID
}else if( rayHitInfo.y == 2.0 ){
color = doBoxColor( positionOfHit , normalOfSurface );
}
else if( rayHitInfo.y == 3.0)
{
color = doTorusColor( positionOfHit , normalOfSurface );
}
}
return color;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
//---------------------------------------------------
// SECTION 'A' : ONE PROGRAM FOR EVERY PIXEL!
//---------------------------------------------------
// Here we are getting our 'Position' of each pixel
// This section is important, because if we didn't
// divied by the resolution, our values would be masssive
// as fragCoord returns the value of how many pixels over we
// are. which is alot :)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// thats a super long name, so maybe we will
// keep on using uv, but im explicitly defining it
// so you can see exactly what those two letters mean
vec2 xyPositionOfPixelInWindow = p;
//---------------------------------------------------
// SECTION 'B' : BUILDING THE WINDOW
//---------------------------------------------------
// We use the eye position to tell use where the viewer is
float camRotSpeed = 0.5;
float rotRadius = 2.75;
float eyePosX = rotRadius * cos( camRotSpeed * iTime);
float eyePosZ = rotRadius * sin( camRotSpeed * iTime);
vec3 eyePosition = vec3( eyePosX, 0.5, eyePosZ); //vec3( 0., 0.5, 2.);
// This is the point the view is looking at.
// The window will be placed between the eye, and the
// position the eye is looking at!
vec3 pointWeAreLookingAt = vec3( 0. , 0. , 0. );
// This is where the magic of actual mathematics
// gives a way to actually place the window.
// the 0. at the end there gives the 'roll' of the transformation
// AKA we would be standing so up is up, but up could be changing
// like if we were one of those creepy dolls whos rotate their head
// all the way around along the z axis
mat3 eyeTransformationMatrix = calculateEyeRayTransformationMatrix( eyePosition , pointWeAreLookingAt , 0. );
// Here we get the actual ray that goes out of the eye
// and through the individual pixel! This basically the only thing
// that is different between the pixels, but is also the bread and butter
// of ray tracing. It should be since it has the word 'ray' in its variable name...
// the 2. at the end is the 'lens length' . I don't know how to best
// describe this, but once the full scene is built, tryin playing with it
// to understand inherently how it works
vec3 rayComingOutOfEyeDirection = normalize( eyeTransformationMatrix * vec3( p.xy , 2. ) );
//---------------------------------------------------
// SECTION 'C' : NAVIGATING THE WORLD
//---------------------------------------------------
vec2 rayHitInfo = checkRayHit( eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'E' : COLORING THE WORLD
//--------------------------------------------------------------
vec3 color = colorTheWorld( rayHitInfo , eyePosition , rayComingOutOfEyeDirection );
//--------------------------------------------------------------
// SECTION 'F' : Wrapping up
//--------------------------------------------------------------
fragColor = vec4(color,1.0);
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
// WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW! WOW!
}
| cc0-1.0 | [
31472,
31573,
31650,
31714,
33042
] | [
[
15590,
15992,
16075,
16075,
16253
],
[
16457,
16474,
16517,
16517,
17738
],
[
17740,
17740,
17773,
17773,
17838
],
[
17840,
17840,
17884,
17884,
18130
],
[
18132,
18132,
18169,
18169,
18519
],
[
18521,
18521,
18552,
18552,
18668
],
[
18670,
18670,
18706,
18770,
18799
],
[
18802,
18802,
18841,
18882,
19967
],
[
19970,
20165,
20221,
20221,
20605
],
[
20613,
20765,
20809,
20809,
21118
],
[
22490,
22490,
22553,
22758,
27037
],
[
27214,
27576,
27625,
27625,
28622
],
[
28628,
28716,
28741,
28741,
28765
],
[
28770,
28770,
28834,
28834,
29925
],
[
29929,
29929,
29991,
29991,
31084
],
[
31087,
31208,
31268,
31268,
31467
],
[
31472,
31573,
31650,
31714,
33042
],
[
33046,
33046,
33103,
33547,
36672
]
] | // This is where we decide
// what color the world will be!
// and what marvelous colors it will be!
| vec3 colorTheWorld( vec2 rayHitInfo , vec3 eyePosition , vec3 rayDirection ){ |
vec3 color;
// THE LIL RAY WENT ALL THE WAY
// TO THE EDGE OF THE WORLD,
// AND DIDN'T HIT ANYTHING
if( rayHitInfo.y < 0.0 ){
color = doBackgroundColor();
// THE LIL RAY HIT SOMETHING!!!!
}else{
// If we hit something,
// we also know how far the ray has to travel to hit it
// and because we know the direction of the ray, we can
// get the exact position of where we hit the surface
// by following the ray from the eye, along its direction
// for the however far it had to travel to hit something
vec3 positionOfHit = eyePosition + rayHitInfo.x * rayDirection;
// We can then use this information to tell what direction
// the surface faces in
vec3 normalOfSurface = getNormalOfSurface( positionOfHit );
// 1.0 is the Balloon ID
if( rayHitInfo.y == 1.0 ){
color = doBalloonColor( positionOfHit , normalOfSurface );
// 2.0 is the Box ID
}else if( rayHitInfo.y == 2.0 ){
color = doBoxColor( positionOfHit , normalOfSurface );
}
else if( rayHitInfo.y == 3.0)
{
color = doTorusColor( positionOfHit , normalOfSurface );
}
}
return color;
} | // This is where we decide
// what color the world will be!
// and what marvelous colors it will be!
vec3 colorTheWorld( vec2 rayHitInfo , vec3 eyePosition , vec3 rayDirection ){ | 1 | 3 |
llBSWc | qwert33 | 2015-11-06T23:18:34 | // Made by Dominik Schmid
// MIT license
// biases x to be closer to 0 or 1
// can act like a parameterized smoothstep
// https://www.desmos.com/calculator/c4w7ktzhhk
// if b is near 1.0 then numbers a little closer to 1.0 are returned
// if b is near 0.0 then numbers a little closer to 0.0 are returned
// if b is near 0.5 then values near x are returned
float bias(float x, float b) {
b = -log2(1.0 - b);
return 1.0 - pow(1.0 - pow(x, 1./b), b);
}
float PI = 3.1415926;
#define t iTime
#define bias_number 0.4*sin(iTime) + 0.5
float formula(float x) {
return bias(x, bias_number);
}
bool isClose(float a, float b) { return abs(a-b) < 0.005; }
void plot(out vec4 fragColor, in vec2 uv )
{
float px = 2.0 / iResolution.x;
float py = 2.0 / iResolution.y;
vec4 color = vec4(1.0, 1.0, 1.0, 1.0);
vec4 blue = vec4(0.1, 0.1, 0.9, 1.0);
if (isClose(uv.x, 0.5)) color = blue;
if (isClose(uv.x, 1.5)) color = blue;
if (isClose(uv.y, 0.5)) color = blue;
if (isClose(uv.y, 1.0)) color = blue;
float x = (uv.x - .5);
float y = formula(x);
float y2 = formula(x + px*.5);
float dy = max(px*4.0, abs(y2 - y));
float modX = floor(.5+10.0*(uv.x-.5)) / 10.0;
float fmodX = formula(modX);
// 2d samples
// ok but wonky and horribly inefficient
float avg = 0.0;
float screen_y = 0.0;
float stroke = 1.0;
float dist = 0.0;
for (float step_x = -1.0; step_x < 1.0; step_x += .1)
{
x = (uv.x - .5 +3.0*stroke*(-step_x)*px);
for (float step_y = -1.0; step_y < 1.0; step_y += .1)
{
y = formula(x);
screen_y = uv.y + stroke*(-step_y)*py;
dist = step_x*step_x + step_y*step_y;
dist /= stroke*stroke;
avg += (1.0 - min(1.0,(abs(screen_y-.5 - .5*y)/py))) /dist;
}
}
avg /= 100.0;
color.r -= avg;
color.g -= avg;
color.b -= avg;
fragColor = color;
}
// creates white noise in the range 0..1 including 0 excluding 1
float rand(vec2 p){
p /= iResolution.xy;
return fract(sin(dot(p.xy, vec2(12.9898, 78.2377))) * 43758.5453);
}
// creates white noise in the range 0..1 including 0 including 1
float rand_inclusive(vec2 p){
return clamp(rand(p)*1.005, 0.0, 1.0);
}
void applyBias(out vec4 fragColor, in vec2 fragCoord) {
fragColor = vec4(
bias(rand_inclusive(fragCoord), bias_number)
);
}
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 uv = fragCoord.xy / iResolution.xy;
if (isClose(uv.x, 0.5)) {
fragColor = vec4(0.5);
}
else if (uv.x < 0.5) {
uv += vec2(0.4, 0.3);
uv -= vec2(0.5);
uv *= vec2(3.0, 1.0);
uv += vec2(0.5);
//uv += vec2(0.5, 0.0);
plot(fragColor, uv);
}
else {
applyBias(fragColor, fragCoord);
}
} | mit | [
44,
360,
390,
390,
461
] | [
[
44,
360,
390,
390,
461
],
[
544,
544,
568,
568,
603
],
[
604,
604,
636,
636,
663
],
[
664,
664,
708,
708,
1985
],
[
1989,
2054,
2073,
2073,
2171
],
[
2173,
2238,
2267,
2267,
2313
],
[
2316,
2316,
2371,
2371,
2455
],
[
2457,
2457,
2512,
2512,
2893
]
] | // biases x to be closer to 0 or 1
// can act like a parameterized smoothstep
// https://www.desmos.com/calculator/c4w7ktzhhk
// if b is near 1.0 then numbers a little closer to 1.0 are returned
// if b is near 0.0 then numbers a little closer to 0.0 are returned
// if b is near 0.5 then values near x are returned
| float bias(float x, float b) { |
b = -log2(1.0 - b);
return 1.0 - pow(1.0 - pow(x, 1./b), b);
} | // biases x to be closer to 0 or 1
// can act like a parameterized smoothstep
// https://www.desmos.com/calculator/c4w7ktzhhk
// if b is near 1.0 then numbers a little closer to 1.0 are returned
// if b is near 0.0 then numbers a little closer to 0.0 are returned
// if b is near 0.5 then values near x are returned
float bias(float x, float b) { | 1 | 5 |
llBSWc | qwert33 | 2015-11-06T23:18:34 | // Made by Dominik Schmid
// MIT license
// biases x to be closer to 0 or 1
// can act like a parameterized smoothstep
// https://www.desmos.com/calculator/c4w7ktzhhk
// if b is near 1.0 then numbers a little closer to 1.0 are returned
// if b is near 0.0 then numbers a little closer to 0.0 are returned
// if b is near 0.5 then values near x are returned
float bias(float x, float b) {
b = -log2(1.0 - b);
return 1.0 - pow(1.0 - pow(x, 1./b), b);
}
float PI = 3.1415926;
#define t iTime
#define bias_number 0.4*sin(iTime) + 0.5
float formula(float x) {
return bias(x, bias_number);
}
bool isClose(float a, float b) { return abs(a-b) < 0.005; }
void plot(out vec4 fragColor, in vec2 uv )
{
float px = 2.0 / iResolution.x;
float py = 2.0 / iResolution.y;
vec4 color = vec4(1.0, 1.0, 1.0, 1.0);
vec4 blue = vec4(0.1, 0.1, 0.9, 1.0);
if (isClose(uv.x, 0.5)) color = blue;
if (isClose(uv.x, 1.5)) color = blue;
if (isClose(uv.y, 0.5)) color = blue;
if (isClose(uv.y, 1.0)) color = blue;
float x = (uv.x - .5);
float y = formula(x);
float y2 = formula(x + px*.5);
float dy = max(px*4.0, abs(y2 - y));
float modX = floor(.5+10.0*(uv.x-.5)) / 10.0;
float fmodX = formula(modX);
// 2d samples
// ok but wonky and horribly inefficient
float avg = 0.0;
float screen_y = 0.0;
float stroke = 1.0;
float dist = 0.0;
for (float step_x = -1.0; step_x < 1.0; step_x += .1)
{
x = (uv.x - .5 +3.0*stroke*(-step_x)*px);
for (float step_y = -1.0; step_y < 1.0; step_y += .1)
{
y = formula(x);
screen_y = uv.y + stroke*(-step_y)*py;
dist = step_x*step_x + step_y*step_y;
dist /= stroke*stroke;
avg += (1.0 - min(1.0,(abs(screen_y-.5 - .5*y)/py))) /dist;
}
}
avg /= 100.0;
color.r -= avg;
color.g -= avg;
color.b -= avg;
fragColor = color;
}
// creates white noise in the range 0..1 including 0 excluding 1
float rand(vec2 p){
p /= iResolution.xy;
return fract(sin(dot(p.xy, vec2(12.9898, 78.2377))) * 43758.5453);
}
// creates white noise in the range 0..1 including 0 including 1
float rand_inclusive(vec2 p){
return clamp(rand(p)*1.005, 0.0, 1.0);
}
void applyBias(out vec4 fragColor, in vec2 fragCoord) {
fragColor = vec4(
bias(rand_inclusive(fragCoord), bias_number)
);
}
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 uv = fragCoord.xy / iResolution.xy;
if (isClose(uv.x, 0.5)) {
fragColor = vec4(0.5);
}
else if (uv.x < 0.5) {
uv += vec2(0.4, 0.3);
uv -= vec2(0.5);
uv *= vec2(3.0, 1.0);
uv += vec2(0.5);
//uv += vec2(0.5, 0.0);
plot(fragColor, uv);
}
else {
applyBias(fragColor, fragCoord);
}
} | mit | [
1989,
2054,
2073,
2073,
2171
] | [
[
44,
360,
390,
390,
461
],
[
544,
544,
568,
568,
603
],
[
604,
604,
636,
636,
663
],
[
664,
664,
708,
708,
1985
],
[
1989,
2054,
2073,
2073,
2171
],
[
2173,
2238,
2267,
2267,
2313
],
[
2316,
2316,
2371,
2371,
2455
],
[
2457,
2457,
2512,
2512,
2893
]
] | // creates white noise in the range 0..1 including 0 excluding 1
| float rand(vec2 p){ |
p /= iResolution.xy;
return fract(sin(dot(p.xy, vec2(12.9898, 78.2377))) * 43758.5453);
} | // creates white noise in the range 0..1 including 0 excluding 1
float rand(vec2 p){ | 1 | 12 |
llBSWc | qwert33 | 2015-11-06T23:18:34 | // Made by Dominik Schmid
// MIT license
// biases x to be closer to 0 or 1
// can act like a parameterized smoothstep
// https://www.desmos.com/calculator/c4w7ktzhhk
// if b is near 1.0 then numbers a little closer to 1.0 are returned
// if b is near 0.0 then numbers a little closer to 0.0 are returned
// if b is near 0.5 then values near x are returned
float bias(float x, float b) {
b = -log2(1.0 - b);
return 1.0 - pow(1.0 - pow(x, 1./b), b);
}
float PI = 3.1415926;
#define t iTime
#define bias_number 0.4*sin(iTime) + 0.5
float formula(float x) {
return bias(x, bias_number);
}
bool isClose(float a, float b) { return abs(a-b) < 0.005; }
void plot(out vec4 fragColor, in vec2 uv )
{
float px = 2.0 / iResolution.x;
float py = 2.0 / iResolution.y;
vec4 color = vec4(1.0, 1.0, 1.0, 1.0);
vec4 blue = vec4(0.1, 0.1, 0.9, 1.0);
if (isClose(uv.x, 0.5)) color = blue;
if (isClose(uv.x, 1.5)) color = blue;
if (isClose(uv.y, 0.5)) color = blue;
if (isClose(uv.y, 1.0)) color = blue;
float x = (uv.x - .5);
float y = formula(x);
float y2 = formula(x + px*.5);
float dy = max(px*4.0, abs(y2 - y));
float modX = floor(.5+10.0*(uv.x-.5)) / 10.0;
float fmodX = formula(modX);
// 2d samples
// ok but wonky and horribly inefficient
float avg = 0.0;
float screen_y = 0.0;
float stroke = 1.0;
float dist = 0.0;
for (float step_x = -1.0; step_x < 1.0; step_x += .1)
{
x = (uv.x - .5 +3.0*stroke*(-step_x)*px);
for (float step_y = -1.0; step_y < 1.0; step_y += .1)
{
y = formula(x);
screen_y = uv.y + stroke*(-step_y)*py;
dist = step_x*step_x + step_y*step_y;
dist /= stroke*stroke;
avg += (1.0 - min(1.0,(abs(screen_y-.5 - .5*y)/py))) /dist;
}
}
avg /= 100.0;
color.r -= avg;
color.g -= avg;
color.b -= avg;
fragColor = color;
}
// creates white noise in the range 0..1 including 0 excluding 1
float rand(vec2 p){
p /= iResolution.xy;
return fract(sin(dot(p.xy, vec2(12.9898, 78.2377))) * 43758.5453);
}
// creates white noise in the range 0..1 including 0 including 1
float rand_inclusive(vec2 p){
return clamp(rand(p)*1.005, 0.0, 1.0);
}
void applyBias(out vec4 fragColor, in vec2 fragCoord) {
fragColor = vec4(
bias(rand_inclusive(fragCoord), bias_number)
);
}
void mainImage(out vec4 fragColor, in vec2 fragCoord) {
vec2 uv = fragCoord.xy / iResolution.xy;
if (isClose(uv.x, 0.5)) {
fragColor = vec4(0.5);
}
else if (uv.x < 0.5) {
uv += vec2(0.4, 0.3);
uv -= vec2(0.5);
uv *= vec2(3.0, 1.0);
uv += vec2(0.5);
//uv += vec2(0.5, 0.0);
plot(fragColor, uv);
}
else {
applyBias(fragColor, fragCoord);
}
} | mit | [
2173,
2238,
2267,
2267,
2313
] | [
[
44,
360,
390,
390,
461
],
[
544,
544,
568,
568,
603
],
[
604,
604,
636,
636,
663
],
[
664,
664,
708,
708,
1985
],
[
1989,
2054,
2073,
2073,
2171
],
[
2173,
2238,
2267,
2267,
2313
],
[
2316,
2316,
2371,
2371,
2455
],
[
2457,
2457,
2512,
2512,
2893
]
] | // creates white noise in the range 0..1 including 0 including 1
| float rand_inclusive(vec2 p){ |
return clamp(rand(p)*1.005, 0.0, 1.0);
} | // creates white noise in the range 0..1 including 0 including 1
float rand_inclusive(vec2 p){ | 1 | 1 |
Msc3zN | sagarpatel | 2015-11-25T11:26:57 | // CC0 1.0
// @sagzorz
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// output --> smoothed/blended output
float smin( float d1, float d2)
{
float k = 0.6521;
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input d1 --> distance of object 1
// input d2 --> distance of object 2
// output --> blended object
float opBlend( float d1, float d2)
{
return smin( d1, d2 );
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
vec2 map(vec3 p)
{
// results container
vec2 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sP = p - (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec2 sphere_1 = vec2( sdSphere(sP,sR), 1.0 );
// torus 1
vec2 torusSpecs = vec2(1.6, 0.613333);
float twistSpeed = 0.35;
float twistPower = 5.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec2 torus_1 = vec2(ddc * sdTorus(distortedP, torusSpecs), 2.0);
// combine and blend objects
res = opU( sphere_1, torus_1 );
res.x = opBlend( sphere_1.x, torus_1.x );
//res.x = torus_1.x;
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// output is vec2 where
// .x = distance travelled by ray
// .y = hit object's ID
//
vec2 castRay( vec3 ro, vec3 rd)
{
// variables used to control the marching process
const int maxMarchCount = 300;
float maxRayDistance = 20.0;
float minPrecisionCheck = 0.001;
float t = 0.0; // travelled distance by ray
float id = -1.0; // object ID, default of -1 means background
for(int i = 0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec2 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
id = res.y;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
id = -1.0;
return vec2(t, id);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// output --> pixel color
vec3 render(vec3 ro, vec3 rd)
{
vec3 bkgColor = vec3(0.75);
vec3 light = normalize( vec3(1.0, 4.0, 3.0) );
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 ambientLightColor = vec3( 0.3 , 0.1, 0.2 );
vec2 res = castRay(ro, rd);
float t = res.x;
float id = res.y;
// hard set pixel value if its a background one
if(id == -1.0)
return bkgColor;
else
{
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
vec3 objectColor = vec3(1);
if(id == 1.0)
objectColor = objectColor_1;
else if(id == 2.0)
objectColor = objectColor_2;
else if(id == 3.0)
objectColor = objectColor_3;
float surf = clamp(dot(normal, light), 0.0, 1.0);
vec3 pixelColor = objectColor * surf + ambientLightColor;
return pixelColor;
}
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.xy;
// get pixel (range from -1.0 to 1.0)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// camera stuff
float camOrbitSpeed = 0.5;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLength = 2.0;
vec3 rd = camMatrix * normalize( vec3(p.xy,2.0) );
vec3 col = render(camPos,rd);
fragColor = vec4(col,1.0);
}
| cc0-1.0 | [
1343,
1478,
1511,
1511,
1539
] | [
[
1343,
1478,
1511,
1511,
1539
],
[
1541,
2768,
2797,
2797,
3021
],
[
3171,
3586,
3617,
3617,
3740
],
[
3862,
4109,
4142,
4142,
4261
],
[
4263,
4440,
4476,
4476,
4509
],
[
4511,
4750,
4794,
4794,
4926
],
[
4928,
5100,
5128,
5128,
5198
],
[
5200,
5404,
5422,
5447,
6598
],
[
6600,
6822,
6855,
6906,
7900
],
[
8192,
8192,
8222,
8222,
8548
],
[
8550,
8737,
8768,
8768,
9770
],
[
9772,
10011,
10076,
10076,
10270
],
[
10272,
10272,
10329,
10329,
11140
]
] | // ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
| float sdSphere(vec3 p, float r)
{ |
return length(p) - r;
} | // ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{ | 18 | 57 |
Msc3zN | sagarpatel | 2015-11-25T11:26:57 | // CC0 1.0
// @sagzorz
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// output --> smoothed/blended output
float smin( float d1, float d2)
{
float k = 0.6521;
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input d1 --> distance of object 1
// input d2 --> distance of object 2
// output --> blended object
float opBlend( float d1, float d2)
{
return smin( d1, d2 );
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
vec2 map(vec3 p)
{
// results container
vec2 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sP = p - (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec2 sphere_1 = vec2( sdSphere(sP,sR), 1.0 );
// torus 1
vec2 torusSpecs = vec2(1.6, 0.613333);
float twistSpeed = 0.35;
float twistPower = 5.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec2 torus_1 = vec2(ddc * sdTorus(distortedP, torusSpecs), 2.0);
// combine and blend objects
res = opU( sphere_1, torus_1 );
res.x = opBlend( sphere_1.x, torus_1.x );
//res.x = torus_1.x;
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// output is vec2 where
// .x = distance travelled by ray
// .y = hit object's ID
//
vec2 castRay( vec3 ro, vec3 rd)
{
// variables used to control the marching process
const int maxMarchCount = 300;
float maxRayDistance = 20.0;
float minPrecisionCheck = 0.001;
float t = 0.0; // travelled distance by ray
float id = -1.0; // object ID, default of -1 means background
for(int i = 0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec2 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
id = res.y;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
id = -1.0;
return vec2(t, id);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// output --> pixel color
vec3 render(vec3 ro, vec3 rd)
{
vec3 bkgColor = vec3(0.75);
vec3 light = normalize( vec3(1.0, 4.0, 3.0) );
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 ambientLightColor = vec3( 0.3 , 0.1, 0.2 );
vec2 res = castRay(ro, rd);
float t = res.x;
float id = res.y;
// hard set pixel value if its a background one
if(id == -1.0)
return bkgColor;
else
{
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
vec3 objectColor = vec3(1);
if(id == 1.0)
objectColor = objectColor_1;
else if(id == 2.0)
objectColor = objectColor_2;
else if(id == 3.0)
objectColor = objectColor_3;
float surf = clamp(dot(normal, light), 0.0, 1.0);
vec3 pixelColor = objectColor * surf + ambientLightColor;
return pixelColor;
}
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.xy;
// get pixel (range from -1.0 to 1.0)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// camera stuff
float camOrbitSpeed = 0.5;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLength = 2.0;
vec3 rd = camMatrix * normalize( vec3(p.xy,2.0) );
vec3 col = render(camPos,rd);
fragColor = vec4(col,1.0);
}
| cc0-1.0 | [
3171,
3586,
3617,
3617,
3740
] | [
[
1343,
1478,
1511,
1511,
1539
],
[
1541,
2768,
2797,
2797,
3021
],
[
3171,
3586,
3617,
3617,
3740
],
[
3862,
4109,
4142,
4142,
4261
],
[
4263,
4440,
4476,
4476,
4509
],
[
4511,
4750,
4794,
4794,
4926
],
[
4928,
5100,
5128,
5128,
5198
],
[
5200,
5404,
5422,
5447,
6598
],
[
6600,
6822,
6855,
6906,
7900
],
[
8192,
8192,
8222,
8222,
8548
],
[
8550,
8737,
8768,
8768,
9770
],
[
9772,
10011,
10076,
10076,
10270
],
[
10272,
10272,
10329,
10329,
11140
]
] | // ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
| float sdTorus(vec3 p, vec2 t)
{ |
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
} | // ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{ | 3 | 16 |
Msc3zN | sagarpatel | 2015-11-25T11:26:57 | // CC0 1.0
// @sagzorz
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// output --> smoothed/blended output
float smin( float d1, float d2)
{
float k = 0.6521;
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input d1 --> distance of object 1
// input d2 --> distance of object 2
// output --> blended object
float opBlend( float d1, float d2)
{
return smin( d1, d2 );
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
vec2 map(vec3 p)
{
// results container
vec2 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sP = p - (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec2 sphere_1 = vec2( sdSphere(sP,sR), 1.0 );
// torus 1
vec2 torusSpecs = vec2(1.6, 0.613333);
float twistSpeed = 0.35;
float twistPower = 5.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec2 torus_1 = vec2(ddc * sdTorus(distortedP, torusSpecs), 2.0);
// combine and blend objects
res = opU( sphere_1, torus_1 );
res.x = opBlend( sphere_1.x, torus_1.x );
//res.x = torus_1.x;
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// output is vec2 where
// .x = distance travelled by ray
// .y = hit object's ID
//
vec2 castRay( vec3 ro, vec3 rd)
{
// variables used to control the marching process
const int maxMarchCount = 300;
float maxRayDistance = 20.0;
float minPrecisionCheck = 0.001;
float t = 0.0; // travelled distance by ray
float id = -1.0; // object ID, default of -1 means background
for(int i = 0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec2 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
id = res.y;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
id = -1.0;
return vec2(t, id);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// output --> pixel color
vec3 render(vec3 ro, vec3 rd)
{
vec3 bkgColor = vec3(0.75);
vec3 light = normalize( vec3(1.0, 4.0, 3.0) );
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 ambientLightColor = vec3( 0.3 , 0.1, 0.2 );
vec2 res = castRay(ro, rd);
float t = res.x;
float id = res.y;
// hard set pixel value if its a background one
if(id == -1.0)
return bkgColor;
else
{
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
vec3 objectColor = vec3(1);
if(id == 1.0)
objectColor = objectColor_1;
else if(id == 2.0)
objectColor = objectColor_2;
else if(id == 3.0)
objectColor = objectColor_3;
float surf = clamp(dot(normal, light), 0.0, 1.0);
vec3 pixelColor = objectColor * surf + ambientLightColor;
return pixelColor;
}
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.xy;
// get pixel (range from -1.0 to 1.0)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// camera stuff
float camOrbitSpeed = 0.5;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLength = 2.0;
vec3 rd = camMatrix * normalize( vec3(p.xy,2.0) );
vec3 col = render(camPos,rd);
fragColor = vec4(col,1.0);
}
| cc0-1.0 | [
3862,
4109,
4142,
4142,
4261
] | [
[
1343,
1478,
1511,
1511,
1539
],
[
1541,
2768,
2797,
2797,
3021
],
[
3171,
3586,
3617,
3617,
3740
],
[
3862,
4109,
4142,
4142,
4261
],
[
4263,
4440,
4476,
4476,
4509
],
[
4511,
4750,
4794,
4794,
4926
],
[
4928,
5100,
5128,
5128,
5198
],
[
5200,
5404,
5422,
5447,
6598
],
[
6600,
6822,
6855,
6906,
7900
],
[
8192,
8192,
8222,
8222,
8548
],
[
8550,
8737,
8768,
8768,
9770
],
[
9772,
10011,
10076,
10076,
10270
],
[
10272,
10272,
10329,
10329,
11140
]
] | // ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// output --> smoothed/blended output
| float smin( float d1, float d2)
{ |
float k = 0.6521;
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
} | // ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// output --> smoothed/blended output
float smin( float d1, float d2)
{ | 1 | 2 |
Msc3zN | sagarpatel | 2015-11-25T11:26:57 | // CC0 1.0
// @sagzorz
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// output --> smoothed/blended output
float smin( float d1, float d2)
{
float k = 0.6521;
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input d1 --> distance of object 1
// input d2 --> distance of object 2
// output --> blended object
float opBlend( float d1, float d2)
{
return smin( d1, d2 );
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
vec2 map(vec3 p)
{
// results container
vec2 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sP = p - (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec2 sphere_1 = vec2( sdSphere(sP,sR), 1.0 );
// torus 1
vec2 torusSpecs = vec2(1.6, 0.613333);
float twistSpeed = 0.35;
float twistPower = 5.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec2 torus_1 = vec2(ddc * sdTorus(distortedP, torusSpecs), 2.0);
// combine and blend objects
res = opU( sphere_1, torus_1 );
res.x = opBlend( sphere_1.x, torus_1.x );
//res.x = torus_1.x;
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// output is vec2 where
// .x = distance travelled by ray
// .y = hit object's ID
//
vec2 castRay( vec3 ro, vec3 rd)
{
// variables used to control the marching process
const int maxMarchCount = 300;
float maxRayDistance = 20.0;
float minPrecisionCheck = 0.001;
float t = 0.0; // travelled distance by ray
float id = -1.0; // object ID, default of -1 means background
for(int i = 0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec2 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
id = res.y;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
id = -1.0;
return vec2(t, id);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// output --> pixel color
vec3 render(vec3 ro, vec3 rd)
{
vec3 bkgColor = vec3(0.75);
vec3 light = normalize( vec3(1.0, 4.0, 3.0) );
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 ambientLightColor = vec3( 0.3 , 0.1, 0.2 );
vec2 res = castRay(ro, rd);
float t = res.x;
float id = res.y;
// hard set pixel value if its a background one
if(id == -1.0)
return bkgColor;
else
{
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
vec3 objectColor = vec3(1);
if(id == 1.0)
objectColor = objectColor_1;
else if(id == 2.0)
objectColor = objectColor_2;
else if(id == 3.0)
objectColor = objectColor_3;
float surf = clamp(dot(normal, light), 0.0, 1.0);
vec3 pixelColor = objectColor * surf + ambientLightColor;
return pixelColor;
}
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.xy;
// get pixel (range from -1.0 to 1.0)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// camera stuff
float camOrbitSpeed = 0.5;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLength = 2.0;
vec3 rd = camMatrix * normalize( vec3(p.xy,2.0) );
vec3 col = render(camPos,rd);
fragColor = vec4(col,1.0);
}
| cc0-1.0 | [
4263,
4440,
4476,
4476,
4509
] | [
[
1343,
1478,
1511,
1511,
1539
],
[
1541,
2768,
2797,
2797,
3021
],
[
3171,
3586,
3617,
3617,
3740
],
[
3862,
4109,
4142,
4142,
4261
],
[
4263,
4440,
4476,
4476,
4509
],
[
4511,
4750,
4794,
4794,
4926
],
[
4928,
5100,
5128,
5128,
5198
],
[
5200,
5404,
5422,
5447,
6598
],
[
6600,
6822,
6855,
6906,
7900
],
[
8192,
8192,
8222,
8222,
8548
],
[
8550,
8737,
8768,
8768,
9770
],
[
9772,
10011,
10076,
10076,
10270
],
[
10272,
10272,
10329,
10329,
11140
]
] | // ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input d1 --> distance of object 1
// input d2 --> distance of object 2
// output --> blended object
| float opBlend( float d1, float d2)
{ |
return smin( d1, d2 );
} | // ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input d1 --> distance of object 1
// input d2 --> distance of object 2
// output --> blended object
float opBlend( float d1, float d2)
{ | 1 | 4 |
Msc3zN | sagarpatel | 2015-11-25T11:26:57 | // CC0 1.0
// @sagzorz
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// output --> smoothed/blended output
float smin( float d1, float d2)
{
float k = 0.6521;
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input d1 --> distance of object 1
// input d2 --> distance of object 2
// output --> blended object
float opBlend( float d1, float d2)
{
return smin( d1, d2 );
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
vec2 map(vec3 p)
{
// results container
vec2 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sP = p - (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec2 sphere_1 = vec2( sdSphere(sP,sR), 1.0 );
// torus 1
vec2 torusSpecs = vec2(1.6, 0.613333);
float twistSpeed = 0.35;
float twistPower = 5.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec2 torus_1 = vec2(ddc * sdTorus(distortedP, torusSpecs), 2.0);
// combine and blend objects
res = opU( sphere_1, torus_1 );
res.x = opBlend( sphere_1.x, torus_1.x );
//res.x = torus_1.x;
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// output is vec2 where
// .x = distance travelled by ray
// .y = hit object's ID
//
vec2 castRay( vec3 ro, vec3 rd)
{
// variables used to control the marching process
const int maxMarchCount = 300;
float maxRayDistance = 20.0;
float minPrecisionCheck = 0.001;
float t = 0.0; // travelled distance by ray
float id = -1.0; // object ID, default of -1 means background
for(int i = 0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec2 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
id = res.y;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
id = -1.0;
return vec2(t, id);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// output --> pixel color
vec3 render(vec3 ro, vec3 rd)
{
vec3 bkgColor = vec3(0.75);
vec3 light = normalize( vec3(1.0, 4.0, 3.0) );
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 ambientLightColor = vec3( 0.3 , 0.1, 0.2 );
vec2 res = castRay(ro, rd);
float t = res.x;
float id = res.y;
// hard set pixel value if its a background one
if(id == -1.0)
return bkgColor;
else
{
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
vec3 objectColor = vec3(1);
if(id == 1.0)
objectColor = objectColor_1;
else if(id == 2.0)
objectColor = objectColor_2;
else if(id == 3.0)
objectColor = objectColor_3;
float surf = clamp(dot(normal, light), 0.0, 1.0);
vec3 pixelColor = objectColor * surf + ambientLightColor;
return pixelColor;
}
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.xy;
// get pixel (range from -1.0 to 1.0)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// camera stuff
float camOrbitSpeed = 0.5;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLength = 2.0;
vec3 rd = camMatrix * normalize( vec3(p.xy,2.0) );
vec3 col = render(camPos,rd);
fragColor = vec4(col,1.0);
}
| cc0-1.0 | [
4511,
4750,
4794,
4794,
4926
] | [
[
1343,
1478,
1511,
1511,
1539
],
[
1541,
2768,
2797,
2797,
3021
],
[
3171,
3586,
3617,
3617,
3740
],
[
3862,
4109,
4142,
4142,
4261
],
[
4263,
4440,
4476,
4476,
4509
],
[
4511,
4750,
4794,
4794,
4926
],
[
4928,
5100,
5128,
5128,
5198
],
[
5200,
5404,
5422,
5447,
6598
],
[
6600,
6822,
6855,
6906,
7900
],
[
8192,
8192,
8222,
8222,
8548
],
[
8550,
8737,
8768,
8768,
9770
],
[
9772,
10011,
10076,
10076,
10270
],
[
10272,
10272,
10329,
10329,
11140
]
] | // ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
| vec3 opTwist( vec3 p, float t, float yaw )
{ |
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
} | // ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{ | 3 | 3 |
Msc3zN | sagarpatel | 2015-11-25T11:26:57 | // CC0 1.0
// @sagzorz
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// output --> smoothed/blended output
float smin( float d1, float d2)
{
float k = 0.6521;
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input d1 --> distance of object 1
// input d2 --> distance of object 2
// output --> blended object
float opBlend( float d1, float d2)
{
return smin( d1, d2 );
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
vec2 map(vec3 p)
{
// results container
vec2 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sP = p - (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec2 sphere_1 = vec2( sdSphere(sP,sR), 1.0 );
// torus 1
vec2 torusSpecs = vec2(1.6, 0.613333);
float twistSpeed = 0.35;
float twistPower = 5.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec2 torus_1 = vec2(ddc * sdTorus(distortedP, torusSpecs), 2.0);
// combine and blend objects
res = opU( sphere_1, torus_1 );
res.x = opBlend( sphere_1.x, torus_1.x );
//res.x = torus_1.x;
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// output is vec2 where
// .x = distance travelled by ray
// .y = hit object's ID
//
vec2 castRay( vec3 ro, vec3 rd)
{
// variables used to control the marching process
const int maxMarchCount = 300;
float maxRayDistance = 20.0;
float minPrecisionCheck = 0.001;
float t = 0.0; // travelled distance by ray
float id = -1.0; // object ID, default of -1 means background
for(int i = 0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec2 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
id = res.y;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
id = -1.0;
return vec2(t, id);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// output --> pixel color
vec3 render(vec3 ro, vec3 rd)
{
vec3 bkgColor = vec3(0.75);
vec3 light = normalize( vec3(1.0, 4.0, 3.0) );
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 ambientLightColor = vec3( 0.3 , 0.1, 0.2 );
vec2 res = castRay(ro, rd);
float t = res.x;
float id = res.y;
// hard set pixel value if its a background one
if(id == -1.0)
return bkgColor;
else
{
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
vec3 objectColor = vec3(1);
if(id == 1.0)
objectColor = objectColor_1;
else if(id == 2.0)
objectColor = objectColor_2;
else if(id == 3.0)
objectColor = objectColor_3;
float surf = clamp(dot(normal, light), 0.0, 1.0);
vec3 pixelColor = objectColor * surf + ambientLightColor;
return pixelColor;
}
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.xy;
// get pixel (range from -1.0 to 1.0)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// camera stuff
float camOrbitSpeed = 0.5;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLength = 2.0;
vec3 rd = camMatrix * normalize( vec3(p.xy,2.0) );
vec3 col = render(camPos,rd);
fragColor = vec4(col,1.0);
}
| cc0-1.0 | [
4928,
5100,
5128,
5128,
5198
] | [
[
1343,
1478,
1511,
1511,
1539
],
[
1541,
2768,
2797,
2797,
3021
],
[
3171,
3586,
3617,
3617,
3740
],
[
3862,
4109,
4142,
4142,
4261
],
[
4263,
4440,
4476,
4476,
4509
],
[
4511,
4750,
4794,
4794,
4926
],
[
4928,
5100,
5128,
5128,
5198
],
[
5200,
5404,
5422,
5447,
6598
],
[
6600,
6822,
6855,
6906,
7900
],
[
8192,
8192,
8222,
8222,
8548
],
[
8550,
8737,
8768,
8768,
9770
],
[
9772,
10011,
10076,
10076,
10270
],
[
10272,
10272,
10329,
10329,
11140
]
] | // ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
| vec2 opU(vec2 o1, vec2 o2)
{ |
if(o1.x < o2.x)
return o1;
else
return o2;
} | // ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{ | 3 | 3 |
Msc3zN | sagarpatel | 2015-11-25T11:26:57 | // CC0 1.0
// @sagzorz
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// output --> smoothed/blended output
float smin( float d1, float d2)
{
float k = 0.6521;
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input d1 --> distance of object 1
// input d2 --> distance of object 2
// output --> blended object
float opBlend( float d1, float d2)
{
return smin( d1, d2 );
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
vec2 map(vec3 p)
{
// results container
vec2 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sP = p - (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec2 sphere_1 = vec2( sdSphere(sP,sR), 1.0 );
// torus 1
vec2 torusSpecs = vec2(1.6, 0.613333);
float twistSpeed = 0.35;
float twistPower = 5.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec2 torus_1 = vec2(ddc * sdTorus(distortedP, torusSpecs), 2.0);
// combine and blend objects
res = opU( sphere_1, torus_1 );
res.x = opBlend( sphere_1.x, torus_1.x );
//res.x = torus_1.x;
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// output is vec2 where
// .x = distance travelled by ray
// .y = hit object's ID
//
vec2 castRay( vec3 ro, vec3 rd)
{
// variables used to control the marching process
const int maxMarchCount = 300;
float maxRayDistance = 20.0;
float minPrecisionCheck = 0.001;
float t = 0.0; // travelled distance by ray
float id = -1.0; // object ID, default of -1 means background
for(int i = 0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec2 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
id = res.y;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
id = -1.0;
return vec2(t, id);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// output --> pixel color
vec3 render(vec3 ro, vec3 rd)
{
vec3 bkgColor = vec3(0.75);
vec3 light = normalize( vec3(1.0, 4.0, 3.0) );
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 ambientLightColor = vec3( 0.3 , 0.1, 0.2 );
vec2 res = castRay(ro, rd);
float t = res.x;
float id = res.y;
// hard set pixel value if its a background one
if(id == -1.0)
return bkgColor;
else
{
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
vec3 objectColor = vec3(1);
if(id == 1.0)
objectColor = objectColor_1;
else if(id == 2.0)
objectColor = objectColor_2;
else if(id == 3.0)
objectColor = objectColor_3;
float surf = clamp(dot(normal, light), 0.0, 1.0);
vec3 pixelColor = objectColor * surf + ambientLightColor;
return pixelColor;
}
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.xy;
// get pixel (range from -1.0 to 1.0)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// camera stuff
float camOrbitSpeed = 0.5;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLength = 2.0;
vec3 rd = camMatrix * normalize( vec3(p.xy,2.0) );
vec3 col = render(camPos,rd);
fragColor = vec4(col,1.0);
}
| cc0-1.0 | [
5200,
5404,
5422,
5447,
6598
] | [
[
1343,
1478,
1511,
1511,
1539
],
[
1541,
2768,
2797,
2797,
3021
],
[
3171,
3586,
3617,
3617,
3740
],
[
3862,
4109,
4142,
4142,
4261
],
[
4263,
4440,
4476,
4476,
4509
],
[
4511,
4750,
4794,
4794,
4926
],
[
4928,
5100,
5128,
5128,
5198
],
[
5200,
5404,
5422,
5447,
6598
],
[
6600,
6822,
6855,
6906,
7900
],
[
8192,
8192,
8222,
8222,
8548
],
[
8550,
8737,
8768,
8768,
9770
],
[
9772,
10011,
10076,
10076,
10270
],
[
10272,
10272,
10329,
10329,
11140
]
] | // ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
| vec2 map(vec3 p)
{ |
vec2 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sP = p - (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec2 sphere_1 = vec2( sdSphere(sP,sR), 1.0 );
// torus 1
vec2 torusSpecs = vec2(1.6, 0.613333);
float twistSpeed = 0.35;
float twistPower = 5.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec2 torus_1 = vec2(ddc * sdTorus(distortedP, torusSpecs), 2.0);
// combine and blend objects
res = opU( sphere_1, torus_1 );
res.x = opBlend( sphere_1.x, torus_1.x );
//res.x = torus_1.x;
return res;
} | // ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
vec2 map(vec3 p)
{ | 1 | 113 |
Msc3zN | sagarpatel | 2015-11-25T11:26:57 | // CC0 1.0
// @sagzorz
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// output --> smoothed/blended output
float smin( float d1, float d2)
{
float k = 0.6521;
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input d1 --> distance of object 1
// input d2 --> distance of object 2
// output --> blended object
float opBlend( float d1, float d2)
{
return smin( d1, d2 );
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
vec2 map(vec3 p)
{
// results container
vec2 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sP = p - (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec2 sphere_1 = vec2( sdSphere(sP,sR), 1.0 );
// torus 1
vec2 torusSpecs = vec2(1.6, 0.613333);
float twistSpeed = 0.35;
float twistPower = 5.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec2 torus_1 = vec2(ddc * sdTorus(distortedP, torusSpecs), 2.0);
// combine and blend objects
res = opU( sphere_1, torus_1 );
res.x = opBlend( sphere_1.x, torus_1.x );
//res.x = torus_1.x;
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// output is vec2 where
// .x = distance travelled by ray
// .y = hit object's ID
//
vec2 castRay( vec3 ro, vec3 rd)
{
// variables used to control the marching process
const int maxMarchCount = 300;
float maxRayDistance = 20.0;
float minPrecisionCheck = 0.001;
float t = 0.0; // travelled distance by ray
float id = -1.0; // object ID, default of -1 means background
for(int i = 0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec2 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
id = res.y;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
id = -1.0;
return vec2(t, id);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// output --> pixel color
vec3 render(vec3 ro, vec3 rd)
{
vec3 bkgColor = vec3(0.75);
vec3 light = normalize( vec3(1.0, 4.0, 3.0) );
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 ambientLightColor = vec3( 0.3 , 0.1, 0.2 );
vec2 res = castRay(ro, rd);
float t = res.x;
float id = res.y;
// hard set pixel value if its a background one
if(id == -1.0)
return bkgColor;
else
{
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
vec3 objectColor = vec3(1);
if(id == 1.0)
objectColor = objectColor_1;
else if(id == 2.0)
objectColor = objectColor_2;
else if(id == 3.0)
objectColor = objectColor_3;
float surf = clamp(dot(normal, light), 0.0, 1.0);
vec3 pixelColor = objectColor * surf + ambientLightColor;
return pixelColor;
}
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.xy;
// get pixel (range from -1.0 to 1.0)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// camera stuff
float camOrbitSpeed = 0.5;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLength = 2.0;
vec3 rd = camMatrix * normalize( vec3(p.xy,2.0) );
vec3 col = render(camPos,rd);
fragColor = vec4(col,1.0);
}
| cc0-1.0 | [
6600,
6822,
6855,
6906,
7900
] | [
[
1343,
1478,
1511,
1511,
1539
],
[
1541,
2768,
2797,
2797,
3021
],
[
3171,
3586,
3617,
3617,
3740
],
[
3862,
4109,
4142,
4142,
4261
],
[
4263,
4440,
4476,
4476,
4509
],
[
4511,
4750,
4794,
4794,
4926
],
[
4928,
5100,
5128,
5128,
5198
],
[
5200,
5404,
5422,
5447,
6598
],
[
6600,
6822,
6855,
6906,
7900
],
[
8192,
8192,
8222,
8222,
8548
],
[
8550,
8737,
8768,
8768,
9770
],
[
9772,
10011,
10076,
10076,
10270
],
[
10272,
10272,
10329,
10329,
11140
]
] | // ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// output is vec2 where
// .x = distance travelled by ray
// .y = hit object's ID
//
| vec2 castRay( vec3 ro, vec3 rd)
{ |
const int maxMarchCount = 300;
float maxRayDistance = 20.0;
float minPrecisionCheck = 0.001;
float t = 0.0; // travelled distance by ray
float id = -1.0; // object ID, default of -1 means background
for(int i = 0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec2 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
id = res.y;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
id = -1.0;
return vec2(t, id);
} | // ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// output is vec2 where
// .x = distance travelled by ray
// .y = hit object's ID
//
vec2 castRay( vec3 ro, vec3 rd)
{ | 1 | 1 |
Msc3zN | sagarpatel | 2015-11-25T11:26:57 | // CC0 1.0
// @sagzorz
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// output --> smoothed/blended output
float smin( float d1, float d2)
{
float k = 0.6521;
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input d1 --> distance of object 1
// input d2 --> distance of object 2
// output --> blended object
float opBlend( float d1, float d2)
{
return smin( d1, d2 );
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
vec2 map(vec3 p)
{
// results container
vec2 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sP = p - (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec2 sphere_1 = vec2( sdSphere(sP,sR), 1.0 );
// torus 1
vec2 torusSpecs = vec2(1.6, 0.613333);
float twistSpeed = 0.35;
float twistPower = 5.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec2 torus_1 = vec2(ddc * sdTorus(distortedP, torusSpecs), 2.0);
// combine and blend objects
res = opU( sphere_1, torus_1 );
res.x = opBlend( sphere_1.x, torus_1.x );
//res.x = torus_1.x;
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// output is vec2 where
// .x = distance travelled by ray
// .y = hit object's ID
//
vec2 castRay( vec3 ro, vec3 rd)
{
// variables used to control the marching process
const int maxMarchCount = 300;
float maxRayDistance = 20.0;
float minPrecisionCheck = 0.001;
float t = 0.0; // travelled distance by ray
float id = -1.0; // object ID, default of -1 means background
for(int i = 0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec2 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
id = res.y;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
id = -1.0;
return vec2(t, id);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// output --> pixel color
vec3 render(vec3 ro, vec3 rd)
{
vec3 bkgColor = vec3(0.75);
vec3 light = normalize( vec3(1.0, 4.0, 3.0) );
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 ambientLightColor = vec3( 0.3 , 0.1, 0.2 );
vec2 res = castRay(ro, rd);
float t = res.x;
float id = res.y;
// hard set pixel value if its a background one
if(id == -1.0)
return bkgColor;
else
{
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
vec3 objectColor = vec3(1);
if(id == 1.0)
objectColor = objectColor_1;
else if(id == 2.0)
objectColor = objectColor_2;
else if(id == 3.0)
objectColor = objectColor_3;
float surf = clamp(dot(normal, light), 0.0, 1.0);
vec3 pixelColor = objectColor * surf + ambientLightColor;
return pixelColor;
}
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.xy;
// get pixel (range from -1.0 to 1.0)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// camera stuff
float camOrbitSpeed = 0.5;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLength = 2.0;
vec3 rd = camMatrix * normalize( vec3(p.xy,2.0) );
vec3 col = render(camPos,rd);
fragColor = vec4(col,1.0);
}
| cc0-1.0 | [
8550,
8737,
8768,
8768,
9770
] | [
[
1343,
1478,
1511,
1511,
1539
],
[
1541,
2768,
2797,
2797,
3021
],
[
3171,
3586,
3617,
3617,
3740
],
[
3862,
4109,
4142,
4142,
4261
],
[
4263,
4440,
4476,
4476,
4509
],
[
4511,
4750,
4794,
4794,
4926
],
[
4928,
5100,
5128,
5128,
5198
],
[
5200,
5404,
5422,
5447,
6598
],
[
6600,
6822,
6855,
6906,
7900
],
[
8192,
8192,
8222,
8222,
8548
],
[
8550,
8737,
8768,
8768,
9770
],
[
9772,
10011,
10076,
10076,
10270
],
[
10272,
10272,
10329,
10329,
11140
]
] | // ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// output --> pixel color
| vec3 render(vec3 ro, vec3 rd)
{ |
vec3 bkgColor = vec3(0.75);
vec3 light = normalize( vec3(1.0, 4.0, 3.0) );
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 ambientLightColor = vec3( 0.3 , 0.1, 0.2 );
vec2 res = castRay(ro, rd);
float t = res.x;
float id = res.y;
// hard set pixel value if its a background one
if(id == -1.0)
return bkgColor;
else
{
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
vec3 objectColor = vec3(1);
if(id == 1.0)
objectColor = objectColor_1;
else if(id == 2.0)
objectColor = objectColor_2;
else if(id == 3.0)
objectColor = objectColor_3;
float surf = clamp(dot(normal, light), 0.0, 1.0);
vec3 pixelColor = objectColor * surf + ambientLightColor;
return pixelColor;
}
} | // ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// output --> pixel color
vec3 render(vec3 ro, vec3 rd)
{ | 1 | 16 |
Msc3zN | sagarpatel | 2015-11-25T11:26:57 | // CC0 1.0
// @sagzorz
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// output --> smoothed/blended output
float smin( float d1, float d2)
{
float k = 0.6521;
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input d1 --> distance of object 1
// input d2 --> distance of object 2
// output --> blended object
float opBlend( float d1, float d2)
{
return smin( d1, d2 );
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
vec2 map(vec3 p)
{
// results container
vec2 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sP = p - (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec2 sphere_1 = vec2( sdSphere(sP,sR), 1.0 );
// torus 1
vec2 torusSpecs = vec2(1.6, 0.613333);
float twistSpeed = 0.35;
float twistPower = 5.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec2 torus_1 = vec2(ddc * sdTorus(distortedP, torusSpecs), 2.0);
// combine and blend objects
res = opU( sphere_1, torus_1 );
res.x = opBlend( sphere_1.x, torus_1.x );
//res.x = torus_1.x;
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// output is vec2 where
// .x = distance travelled by ray
// .y = hit object's ID
//
vec2 castRay( vec3 ro, vec3 rd)
{
// variables used to control the marching process
const int maxMarchCount = 300;
float maxRayDistance = 20.0;
float minPrecisionCheck = 0.001;
float t = 0.0; // travelled distance by ray
float id = -1.0; // object ID, default of -1 means background
for(int i = 0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec2 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
id = res.y;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
id = -1.0;
return vec2(t, id);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// output --> pixel color
vec3 render(vec3 ro, vec3 rd)
{
vec3 bkgColor = vec3(0.75);
vec3 light = normalize( vec3(1.0, 4.0, 3.0) );
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 ambientLightColor = vec3( 0.3 , 0.1, 0.2 );
vec2 res = castRay(ro, rd);
float t = res.x;
float id = res.y;
// hard set pixel value if its a background one
if(id == -1.0)
return bkgColor;
else
{
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
vec3 objectColor = vec3(1);
if(id == 1.0)
objectColor = objectColor_1;
else if(id == 2.0)
objectColor = objectColor_2;
else if(id == 3.0)
objectColor = objectColor_3;
float surf = clamp(dot(normal, light), 0.0, 1.0);
vec3 pixelColor = objectColor * surf + ambientLightColor;
return pixelColor;
}
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.xy;
// get pixel (range from -1.0 to 1.0)
vec2 p = ( -iResolution.xy + 2.0 * fragCoord.xy ) / iResolution.y;
// camera stuff
float camOrbitSpeed = 0.5;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLength = 2.0;
vec3 rd = camMatrix * normalize( vec3(p.xy,2.0) );
vec3 col = render(camPos,rd);
fragColor = vec4(col,1.0);
}
| cc0-1.0 | [
9772,
10011,
10076,
10076,
10270
] | [
[
1343,
1478,
1511,
1511,
1539
],
[
1541,
2768,
2797,
2797,
3021
],
[
3171,
3586,
3617,
3617,
3740
],
[
3862,
4109,
4142,
4142,
4261
],
[
4263,
4440,
4476,
4476,
4509
],
[
4511,
4750,
4794,
4794,
4926
],
[
4928,
5100,
5128,
5128,
5198
],
[
5200,
5404,
5422,
5447,
6598
],
[
6600,
6822,
6855,
6906,
7900
],
[
8192,
8192,
8222,
8222,
8548
],
[
8550,
8737,
8768,
8768,
9770
],
[
9772,
10011,
10076,
10076,
10270
],
[
10272,
10272,
10329,
10329,
11140
]
] | // ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
| mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{ |
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
} | // ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{ | 1 | 3 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
1507,
1728,
1757,
1757,
2660
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
| vec3 accessColors(float id)
{ |
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
} | // ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{ | 2 | 2 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
4491,
4907,
4938,
4938,
5061
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
| float sdTorus(vec3 p, vec2 t)
{ |
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
} | // ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{ | 3 | 16 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
5182,
5395,
5418,
5418,
5436
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
| float sdPlane(vec3 p)
{ |
return p.y;
} | // ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{ | 7 | 13 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
5438,
5713,
5755,
5755,
5856
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
| float smin( float d1, float d2, float k)
{ |
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
} | // ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{ | 2 | 2 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
5858,
6156,
6199,
6199,
6490
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
| vec4 opBlend( vec4 o1, vec4 o2, float bf)
{ |
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
} | // ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{ | 2 | 2 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
7181,
7406,
7438,
7438,
7467
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
| float opSub(float d1,float d2)
{ |
return max(d1,-d2);
} | // ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{ | 2 | 2 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
7470,
7561,
7586,
7586,
7839
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
| vec3 generateLightPos()
{ |
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
} | // ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{ | 1 | 1 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
7841,
8119,
8137,
8162,
10044
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
| vec4 map(vec3 p)
{ |
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
} | // ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{ | 1 | 31 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
10046,
10367,
10424,
10478,
11655
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
| vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{ |
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
} | // ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{ | 1 | 2 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
12559,
12842,
12886,
12886,
13601
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
| float castRay_SoftShadow(vec3 sp, vec3 lp)
{ |
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
} | // ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{ | 2 | 2 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
13603,
13806,
13857,
13857,
14317
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
| float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{ |
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
} | // ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{ | 2 | 2 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
14967,
15176,
15217,
15239,
15774
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
| vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{ |
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
} | // ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{ | 2 | 2 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
15776,
15992,
16027,
16027,
16065
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
| vec3 applyGammaCorrection(vec3 c)
{ |
return pow( c, vec3(1.0/2.2) );
} | // ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{ | 2 | 2 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
16067,
16520,
16595,
16595,
16786
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
| vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{ |
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
} | // ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{ | 2 | 2 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
16790,
17113,
17178,
17178,
17246
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
| float calculateLightAttn(float cF, float lF, float qF, float d)
{ |
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
} | // ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{ | 1 | 1 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
20154,
20326,
20375,
20375,
20689
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
| vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{ |
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
} | // ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{ | 2 | 2 |
Xs3GRM | sagarpatel | 2015-11-26T04:07:03 | // CC0 1.0
// @sagzorz
const bool isPseudoAA = false;
// Building on basics and creating helper functions
// POUET toolbox
// http://www.pouet.net/topic.php?which=7931&page=1&x=3&y=14
// NOTE: if you are new to SDFs, do @cabbibo's tutorial first!!!
//
// @cabbibo's original SDF tutorial --> https://www.shadertoy.com/view/Xl2XWt
// my original hacked up shader --> https://www.shadertoy.com/view/4d33z4
// this is a clean/from scratch re-implementation of my first shdaer/sdf,
// which was based on @cabbibo's awesome SDF tutorial
// also used functions from iq's super handy page about distance functions
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// resstructured to be closer to iq's Raymarching Primitives example
// https://www.shadertoy.com/view/Xds3zN
// NOW PROPERLY MARCHING THE RAY!
// (was using silly hack in original version to compensate for twist artifacts)
// Performs much better than old version
// the sd functions below are the same as from iq's page (link above)
// though when I wrote this version I derived from scratch as much as I could on my own
// by thinking/sketching on paper etc.
// The comments explain my interpretation of the funcs
// for all signed distance functions sd*() below,
// input p --> is ray position, where the object is at the origin (0,0,0)
// output float is distance from ray position to surface of sphere
// positive means outside of sphere
// negative means ray is inside
// 0 means its exactly on the surface
// ~~~~~~~ silly function to access array memeber
// because webgl needs const index for array acess
// TODO : FIX THIS, disgusting branching etc
// THIS IS DEPRECATED, NO LONGER NEED AN ARRAY SINCE DIRECT COL MIX NOW
vec3 accessColors(float id)
{
vec3 bkgColor = vec3(0.5,0.6,0.7);//vec3(0.75);
vec3 objectColor_1 = vec3(1.0, 0.0, 0.0);
vec3 objectColor_2 = vec3( 0.25 , 0.95 , 0.25 );
vec3 objectColor_3 = vec3(0.12, 0.12, 0.9);
vec3 objectColor_4 = vec3(0.65);
vec3 objectColor_5 = vec3(1.0,1.0,1.0);
vec3 colorsArray[6];
colorsArray[0] = bkgColor;
colorsArray[1] = objectColor_1;
colorsArray[2] = objectColor_2;
colorsArray[3] = objectColor_3;
colorsArray[4] = objectColor_4;
colorsArray[5] = objectColor_5;
if(id == -1.0)
return bkgColor;
else if(id == 1.0)
return colorsArray[1];
else if(id == 2.0)
return colorsArray[2];
else if(id == 3.0)
return colorsArray[3];
else if(id == 4.0)
return colorsArray[4];
else if(id == 5.0)
return colorsArray[5];
else
return vec3(1.0,0.0,1.0);
}
// ~~~~~~~ signed fistance fuction for sphere
// input r --> is sphere radius
// pretty simple, just compare point to radius of sphere
float sdSphere(vec3 p, float r)
{
return length(p) - r;
}
// ~~~~~~~ signed distance function for box
// input s -- > is box size vector (all postive values)
//
// the key to simply calcualting distance to surface to box is to first
// force the ray position into the first octant (all positive values)
// this massively simplifies the math and is ok since distance to surf
// on a box is the same in the - or + direction on a given axis
// simple to figure by once you sketch out 2D equivalent problem on papaer
// 2D ex: distance to box of size (2,1)
// for p of (-3,-2) == (-3, 2) == (3, -2) == (3, 2)
//
// now that all the coordinates are "normalized"/positive, its much easier,
// the next part is to figure out the diff between the box surface the and p
// a bit like the sphere function were you do p - "shape size", but
// you clamp the result to >0, done below by using max() with 0
// i'm having trouble putting this into words corretcly, but it was really easy
// to understand once I sketched out a rect and points on paper,
// that was enough for me to be able to derive the 3D version
//
// the last part is to account for is p is insde the box,
// in which case we need to return a negative value
// for that value, its a simple check of which side is the closest
float sdBox(vec3 p, vec3 s)
{
vec3 diffVec = abs(p) - s;
float surfDiff_Outter = length(max(diffVec,0.0));
float surfDiff_Inner = min( max(diffVec.z,max(diffVec.x,diffVec.y)),0.0);
return surfDiff_Outter + surfDiff_Inner;
}
/*
// Minimial IQ version
float sdBox( vec3 p, vec3 s )
{
vec3 d = abs(p) - s;
return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}
*/
// ~~~~~~~ signed distance function for torus
// input t --> torus specs where:
// t.x = torus circumference
// t.y = torus thickness
//
// think of the torus as circles wrappeed around 1 large cicle (perpendicular)
// first flatten the y axis of p (by using p.xz) and get the distance to
// the torus circumference/core/radius which is flat on the y axis
// then simply subtract the torus thickenss from that
float sdTorus(vec3 p, vec2 t)
{
float distPtoTorusCircumference = length(vec2( length(p.xz)-t.x , p.y));
return distPtoTorusCircumference - t.y;
}
/*
// IQ version
float sdTorus( vec3 p, vec2 t )
{
vec2 q = vec2(length(p.xz)-t.x,p.y);
return length(q)-t.y;
}
*/
// ~~~~~~~ signed distance function for plane
// input ps --> specs of plane
// ps.x --> size x
// ps.y --> size z
// plane extends indefinately in x and z,
// so just return height from floor (y)
float sdPlane(vec3 p)
{
return p.y;
}
// ~~~~~~~ smooth minimum function (polynomial version) from iq's page
// http://iquilezles.org/www/articles/smin/smin.htm
// input d1 --> distance value of object a
// input d1 --> distance value of object b
// input k --> blend factor
// output --> smoothed/blended output
float smin( float d1, float d2, float k)
{
float h = clamp( 0.5+0.5*(d2-d1)/k, 0.0, 1.0 );
return mix( d2, d1, h ) - k*h*(1.0-h);
}
// ~~~~~~~ distance deformation, blends 2 shapes based on their distances
// input o1 --> object 1 (dist and material color)
// input 02 --> object 2 (dist and material color)
// input bf --> blend factor
// output --> blended dist, blended material color
// TODO: FIX/IMPROVE COLOR BLENDING LOGIC
vec4 opBlend( vec4 o1, vec4 o2, float bf)
{
float distBlend = smin( o1.x, o2.x, bf);
// blend color based on prozimity to surface
float dr1 = 1.0 - clamp(o1.x,0.0,1.0);
float dr2 = 1.0 - clamp(o2.x,0.0,1.0);
vec3 dc1 = dr1 * o1.yzw;
vec3 dc2 = dr2 * o2.yzw;
return vec4(distBlend, dc1+dc2);
}
// ~~~~~~~ domain deformation, twists the shape
// input p --> original ray position
// input t --> twist scale factor
// output --> twisted ray position
//
// need more max itterations on ray march for stronger/bigger domain deformation
vec3 opTwist( vec3 p, float t, float yaw )
{
float c = cos(t * p.y + yaw);
float s = sin(t * p.y + yaw);
mat2 m = mat2(c,-s,s,c);
return vec3(m*p.xz,p.y);
}
// ~~~~~~~ do Union / combine 2 sd objects
// input vec2 --> .x is the distance, .y is the object ID
// returns the closest object (basically does a min() but we use if()
vec2 opU(vec2 o1, vec2 o2)
{
if(o1.x < o2.x)
return o1;
else
return o2;
}
// ~~~~~~~ do shape subtract, cuts d2 out of d1
// by using the negative of d2, were effectively comparing wrt to internal d
// input d1 --> object/distance 1
// input d2 --> object/distance 2
// output --> cut out distance
float opSub(float d1,float d2)
{
return max(d1,-d2);
}
// ~~~~~~~~ generates world position of point light
// output --> wolrd pos of point light
vec3 generateLightPos()
{
float lOR_X = 1.20;
float lOR_Y = 2.40;
float lOR_Z = 3.0;
float lORS = 0.65;
float lpX = lOR_X*cos(lORS*iTime);
float lpY = lOR_Y*sin(lORS*iTime);
float lpZ = lOR_Z*cos(lORS*iTime);
return vec3(lpX,abs(lpY),lpZ);
}
// ~~~~~~~ map out the world
// input p --> is ray position
// basically find the object/point closest to the ray by
// checking all the objects with respect to p
// move objects/shapes by messing with p
// outputs closest distance and blended colors for that surface as a vec4
vec4 map(vec3 p)
{
// results container
vec4 res;
// define objects
// sphere 1
// sphere: radius, orbit radius, orbit speed, orbit offset, position
float sR = 1.359997;
float sOR = 2.666662;
float sOS = 0.85;
vec3 sOO = vec3(2.66662,0.0,0.0);
vec3 sOP = (sOO + vec3(sOR*cos(sOS*iTime),sOR*sin(sOS*iTime),0.0));
vec3 sP = p - sOP;
vec4 sphere_1 = vec4( sdSphere(sP,sR), accessColors(1.0) );
vec3 sP2 = p - 1.0515*sOP.xzy;
vec4 sphere_2 = vec4( sdSphere(sP2,1.1750*sR), accessColors(5.0) );
vec3 lightSP = p - generateLightPos();
vec4 lightSphere = vec4( sdSphere(lightSP,0.24), accessColors(5.0));
// torus 1
vec2 torusSpecs = vec2(1.76, 0.413333);
float twistSpeed = 0.35;
float twistPower = 3.0*sin(twistSpeed * iTime);
// to twist the torus (or any object), we actually distort p/space (domain) itself,
// this then gives us a distorted view of the object
vec3 torusPos = vec3(0.0);
vec3 distortedP = opTwist(p - torusPos, twistPower, 0.0) ;
// domain distortion correction:
// needed to find this by hand, inversely proportional to domain deformation
float ddc = 0.25;
vec4 torus_1 = vec4(ddc*sdTorus(distortedP,torusSpecs),accessColors(2.0));
vec3 boxPos = p - vec3(4.0, -0.800,1.0);
vec4 box_1 = vec4(sdBox(boxPos,vec3(0.50,1.0,1.5)),accessColors(3.0));
vec3 planePos = p - vec3(0.0, -3.0, 0.0);
vec4 plane_1 = vec4(sdPlane(planePos), accessColors(4.0));
// blend objects
res = opBlend( sphere_1, torus_1, 0.7 );
res = opBlend( res, box_1, 0.6 );
res = opBlend( res, plane_1, 0.5);
//res = opBlend( res, sphere_2, 0.87);
res.x = opSub(res.x,sphere_2.x);
// visualize light pos, but blocks light :/
//res = opBlend( res, lightSphere, 0.1);
return res;
}
// ~~~~~~~ cast/march ray through the word and see what it hits
// input ro --> ray origin point/position
// input rd --> ray direction
// in/out --> itterationRatio (used for AA),in/out cuz no more room in vec
// output is vec3 where
// .x = distance travelled by ray
// .y = hit object's ID
// .z = itteration ratio
vec4 castRay( vec3 ro, vec3 rd, inout float itterRatio)
{
// variables used to control the marching process
const float maxMarchCount = 200.0;
float maxRayDistance = 50.0;
// making this more precise can also help with AA detection
// value lower than 0.000001 causes noise
float minPrecisionCheck = 0.000001;
float t = 0.0; // travelled distance by ray
vec3 oc = vec3(1.0,0.0,1.0); // object color
itterRatio = 0.0;
for(float i = 0.0; i < maxMarchCount; i++)
{
// get closest object to current ray position
vec4 res = map(ro + rd*t);
// stop itterating/marching once either we've past max ray length
// or
// once we're close enough to an object (defined by the precision check variable)
if(t > maxRayDistance || res.x < minPrecisionCheck)
break;
// move ray forward by distance to closet object, see
// http://http.developer.nvidia.com/GPUGems2/elementLinks/08_displacement_05.jpg
t += res.x;
oc = res.yzw;
itterRatio = i/maxMarchCount;
}
// if ray goes beyond max distance, force ID back to background one
if(t > maxRayDistance)
oc = accessColors(-1.0);
return vec4(t,oc.xyz);
}
// ~~~~~~~ hardShadow, raymarches from shading point to light
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> 0.0 means shadow, 1.0 means no shadow
float castRay_HardShadow(vec3 sp, vec3 lp)
{
const int hsMaxMarchCount = 100;
const float hsPrecision = 0.0001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float hsMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float hsT = 0.02; //2.10 * hsPrecision;
for(int i = 0; i < hsMaxMarchCount; i++)
{
float dist = map(sp + rd*hsT).x;
// if object hit on way to light, return hard shadow
if(dist < hsPrecision)
return 0.0;
hsT += dist;
}
// no object hit on the way to light source
return 1.0;
}
// ~~~~~~~ softShadow, took pointers from iq's
// http://www.iquilezles.org/www/articles/rmshadows/rmshadows.htm
// and
// https://www.shadertoy.com/view/Xds3zN
// input sp --> position of surface we are shading
// input lp --> light position
// output float --> amount of shadow
float castRay_SoftShadow(vec3 sp, vec3 lp)
{
const int ssMaxMarchCount = 90;
const float ssPrecision = 0.001;
// direction of ray, from shaded surface point to light pos
vec3 rd = normalize(lp - sp);
// max travel distance of hard shadow ray
float ssMaxT = length(lp - sp);
// travelled distance by hard shadow ray
float ssT = 0.02;
// softShadow value
float ssV = 1.0;
for(int i = 0; i < ssMaxMarchCount; i++)
{
float dist = map(sp + rd*ssT).x;
// if object hit on way to light, return hard shadow
if(dist < ssPrecision)
return 0.0;
ssV = min(ssV, 16.0*dist/ssT);
ssT += dist;
if(ssT > ssMaxT)
break;
}
return ssV;
}
// ~~~~~~~ ambientOcclusion
// just cast from surface point in direction of normal to see if any hit
// basic concept from:
// http://9bitscience.blogspot.com/2013/07/raymarching-distance-fields_14.html
float castRay_AmbientOcclusion(vec3 sp, vec3 nor)
{
const int aoMaxMarchCount = 20;
const float aoPrecision = 0.001;
// range of ambient occlusion
float aoMaxT = 1.0;
float aoT = 0.01;
float aoV = 1.0;
for(int i = 0; i < aoMaxMarchCount; i++)
{
float dist = map(sp + nor*aoT).x;
aoV = aoT/aoMaxT;
if(dist < aoPrecision)
break;
if(aoT > aoMaxT)
break;
aoT += dist;
}
return clamp(aoV, 0.0,1.0);
}
// ~~~~~~ calculate normal of closest objects surface given a ray position
// input p --> ray position (calculated previously from ray cast position, no iteration now
// output --> surface normal vector
//
// gets the surface normal by sampling neaby points and getting direction of diffs
vec3 calculateNormal(vec3 p)
{
float normalEpsilon = 0.0001;
vec3 eps = vec3(normalEpsilon,0,0);
vec3 normal = vec3( map(p + eps.xyy).x - map(p - eps.xyy).x,
map(p + eps.yxy).x - map(p - eps.yxy).x,
map(p + eps.yyx).x - map(p - eps.yyx).x
);
return normalize(normal);
}
// ~~~~~~~ calculates the normals near point p in world space
// input p --> ray position world coordinates
// input oN --> normal vector at point p
// output --> averaged? out norals diffs of nearby points
vec3 nearbyNormalsDiff(vec3 p, vec3 oN)
{
// world pos diff
float wPD = 0.0;
wPD = 0.057;
//wPD = abs(0.05*sin(0.25*iTime)) + 0.1;
vec3 n1 = calculateNormal(p+vec3(wPD,wPD,wPD));
//vec3 n2 = calculateNormal(p+vec3(wPD,wPD,-wPD));
//vec3 n3 = calculateNormal(p+vec3(wPD,-wPD,wPD));
//vec3 n4 = calculateNormal(p+vec3(wPD,-wPD,-wPD));
// doing full on 8 points version seems to crash it
vec3 diffVec = vec3(0.0);
diffVec += oN - n1;
//diffVec += oN - n2;
//diffVec += oN - n3;
//diffVec += oN - n4;
return diffVec;
}
// ~~~~~~~ do gamma correction
// from iq's pageon outdoor lighting:
// http://www.iquilezles.org/www/articles/outdoorslighting/outdoorslighting.htm
// input c --> original color
// output --> gamma corrected output
vec3 applyGammaCorrection(vec3 c)
{
return pow( c, vec3(1.0/2.2) );
}
// ~~~~~~~ do fog
// from iq's pageon fog:
// http://www.iquilezles.org/www/articles/fog/fog.htm
// input c --> original color
// input d --> pixel world distance
// input fc1 --> fog color 1
// input fc2 --> fog color 2
// input fs -- fog specs>
// fs.x --> fog density
// fs.y --> fog color lerp exponent (iq's default is 8.0)
// input cRD --> camera ray direction
// input lRD --> light ray direction
// output --> color with fog applied
vec3 applyFog(vec3 c,float d,vec3 fc1,vec3 fc2,vec2 fs,vec3 cRD,vec3 lRD)
{
float fogAmount = 1.0 - exp(-d*fs.x);
float lightAmount = max( dot( cRD, lRD ), 0.0 );
vec3 fogColor = mix(fc1,fc2,pow(lightAmount,fs.y));
return mix(c,fogColor,fogAmount);
}
// ~~~~~~~ calculates attenuation factor for light for a given distance and parameters
// input cF --> constant factor
// input lF --> linear factor
// input qF --> quadratic factor
// the factors above should range between 0 and 1
// pure realistic would follow inverse square law, i.e. pure quadtratic, so cF=0,lF=0,qF=1
float calculateLightAttn(float cF, float lF, float qF, float d)
{
float falloff = 1.0/(cF + lF*d + qF*d*d);
return falloff;
}
// ~~~~~~~ render pixel --> find closest surface and apply color accordingly
// input ro --> pixel's ray original position
// input rd --> pixel's ray direction
// in/out aaF --> antialiasing factor
// output --> pixel color
vec4 render(vec3 ro, vec3 rd, inout float aaF)
{
vec3 ambientLightColor = vec3( 0.001 , 0.001, 0.001 );
vec3 lightPos = generateLightPos();
float iR = 0.0;
vec4 res = castRay(ro, rd, iR);
float t = res.x;
vec3 objectColor = vec3(1.0,0.0,1.0);
objectColor = res.yzw;
// hard set pixel value if its a background one
if(objectColor == accessColors(-1.0))
return vec4(objectColor.xyz,iR);
else
{
//objectColor = normalize(objectColor);
// calculate pixel normal
vec3 pos = ro + t*rd;
vec3 normal = calculateNormal(pos);
float dist = length(pos);
vec3 lightDir = normalize(lightPos-pos);
float lightFalloff = calculateLightAttn(0.0,0.0,1.0,dist);
float lightIntensity = 6.0;
float lightFactor = lightFalloff * lightIntensity;
// treating light as a point light (calculating normal based on pos)
float surf = lightFactor * clamp(dot(normal,lightDir), 0.0, 1.0);
vec3 pixelColor = objectColor * surf;
pixelColor *= castRay_SoftShadow(pos,lightPos);
pixelColor *= castRay_AmbientOcclusion(pos,normal);
pixelColor += ambientLightColor;
vec3 fc_1 = vec3(0.5,0.6,0.7);
vec3 fc_2 = vec3(1.0,0.9,0.7);
vec2 fS = vec2(0.020,2.0);
pixelColor = applyFog(pixelColor,dist,fc_1,fc_2,fS,rd,lightDir);
pixelColor = applyGammaCorrection(pixelColor);
float aaFactor = 0.0;
if(isPseudoAA == true)
{
// AA RELATED STUFF
// visualize itteration count of pixels
//pixelColor = vec3(res.z);
vec3 nnDiff = nearbyNormalsDiff(pos,normal);
// pseudo edge/tangent detect? wrt ray, approx grazing ray
float sEdge = clamp(1.0 + dot(rd,normal),0.0,1.0);
//sEdge *= 1.0 - (t/200.0);
// TODO : better weighing for the 2 factors to narrow down on AA p
// gets affected by castRay precision variable
//aaFactor = 0.75*pow(sEdge,10.0)+ 0.5*iR;
aaFactor += 0.75*pow(sEdge,10.0);
// visualizes march count, looks cool!
aaFactor += 0.5*iR;
aaFactor += 0.5 *length(nnDiff);
// visualize AA needing pizel
pixelColor = vec3(aaFactor);
//pixelColor = nnDiff;
aaF = aaFactor;
}
// pixelColor in xyz, w is itteration count, used for AA
vec4 pixelData = vec4(pixelColor.xyz,aaFactor);
return pixelData;
}
}
// ~~~~~~~ generate camera ray direction, different for each frag/pixel
// input fCoord --> pixel coordinate
// input cMatric --> camera matrix
// output --> ray direction
vec3 calculateRayDir(vec2 fCoord, mat3 cMatrix)
{
vec2 p = ( -iResolution.xy + 2.0 * fCoord.xy ) / iResolution.y;
// determines ray direction based on camera matrix
// "lens length" seems to be related to field of view / ray divergence
float lensLen0gth = 2.0;
vec3 rD = cMatrix * normalize( vec3(p.xy,2.0) );
return rD;
}
// ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
}
// ~~~~~~~ creates camera matrix used to transform ray point/direction
// input camPos --> camera position
// input targetPos --> look at target position
// input roll --> how much camera roll
// output --> camera matrix used to transform
mat3 setCamera( in vec3 camPos, in vec3 targetPos, float roll )
{
vec3 cw = normalize(targetPos - camPos);
vec3 cp = vec3(sin(roll), cos(roll),0.0);
vec3 cu = normalize( cross(cw,cp) );
vec3 cv = normalize( cross(cu,cw) );
return mat3( cu, cv, cw );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera stuff, the same for all pixel in a frame
float camOrbitSpeed = 0.10;
float camOrbitRadius = 7.3333;
float camPosX = camOrbitRadius * cos( camOrbitSpeed * iTime);
float camPosZ = camOrbitRadius * sin( camOrbitSpeed * iTime);
vec3 camPos = vec3(camPosX, 0.5, camPosZ);
vec3 lookAtTarget = vec3(0.0);
mat3 camMatrix = setCamera(camPos, lookAtTarget, 0.0);
// ordinary, no AA render
vec3 rd = calculateRayDir(fragCoord,camMatrix);
vec3 col;
if(isPseudoAA == false)
{
float dum = 0.0; col = render(camPos,rd,dum).xyz;
}
else
col = render_AA(fragCoord,camPos,camMatrix);
fragColor = vec4(col,1.0);
//fragColor = vec4(fragCoord.xy/iResolution.y,0,0);
}
| cc0-1.0 | [
20692,
20987,
21036,
21036,
22763
] | [
[
1507,
1728,
1757,
1757,
2660
],
[
2663,
2798,
2831,
2831,
2859
],
[
2861,
4088,
4117,
4117,
4341
],
[
4491,
4907,
4938,
4938,
5061
],
[
5182,
5395,
5418,
5418,
5436
],
[
5438,
5713,
5755,
5755,
5856
],
[
5858,
6156,
6199,
6199,
6490
],
[
6492,
6731,
6775,
6775,
6907
],
[
6909,
7081,
7109,
7109,
7179
],
[
7181,
7406,
7438,
7438,
7467
],
[
7470,
7561,
7586,
7586,
7839
],
[
7841,
8119,
8137,
8162,
10044
],
[
10046,
10367,
10424,
10478,
11655
],
[
11658,
11863,
11907,
11907,
12557
],
[
12559,
12842,
12886,
12886,
13601
],
[
13603,
13806,
13857,
13857,
14317
],
[
14609,
14609,
14639,
14639,
14965
],
[
14967,
15176,
15217,
15239,
15774
],
[
15776,
15992,
16027,
16027,
16065
],
[
16067,
16520,
16595,
16595,
16786
],
[
16790,
17113,
17178,
17178,
17246
],
[
17248,
17473,
17521,
17521,
20151
],
[
20154,
20326,
20375,
20375,
20689
],
[
20692,
20987,
21036,
21036,
22763
],
[
22765,
23004,
23069,
23069,
23275
],
[
23277,
23277,
23334,
23397,
24099
]
] | // ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
| vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{ |
vec3 rd = calculateRayDir(fCoord,cMat);
float aaF = 0.0;
vec4 pData = render(cPos,rd,aaF);
vec3 col = pData.xyz;
float aaThreashold = 0.845;
// controls blur amount/sample distance
float aaPD = 0.500;
// if requires AA, get color from nearby pixels and average out
//col = vec3(0.0);
if(aaF > aaThreashold)
{
float dummy = 0.0;
vec3 rd_U = calculateRayDir(fCoord + vec2(0,aaPD),cMat);
vec3 pc_U = render(cPos,rd_U,dummy).xyz;
vec3 rd_D = calculateRayDir(fCoord + vec2(0,-aaPD),cMat);
vec3 pc_D = render(cPos,rd_D,dummy).xyz;
vec3 rd_R = calculateRayDir(fCoord + vec2(aaPD,0),cMat);
vec3 pc_R = render(cPos,rd_R,dummy).xyz;
vec3 rd_L = calculateRayDir(fCoord + vec2(-aaPD,0),cMat);
vec3 pc_L = render(cPos,rd_L,dummy).xyz;
/*
vec3 rd_UR = calculateRayDir(fCoord + vec2(aaPD,aaPD),cMat);
vec3 pc_UR = render(cPos,rd_UR,dummy).xyz;
vec3 rd_UL = calculateRayDir(fCoord + vec2(-aaPD,aaPD),cMat);
vec3 pc_UL = render(cPos,rd_UL,dummy).xyz;
vec3 rd_DR = calculateRayDir(fCoord + vec2(aaPD,-aaPD),cMat);
vec3 pc_DR = render(cPos,rd_DR,dummy).xyz;
vec3 rd_DL = calculateRayDir(fCoord + vec2(-aaPD,-aaPD),cMat);
vec3 pc_DL = render(cPos,rd_DL,dummy).xyz;
col = pc_U+pc_D+pc_R+pc_L+pc_UR+pc_UL+pc_DR+pc_DL;
col *= 1.0/8.0;
*/
col = 0.25*(pc_U+pc_D+pc_R+pc_L);
// used to visualize pixels that are getting AA
//col = vec3(1.0,0.0,1.0) + 0.001*(pc_U+pc_D+pc_R+pc_L);
}
return col;
} | // ~~~~~~~ render anti aliased, based on pixel's itteration/march count
// only effective for shape edges, doesn't fix surface col patterns
// input fCoord --> pixel coordinate
// input cPos --> camera position
// input cMat --> camera matrix
// output vec3 --> pixel antialaised color
vec3 render_AA(vec2 fCoord,vec3 cPos,mat3 cMat)
{ | 1 | 2 |
MsyXDV | SparkX120 | 2016-06-23T04:30:06 | /**
* Adapted from my Mandelbrot-JS Project
* http://sparkx120.github.io/mandelbrot.html
* https://github.com/Sparkx120/mandelbrot-js
*
* By: James Wake (SparkX120)
* Copyright (c) 2016 James Wake
*
* MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
const float iterations = 512.;
const float maxZoom = 20.;
vec2 R = iResolution.xy; // Resolution Variable
float scale = 0.5*exp2(mod(iTime, maxZoom)); // Set Scale to 2^time and Loop at MaxZoom
vec2 scalar = vec2(3.5,3.5*R.y/R.x)/scale; // Always fit width
vec2 aspect = vec2(1.4,2.0); // Old Coord Compatibility
vec2 offset = vec2(0); // Hacky solution for multiple coordinates
float modTime = mod(iTime/maxZoom, 3.0);
offset = modTime < 1. ? vec2(21.30899,-5.33795) :
modTime < 2. ? vec2(5.39307,-41.7374) :
vec2(48.895,0) ;
vec2 T = fragCoord-R*offset*scale/100.; // Mandelbrot Space Transform
vec2 z0 = scalar/R*T - scalar/aspect; // Scaling and Aspect Correction
vec2 z = vec2(0);
float iteration = iterations;
for (float i=0.0; i < iterations; i++) { // Escape Time Computation
//z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + z0;
z = mat2(z,-z.y,z.x)*z + z0;
if(dot(z, z) > 4.){ iteration = i; break; }
}
// Custom Color Shader based on log functions
float intensity = iteration == iterations ? 0.0 : iteration/iterations;
float redGreen = intensity*((-1./4.)*log((-1.0/11.112347)*intensity+0.09)-0.25);
float blue = (intensity*(1.-2.4*log(intensity+0.0000000001)));
fragColor = vec4(redGreen,redGreen, blue, 1);
}
/* Old Shader
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
const float iterations = 512.0; // Iterations to compute over
const float maxZoom = 20.0; // Max Zoom Time
float scale = 0.5*pow(2.0, mod(iTime, maxZoom)); // Set Scale to 2^time and Loop at MaxZoomTime
float width = iResolution[0]; // Width Height
float height = iResolution[1]; //
float widthScalar = 3.5/scale; // Always fit width
float heightScalar = 3.5*height/width/scale; // scale height
float Px = fragCoord.x; // Set Pixel Position
float Py = fragCoord.y; //
vec2 offset = vec2(0.0, 0.0); // Hacky solution for multiple coordinates
float modTime = mod(iTime/maxZoom, 3.0);
if(modTime >= 0.0 && modTime < 1.0){
offset = vec2(21.30899, -5.33795); // Coordinate 1
}
if(modTime >= 1.0 && modTime < 2.0){
offset = vec2(5.39307,-41.7374); // Coordinate 2
}
if(modTime >= 2.0 && modTime < 3.0){
offset = vec2(48.895,0.0); // Coordinate 3
}
float xDelta = iResolution.x/100.0*offset.x; // Mandelbrot space offset
float yDelta = iResolution.y/100.0*offset.y; //
float Tx = Px-xDelta*scale; // X-Y Translation
float Ty = Py-yDelta*scale;
float x0 = widthScalar/width*Tx - widthScalar/1.4; // Scaling and Aspect Correction
float y0 = heightScalar/height*Ty - heightScalar/2.0; //
float x = 0.0;
float y = 0.0;
float iteration = iterations;
int end = 0;
for (float i=0.0; i < iterations; i++) { // Escape Time Computation
float xtemp = x*x-y*y+x0;
y = 2.0*x*y+y0;
x = xtemp;
if(x*x+y*y > 4.0){
iteration = i;
break;
}
}
float intensity = iteration == iterations ? 0.0 : iteration/iterations;
// Custom Color Shader based on log functions
float redGreen = intensity*((-1.0/4.0)*log((-1.0/11.112347)*intensity+0.09)-0.25);
float blue = (intensity*(1.0-2.4*log(intensity+0.0000000001)));
fragColor = vec4(redGreen,redGreen, blue, 1.0);
}*/ | mit | [
0,
1289,
1346,
1346,
2956
] | [
[
0,
1289,
1346,
1346,
2956
]
] | /**
* Adapted from my Mandelbrot-JS Project
* http://sparkx120.github.io/mandelbrot.html
* https://github.com/Sparkx120/mandelbrot-js
*
* By: James Wake (SparkX120)
* Copyright (c) 2016 James Wake
*
* MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
| void mainImage( out vec4 fragColor, in vec2 fragCoord )
{ |
const float iterations = 512.;
const float maxZoom = 20.;
vec2 R = iResolution.xy; // Resolution Variable
float scale = 0.5*exp2(mod(iTime, maxZoom)); // Set Scale to 2^time and Loop at MaxZoom
vec2 scalar = vec2(3.5,3.5*R.y/R.x)/scale; // Always fit width
vec2 aspect = vec2(1.4,2.0); // Old Coord Compatibility
vec2 offset = vec2(0); // Hacky solution for multiple coordinates
float modTime = mod(iTime/maxZoom, 3.0);
offset = modTime < 1. ? vec2(21.30899,-5.33795) :
modTime < 2. ? vec2(5.39307,-41.7374) :
vec2(48.895,0) ;
vec2 T = fragCoord-R*offset*scale/100.; // Mandelbrot Space Transform
vec2 z0 = scalar/R*T - scalar/aspect; // Scaling and Aspect Correction
vec2 z = vec2(0);
float iteration = iterations;
for (float i=0.0; i < iterations; i++) { // Escape Time Computation
//z = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + z0;
z = mat2(z,-z.y,z.x)*z + z0;
if(dot(z, z) > 4.){ iteration = i; break; }
}
// Custom Color Shader based on log functions
float intensity = iteration == iterations ? 0.0 : iteration/iterations;
float redGreen = intensity*((-1./4.)*log((-1.0/11.112347)*intensity+0.09)-0.25);
float blue = (intensity*(1.-2.4*log(intensity+0.0000000001)));
fragColor = vec4(redGreen,redGreen, blue, 1);
} | /**
* Adapted from my Mandelbrot-JS Project
* http://sparkx120.github.io/mandelbrot.html
* https://github.com/Sparkx120/mandelbrot-js
*
* By: James Wake (SparkX120)
* Copyright (c) 2016 James Wake
*
* MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{ | 1 | 16,281 |
MsVXDt | otaviogood | 2016-07-20T06:51:21 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// ---------------- Config ----------------
// This is an option that lets you render high quality frames for screenshots. It enables
// stochastic antialiasing and motion blur automatically for any shader.
//#define NON_REALTIME_HQ_RENDER
const float frameToRenderHQ = 11.0; // Time in seconds of frame to render
const float antialiasingSamples = 16.0; // 16x antialiasing - too much might make the shader compiler angry.
//#define MANUAL_CAMERA
// --------------------------------------------------------
// These variables are for the non-realtime block renderer.
float localTime = 0.0;
float seed = 1.0;
// ---- noise functions ----
float v31(vec3 a)
{
return a.x + a.y * 37.0 + a.z * 521.0;
}
float v21(vec2 a)
{
return a.x + a.y * 37.0;
}
float Hash11(float a)
{
return fract(sin(a)*10403.9);
}
float Hash21(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
vec2 Hash22(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(cos(f)*vec2(10003.579, 37049.7));
}
vec2 Hash12(float f)
{
return fract(cos(f)*vec2(10003.579, 37049.7));
}
float Hash1d(float u)
{
return fract(sin(u)*143.9); // scale this down to kill the jitters
}
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(sin(f)*110003.9);
}
const float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
// polynomial smooth min (k = 0.1);
float smin( float a, float b, float k )
{
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
vec2 matMin(vec2 a, vec2 b)
{
if (a.x < b.x) return a;
else return b;
}
// ---- shapes defined by distance fields ----
// See this site for a reference to more distance functions...
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// box distance field
float sdBox(vec3 p, vec3 radius)
{
vec3 dist = abs(p) - radius;
return min(max(dist.x, max(dist.y, dist.z)), 0.0) + length(max(dist, 0.0));
}
// simple cylinder distance field
float cyl(vec2 p, float r)
{
return length(p) - r;
}
const float TAU = 2.0 * PI;
float glow = 0.0;
// This is the function that makes the geometry.
// The input is a position in space.
// The output is the distance to the nearest surface and a material number
vec2 DistanceToObject(vec3 p)
{
float time = localTime*2.0;
float cylRadBig = 1.0;
float cylRadSmall = 0.05;
float freq = 4.0;
float braidRad = 0.15;
float angle = atan(p.z, p.x);
float cylDist = length(p.xz) - cylRadBig;
vec3 cylWarp = vec3(cylDist, p.y, angle);
float amp = sin(angle + time) * 0.5 + 0.5;
float theta = angle*freq;
vec2 wave1 = vec2(sin(theta), cos(theta)) * braidRad;
wave1 *= amp;
//float d = length(cylWarp.xy + wave1) - cylRadSmall;
float d = sdBox(vec3(cylWarp.xy + wave1, 0.0), vec3(cylRadSmall));
float final = d;
theta = angle*freq + TAU / 3.0;
vec2 wave2 = vec2(sin(theta), cos(theta)) * braidRad;
wave2 *= amp;
//d = length(cylWarp.xy + wave2) - cylRadSmall;
d = sdBox(vec3(cylWarp.xy + wave2, 0.0), vec3(cylRadSmall));
final = smin(final, d, 0.1);
theta = angle*freq - TAU / 3.0;
vec2 wave3 = vec2(sin(theta), cos(theta)) * braidRad;
wave3 *= amp;
//d = length(cylWarp.xy + wave3) - cylRadSmall;
d = sdBox(vec3(cylWarp.xy + wave3, 0.0), vec3(cylRadSmall));
final = smin(final, d, 0.1);
vec2 matd = vec2(final, fract((angle+time) / TAU+0.5));
float sliver = cyl(cylWarp.xy, 0.03);
glow += 1.0 / (sliver * sliver * sliver * sliver + 1.0);
//sliver = max(sliver, abs(fract(cylWarp.z*freq-2.0*localTime)-0.5)-0.3);
matd = matMin(matd, vec2(sliver, -1.0));
return matd;
}
// Input is UV coordinate of pixel to render.
// Output is RGB color.
vec3 RayTrace(in vec2 fragCoord )
{
glow = 0.0;
// -------------------------------- animate ---------------------------------------
vec3 camPos, camUp, camLookat;
// ------------------- Set up the camera rays for ray marching --------------------
// Map uv to [-1.0..1.0]
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
float zoom = 2.2;
uv /= zoom;
// Camera up vector.
camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0;
float my=-iMouse.y/iResolution.y*10.0;
#ifndef MANUAL_CAMERA
camPos = vec3(0.0);
camPos.y = sin(localTime*0.125)*3.0;
camPos.z = cos(localTime*0.125)*3.0;
camUp.y = camPos.z;
camUp.z = -camPos.y;
camUp = normalize(camUp);
#else
camPos = vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*3.0;
#endif
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 rayVec = normalize(worldPix - camPos);
// ----------------------------- Ray march the scene ------------------------------
vec2 distMat = vec2(1.0, 0.0);
float t = 0.0 + Hash2d(uv)*1.6; // random dither glow by moving march count start position
const float maxDepth = 6.0; // farthest distance rays will travel
vec3 pos = vec3(0,0,0);
const float smallVal = 0.000625;
float marchCount = 0.0;
// ray marching time
for (int i = 0; i < 80; i++) // This is the count of the max times the ray actually marches.
{
// Step along the ray.
pos = camPos + rayVec * t;
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry. The idea is that the
// distance field returns the distance to the closest object, and then
// we know we are safe to "march" along the ray by that much distance
// without hitting anything. We repeat this until we get really close
// and then break because we have effectively hit the object.
distMat = DistanceToObject(pos);
// Move along the ray.
// Leave room for error by multiplying in case distance function isn't exact.
t += distMat.x * 0.8;
// If we are very close to the object, let's call it a hit and exit this loop.
if ((t > maxDepth) || (abs(distMat.x) < smallVal)) break;
// Glow if we're close to the part of the ring with the braid.
float cyc = (-sin(distMat.y * TAU))*0.5+0.7;
// This function is similar to a gaussian fall-off of glow when you're close
// to an object.
// http://thetamath.com/app/y=(1)/((x*x+1))
marchCount += cyc / (distMat.x * distMat.x + 1.0);
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
// Save off ray-march glows so they don't get messed up when we call the distance
// function again to get the normal
float glowSave = glow;
float marchSave = marchCount;
marchCount = 0.0;
glow = 0.0;
// default to blueish background color.
vec3 finalColor = vec3(0.09, 0.15, 0.35);
// If a ray actually hit the object, let's light it.
if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(smallVal, 0, 0);
vec3 normalU = vec3(distMat.x - DistanceToObject(pos - smallVec.xyy).x,
distMat.x - DistanceToObject(pos - smallVec.yxy).x,
distMat.x - DistanceToObject(pos - smallVec.yyx).x);
vec3 texColor = vec3(0.0, 0.0, 0.1);
if (distMat.y < 0.0) texColor = vec3(0.6, 0.3, 0.1)*110.0;
finalColor = texColor;
// visualize length of gradient of distance field to check distance field correctness
//finalColor = vec3(0.5) * (length(normalU) / smallVec.x);
}
// add the ray marching glows
finalColor += vec3(0.3, 0.5, 0.9) * glowSave*0.00625;
finalColor += vec3(1.0, 0.5, 0.3) * marchSave*0.05;
// vignette
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
// output the final color without gamma correction - will do gamma later.
return vec3(saturate(finalColor));
}
#ifdef NON_REALTIME_HQ_RENDER
// This function breaks the image down into blocks and scans
// through them, rendering 1 block at a time. It's for non-
// realtime things that take a long time to render.
// This is the frame rate to render at. Too fast and you will
// miss some blocks.
const float blockRate = 20.0;
void BlockRender(in vec2 fragCoord)
{
// blockSize is how much it will try to render in 1 frame.
// adjust this smaller for more complex scenes, bigger for
// faster render times.
const float blockSize = 64.0;
// Make the block repeatedly scan across the image based on time.
float frame = floor(iTime * blockRate);
vec2 blockRes = floor(iResolution.xy / blockSize) + vec2(1.0);
// ugly bug with mod.
//float blockX = mod(frame, blockRes.x);
float blockX = fract(frame / blockRes.x) * blockRes.x;
//float blockY = mod(floor(frame / blockRes.x), blockRes.y);
float blockY = fract(floor(frame / blockRes.x) / blockRes.y) * blockRes.y;
// Don't draw anything outside the current block.
if ((fragCoord.x - blockX * blockSize >= blockSize) ||
(fragCoord.x - (blockX - 1.0) * blockSize < blockSize) ||
(fragCoord.y - blockY * blockSize >= blockSize) ||
(fragCoord.y - (blockY - 1.0) * blockSize < blockSize))
{
discard;
}
}
#endif
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
#ifdef NON_REALTIME_HQ_RENDER
// Optionally render a non-realtime scene with high quality
BlockRender(fragCoord);
#endif
// Do a multi-pass render
vec3 finalColor = vec3(0.0);
#ifdef NON_REALTIME_HQ_RENDER
for (float i = 0.0; i < antialiasingSamples; i++)
{
const float motionBlurLengthInSeconds = 1.0 / 60.0;
// Set this to the time in seconds of the frame to render.
localTime = frameToRenderHQ;
// This line will motion-blur the renders
localTime += Hash11(v21(fragCoord + seed)) * motionBlurLengthInSeconds;
// Jitter the pixel position so we get antialiasing when we do multiple passes.
vec2 jittered = fragCoord.xy + vec2(
Hash21(fragCoord + seed),
Hash21(fragCoord*7.234567 + seed)
);
// don't antialias if only 1 sample.
if (antialiasingSamples == 1.0) jittered = fragCoord;
// Accumulate one pass of raytracing into our pixel value
finalColor += RayTrace(jittered);
// Change the random seed for each pass.
seed *= 1.01234567;
}
// Average all accumulated pixel intensities
finalColor /= antialiasingSamples;
#else
// Regular real-time rendering
localTime = iTime;
finalColor = RayTrace(fragCoord);
#endif
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
2400,
2602,
2636,
2636,
2747
] | [
[
1174,
1203,
1222,
1222,
1267
],
[
1268,
1268,
1287,
1287,
1318
],
[
1319,
1319,
1342,
1342,
1378
],
[
1379,
1379,
1402,
1402,
1473
],
[
1474,
1474,
1496,
1496,
1583
],
[
1584,
1584,
1606,
1606,
1659
],
[
1660,
1660,
1683,
1683,
1756
],
[
1757,
1757,
1780,
1780,
1851
],
[
1852,
1852,
1875,
1875,
1961
],
[
1991,
1991,
2014,
2014,
2043
],
[
2044,
2044,
2067,
2067,
2096
],
[
2097,
2097,
2122,
2122,
2151
],
[
2153,
2189,
2230,
2230,
2323
],
[
2325,
2325,
2354,
2354,
2398
],
[
2400,
2602,
2636,
2636,
2747
],
[
2749,
2783,
2811,
2811,
2839
],
[
2888,
3049,
3080,
3080,
4480
],
[
4482,
4552,
4587,
4587,
9140
],
[
10472,
10472,
10529,
10529,
11888
]
] | // ---- shapes defined by distance fields ----
// See this site for a reference to more distance functions...
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// box distance field
| float sdBox(vec3 p, vec3 radius)
{ |
vec3 dist = abs(p) - radius;
return min(max(dist.x, max(dist.y, dist.z)), 0.0) + length(max(dist, 0.0));
} | // ---- shapes defined by distance fields ----
// See this site for a reference to more distance functions...
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// box distance field
float sdBox(vec3 p, vec3 radius)
{ | 10 | 10 |
MsVXDt | otaviogood | 2016-07-20T06:51:21 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
*/
// ---------------- Config ----------------
// This is an option that lets you render high quality frames for screenshots. It enables
// stochastic antialiasing and motion blur automatically for any shader.
//#define NON_REALTIME_HQ_RENDER
const float frameToRenderHQ = 11.0; // Time in seconds of frame to render
const float antialiasingSamples = 16.0; // 16x antialiasing - too much might make the shader compiler angry.
//#define MANUAL_CAMERA
// --------------------------------------------------------
// These variables are for the non-realtime block renderer.
float localTime = 0.0;
float seed = 1.0;
// ---- noise functions ----
float v31(vec3 a)
{
return a.x + a.y * 37.0 + a.z * 521.0;
}
float v21(vec2 a)
{
return a.x + a.y * 37.0;
}
float Hash11(float a)
{
return fract(sin(a)*10403.9);
}
float Hash21(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
vec2 Hash22(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(cos(f)*vec2(10003.579, 37049.7));
}
vec2 Hash12(float f)
{
return fract(cos(f)*vec2(10003.579, 37049.7));
}
float Hash1d(float u)
{
return fract(sin(u)*143.9); // scale this down to kill the jitters
}
float Hash2d(vec2 uv)
{
float f = uv.x + uv.y * 37.0;
return fract(sin(f)*104003.9);
}
float Hash3d(vec3 uv)
{
float f = uv.x + uv.y * 37.0 + uv.z * 521.0;
return fract(sin(f)*110003.9);
}
const float PI=3.14159265;
vec3 saturate(vec3 a) { return clamp(a, 0.0, 1.0); }
vec2 saturate(vec2 a) { return clamp(a, 0.0, 1.0); }
float saturate(float a) { return clamp(a, 0.0, 1.0); }
// polynomial smooth min (k = 0.1);
float smin( float a, float b, float k )
{
float h = clamp( 0.5+0.5*(b-a)/k, 0.0, 1.0 );
return mix( b, a, h ) - k*h*(1.0-h);
}
vec2 matMin(vec2 a, vec2 b)
{
if (a.x < b.x) return a;
else return b;
}
// ---- shapes defined by distance fields ----
// See this site for a reference to more distance functions...
// http://iquilezles.org/www/articles/distfunctions/distfunctions.htm
// box distance field
float sdBox(vec3 p, vec3 radius)
{
vec3 dist = abs(p) - radius;
return min(max(dist.x, max(dist.y, dist.z)), 0.0) + length(max(dist, 0.0));
}
// simple cylinder distance field
float cyl(vec2 p, float r)
{
return length(p) - r;
}
const float TAU = 2.0 * PI;
float glow = 0.0;
// This is the function that makes the geometry.
// The input is a position in space.
// The output is the distance to the nearest surface and a material number
vec2 DistanceToObject(vec3 p)
{
float time = localTime*2.0;
float cylRadBig = 1.0;
float cylRadSmall = 0.05;
float freq = 4.0;
float braidRad = 0.15;
float angle = atan(p.z, p.x);
float cylDist = length(p.xz) - cylRadBig;
vec3 cylWarp = vec3(cylDist, p.y, angle);
float amp = sin(angle + time) * 0.5 + 0.5;
float theta = angle*freq;
vec2 wave1 = vec2(sin(theta), cos(theta)) * braidRad;
wave1 *= amp;
//float d = length(cylWarp.xy + wave1) - cylRadSmall;
float d = sdBox(vec3(cylWarp.xy + wave1, 0.0), vec3(cylRadSmall));
float final = d;
theta = angle*freq + TAU / 3.0;
vec2 wave2 = vec2(sin(theta), cos(theta)) * braidRad;
wave2 *= amp;
//d = length(cylWarp.xy + wave2) - cylRadSmall;
d = sdBox(vec3(cylWarp.xy + wave2, 0.0), vec3(cylRadSmall));
final = smin(final, d, 0.1);
theta = angle*freq - TAU / 3.0;
vec2 wave3 = vec2(sin(theta), cos(theta)) * braidRad;
wave3 *= amp;
//d = length(cylWarp.xy + wave3) - cylRadSmall;
d = sdBox(vec3(cylWarp.xy + wave3, 0.0), vec3(cylRadSmall));
final = smin(final, d, 0.1);
vec2 matd = vec2(final, fract((angle+time) / TAU+0.5));
float sliver = cyl(cylWarp.xy, 0.03);
glow += 1.0 / (sliver * sliver * sliver * sliver + 1.0);
//sliver = max(sliver, abs(fract(cylWarp.z*freq-2.0*localTime)-0.5)-0.3);
matd = matMin(matd, vec2(sliver, -1.0));
return matd;
}
// Input is UV coordinate of pixel to render.
// Output is RGB color.
vec3 RayTrace(in vec2 fragCoord )
{
glow = 0.0;
// -------------------------------- animate ---------------------------------------
vec3 camPos, camUp, camLookat;
// ------------------- Set up the camera rays for ray marching --------------------
// Map uv to [-1.0..1.0]
vec2 uv = fragCoord.xy/iResolution.xy * 2.0 - 1.0;
float zoom = 2.2;
uv /= zoom;
// Camera up vector.
camUp=vec3(0,1,0);
// Camera lookat.
camLookat=vec3(0);
// debugging camera
float mx=iMouse.x/iResolution.x*PI*2.0;
float my=-iMouse.y/iResolution.y*10.0;
#ifndef MANUAL_CAMERA
camPos = vec3(0.0);
camPos.y = sin(localTime*0.125)*3.0;
camPos.z = cos(localTime*0.125)*3.0;
camUp.y = camPos.z;
camUp.z = -camPos.y;
camUp = normalize(camUp);
#else
camPos = vec3(cos(my)*cos(mx),sin(my),cos(my)*sin(mx))*3.0;
#endif
// Camera setup.
vec3 camVec=normalize(camLookat - camPos);
vec3 sideNorm=normalize(cross(camUp, camVec));
vec3 upNorm=cross(camVec, sideNorm);
vec3 worldFacing=(camPos + camVec);
vec3 worldPix = worldFacing + uv.x * sideNorm * (iResolution.x/iResolution.y) + uv.y * upNorm;
vec3 rayVec = normalize(worldPix - camPos);
// ----------------------------- Ray march the scene ------------------------------
vec2 distMat = vec2(1.0, 0.0);
float t = 0.0 + Hash2d(uv)*1.6; // random dither glow by moving march count start position
const float maxDepth = 6.0; // farthest distance rays will travel
vec3 pos = vec3(0,0,0);
const float smallVal = 0.000625;
float marchCount = 0.0;
// ray marching time
for (int i = 0; i < 80; i++) // This is the count of the max times the ray actually marches.
{
// Step along the ray.
pos = camPos + rayVec * t;
// This is _the_ function that defines the "distance field".
// It's really what makes the scene geometry. The idea is that the
// distance field returns the distance to the closest object, and then
// we know we are safe to "march" along the ray by that much distance
// without hitting anything. We repeat this until we get really close
// and then break because we have effectively hit the object.
distMat = DistanceToObject(pos);
// Move along the ray.
// Leave room for error by multiplying in case distance function isn't exact.
t += distMat.x * 0.8;
// If we are very close to the object, let's call it a hit and exit this loop.
if ((t > maxDepth) || (abs(distMat.x) < smallVal)) break;
// Glow if we're close to the part of the ring with the braid.
float cyc = (-sin(distMat.y * TAU))*0.5+0.7;
// This function is similar to a gaussian fall-off of glow when you're close
// to an object.
// http://thetamath.com/app/y=(1)/((x*x+1))
marchCount += cyc / (distMat.x * distMat.x + 1.0);
}
// --------------------------------------------------------------------------------
// Now that we have done our ray marching, let's put some color on this geometry.
// Save off ray-march glows so they don't get messed up when we call the distance
// function again to get the normal
float glowSave = glow;
float marchSave = marchCount;
marchCount = 0.0;
glow = 0.0;
// default to blueish background color.
vec3 finalColor = vec3(0.09, 0.15, 0.35);
// If a ray actually hit the object, let's light it.
if (t <= maxDepth)
{
// calculate the normal from the distance field. The distance field is a volume, so if you
// sample the current point and neighboring points, you can use the difference to get
// the normal.
vec3 smallVec = vec3(smallVal, 0, 0);
vec3 normalU = vec3(distMat.x - DistanceToObject(pos - smallVec.xyy).x,
distMat.x - DistanceToObject(pos - smallVec.yxy).x,
distMat.x - DistanceToObject(pos - smallVec.yyx).x);
vec3 texColor = vec3(0.0, 0.0, 0.1);
if (distMat.y < 0.0) texColor = vec3(0.6, 0.3, 0.1)*110.0;
finalColor = texColor;
// visualize length of gradient of distance field to check distance field correctness
//finalColor = vec3(0.5) * (length(normalU) / smallVec.x);
}
// add the ray marching glows
finalColor += vec3(0.3, 0.5, 0.9) * glowSave*0.00625;
finalColor += vec3(1.0, 0.5, 0.3) * marchSave*0.05;
// vignette
finalColor *= vec3(1.0) * saturate(1.0 - length(uv/2.5));
// output the final color without gamma correction - will do gamma later.
return vec3(saturate(finalColor));
}
#ifdef NON_REALTIME_HQ_RENDER
// This function breaks the image down into blocks and scans
// through them, rendering 1 block at a time. It's for non-
// realtime things that take a long time to render.
// This is the frame rate to render at. Too fast and you will
// miss some blocks.
const float blockRate = 20.0;
void BlockRender(in vec2 fragCoord)
{
// blockSize is how much it will try to render in 1 frame.
// adjust this smaller for more complex scenes, bigger for
// faster render times.
const float blockSize = 64.0;
// Make the block repeatedly scan across the image based on time.
float frame = floor(iTime * blockRate);
vec2 blockRes = floor(iResolution.xy / blockSize) + vec2(1.0);
// ugly bug with mod.
//float blockX = mod(frame, blockRes.x);
float blockX = fract(frame / blockRes.x) * blockRes.x;
//float blockY = mod(floor(frame / blockRes.x), blockRes.y);
float blockY = fract(floor(frame / blockRes.x) / blockRes.y) * blockRes.y;
// Don't draw anything outside the current block.
if ((fragCoord.x - blockX * blockSize >= blockSize) ||
(fragCoord.x - (blockX - 1.0) * blockSize < blockSize) ||
(fragCoord.y - blockY * blockSize >= blockSize) ||
(fragCoord.y - (blockY - 1.0) * blockSize < blockSize))
{
discard;
}
}
#endif
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
#ifdef NON_REALTIME_HQ_RENDER
// Optionally render a non-realtime scene with high quality
BlockRender(fragCoord);
#endif
// Do a multi-pass render
vec3 finalColor = vec3(0.0);
#ifdef NON_REALTIME_HQ_RENDER
for (float i = 0.0; i < antialiasingSamples; i++)
{
const float motionBlurLengthInSeconds = 1.0 / 60.0;
// Set this to the time in seconds of the frame to render.
localTime = frameToRenderHQ;
// This line will motion-blur the renders
localTime += Hash11(v21(fragCoord + seed)) * motionBlurLengthInSeconds;
// Jitter the pixel position so we get antialiasing when we do multiple passes.
vec2 jittered = fragCoord.xy + vec2(
Hash21(fragCoord + seed),
Hash21(fragCoord*7.234567 + seed)
);
// don't antialias if only 1 sample.
if (antialiasingSamples == 1.0) jittered = fragCoord;
// Accumulate one pass of raytracing into our pixel value
finalColor += RayTrace(jittered);
// Change the random seed for each pass.
seed *= 1.01234567;
}
// Average all accumulated pixel intensities
finalColor /= antialiasingSamples;
#else
// Regular real-time rendering
localTime = iTime;
finalColor = RayTrace(fragCoord);
#endif
fragColor = vec4(sqrt(clamp(finalColor, 0.0, 1.0)),1.0);
}
| cc0-1.0 | [
2888,
3049,
3080,
3080,
4480
] | [
[
1174,
1203,
1222,
1222,
1267
],
[
1268,
1268,
1287,
1287,
1318
],
[
1319,
1319,
1342,
1342,
1378
],
[
1379,
1379,
1402,
1402,
1473
],
[
1474,
1474,
1496,
1496,
1583
],
[
1584,
1584,
1606,
1606,
1659
],
[
1660,
1660,
1683,
1683,
1756
],
[
1757,
1757,
1780,
1780,
1851
],
[
1852,
1852,
1875,
1875,
1961
],
[
1991,
1991,
2014,
2014,
2043
],
[
2044,
2044,
2067,
2067,
2096
],
[
2097,
2097,
2122,
2122,
2151
],
[
2153,
2189,
2230,
2230,
2323
],
[
2325,
2325,
2354,
2354,
2398
],
[
2400,
2602,
2636,
2636,
2747
],
[
2749,
2783,
2811,
2811,
2839
],
[
2888,
3049,
3080,
3080,
4480
],
[
4482,
4552,
4587,
4587,
9140
],
[
10472,
10472,
10529,
10529,
11888
]
] | // This is the function that makes the geometry.
// The input is a position in space.
// The output is the distance to the nearest surface and a material number
| vec2 DistanceToObject(vec3 p)
{ |
float time = localTime*2.0;
float cylRadBig = 1.0;
float cylRadSmall = 0.05;
float freq = 4.0;
float braidRad = 0.15;
float angle = atan(p.z, p.x);
float cylDist = length(p.xz) - cylRadBig;
vec3 cylWarp = vec3(cylDist, p.y, angle);
float amp = sin(angle + time) * 0.5 + 0.5;
float theta = angle*freq;
vec2 wave1 = vec2(sin(theta), cos(theta)) * braidRad;
wave1 *= amp;
//float d = length(cylWarp.xy + wave1) - cylRadSmall;
float d = sdBox(vec3(cylWarp.xy + wave1, 0.0), vec3(cylRadSmall));
float final = d;
theta = angle*freq + TAU / 3.0;
vec2 wave2 = vec2(sin(theta), cos(theta)) * braidRad;
wave2 *= amp;
//d = length(cylWarp.xy + wave2) - cylRadSmall;
d = sdBox(vec3(cylWarp.xy + wave2, 0.0), vec3(cylRadSmall));
final = smin(final, d, 0.1);
theta = angle*freq - TAU / 3.0;
vec2 wave3 = vec2(sin(theta), cos(theta)) * braidRad;
wave3 *= amp;
//d = length(cylWarp.xy + wave3) - cylRadSmall;
d = sdBox(vec3(cylWarp.xy + wave3, 0.0), vec3(cylRadSmall));
final = smin(final, d, 0.1);
vec2 matd = vec2(final, fract((angle+time) / TAU+0.5));
float sliver = cyl(cylWarp.xy, 0.03);
glow += 1.0 / (sliver * sliver * sliver * sliver + 1.0);
//sliver = max(sliver, abs(fract(cylWarp.z*freq-2.0*localTime)-0.5)-0.3);
matd = matMin(matd, vec2(sliver, -1.0));
return matd;
} | // This is the function that makes the geometry.
// The input is a position in space.
// The output is the distance to the nearest surface and a material number
vec2 DistanceToObject(vec3 p)
{ | 2 | 8 |
ltVGWG | vmednis | 2016-10-15T10:36:55 | /*
Copyright (c) 2016 Valters Mednis
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#define ITERATIONS_MAX 100
#define EXIT_NUMBER 10.0
#define ANTIALIAS_AMOUNT 2
//Function that returns a complex number to power of 5
vec2 complexPower5(vec2 c)
{
vec2 cRes = c;
for(int i = 1; i < 5; i++)
{
//Multiply the result by the original complex number
vec2 cResCopy = cRes;
cRes.x = (c.x * cResCopy.x) - (c.y * cResCopy.y);
cRes.y = (c.x * cResCopy.y) + (c.y * cResCopy.x);
}
return cRes;
}
//Returns the color of a biomorph at position coord
vec4 colorBiomorph(vec2 coord, vec2 morphConstant)
{
//This part is very similar to crude mandlebrot implementations
vec2 z = coord;
for(int i = 0; i < ITERATIONS_MAX; i++)
{
if((z.x * z.x < EXIT_NUMBER * EXIT_NUMBER) && (z.y * z.y < EXIT_NUMBER * EXIT_NUMBER) && ((z.x * z.x) + (z.y * z.y) < EXIT_NUMBER * EXIT_NUMBER))
{
//z = z^5 + c
z = complexPower5(z) + morphConstant;
}
}
//Unlike mandelbrot and likes this is not colored according to the number of iterations
//it took to reach the exit number, but rather the according to the number itself after
//these iterations
if((z.x * z.x < EXIT_NUMBER * EXIT_NUMBER) || (z.y * z.y < EXIT_NUMBER * EXIT_NUMBER))
{
return vec4(0.0, 0.0, 0.0, 1.0);
}
else
{
return vec4(1.0, 1.0, 1.0, 1.0);
}
}
//Simple multisampling-antialising
//Effectively the same as rendering the thing in a larger resolution and then downscaling
vec4 antiAliasedBiomorph(vec2 uv, vec2 constant)
{
vec4 result = vec4(0.0, 0.0, 0.0, 0.0);
vec2 sampleStep = 1.0 / iResolution.xy / float(ANTIALIAS_AMOUNT + 1);
for(int i = 1; i < ANTIALIAS_AMOUNT + 1; i++)
{
for(int j = 1; j < ANTIALIAS_AMOUNT + 1; j++)
{
vec2 currentPos = uv;
currentPos.x += sampleStep.x * float(i);
currentPos.y += sampleStep.y * float(j);
result += colorBiomorph((currentPos) * 4.0, constant);
}
}
return result / float(ANTIALIAS_AMOUNT * ANTIALIAS_AMOUNT);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.y;
//Position the Biomorph
if(iResolution.x > iResolution.y)
{
uv.x -= 0.5 * (iResolution.x / iResolution.y) - 0.1777;
uv.y -= 0.5;
}
else
{
uv.y -= 0.5 * (iResolution.y / iResolution.x);
uv.x -= 0.3333;
}
//Render the Biomorph
if(iMouse.z < 0.5)
{
fragColor = antiAliasedBiomorph(uv, vec2(0.01 * sin(iTime / 4.0) + 0.15, 0.8));
}
else
{
fragColor = antiAliasedBiomorph(uv, iMouse.xy / iResolution.xy);
}
}
| mit | [
1147,
1202,
1230,
1230,
1509
] | [
[
1147,
1202,
1230,
1230,
1509
],
[
1511,
1563,
1615,
1683,
2423
],
[
2425,
2550,
2600,
2600,
3127
],
[
3129,
3129,
3186,
3186,
3720
]
] | //Function that returns a complex number to power of 5
| vec2 complexPower5(vec2 c)
{ |
vec2 cRes = c;
for(int i = 1; i < 5; i++)
{
//Multiply the result by the original complex number
vec2 cResCopy = cRes;
cRes.x = (c.x * cResCopy.x) - (c.y * cResCopy.y);
cRes.y = (c.x * cResCopy.y) + (c.y * cResCopy.x);
}
return cRes;
} | //Function that returns a complex number to power of 5
vec2 complexPower5(vec2 c)
{ | 1 | 1 |
ltVGWG | vmednis | 2016-10-15T10:36:55 | /*
Copyright (c) 2016 Valters Mednis
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#define ITERATIONS_MAX 100
#define EXIT_NUMBER 10.0
#define ANTIALIAS_AMOUNT 2
//Function that returns a complex number to power of 5
vec2 complexPower5(vec2 c)
{
vec2 cRes = c;
for(int i = 1; i < 5; i++)
{
//Multiply the result by the original complex number
vec2 cResCopy = cRes;
cRes.x = (c.x * cResCopy.x) - (c.y * cResCopy.y);
cRes.y = (c.x * cResCopy.y) + (c.y * cResCopy.x);
}
return cRes;
}
//Returns the color of a biomorph at position coord
vec4 colorBiomorph(vec2 coord, vec2 morphConstant)
{
//This part is very similar to crude mandlebrot implementations
vec2 z = coord;
for(int i = 0; i < ITERATIONS_MAX; i++)
{
if((z.x * z.x < EXIT_NUMBER * EXIT_NUMBER) && (z.y * z.y < EXIT_NUMBER * EXIT_NUMBER) && ((z.x * z.x) + (z.y * z.y) < EXIT_NUMBER * EXIT_NUMBER))
{
//z = z^5 + c
z = complexPower5(z) + morphConstant;
}
}
//Unlike mandelbrot and likes this is not colored according to the number of iterations
//it took to reach the exit number, but rather the according to the number itself after
//these iterations
if((z.x * z.x < EXIT_NUMBER * EXIT_NUMBER) || (z.y * z.y < EXIT_NUMBER * EXIT_NUMBER))
{
return vec4(0.0, 0.0, 0.0, 1.0);
}
else
{
return vec4(1.0, 1.0, 1.0, 1.0);
}
}
//Simple multisampling-antialising
//Effectively the same as rendering the thing in a larger resolution and then downscaling
vec4 antiAliasedBiomorph(vec2 uv, vec2 constant)
{
vec4 result = vec4(0.0, 0.0, 0.0, 0.0);
vec2 sampleStep = 1.0 / iResolution.xy / float(ANTIALIAS_AMOUNT + 1);
for(int i = 1; i < ANTIALIAS_AMOUNT + 1; i++)
{
for(int j = 1; j < ANTIALIAS_AMOUNT + 1; j++)
{
vec2 currentPos = uv;
currentPos.x += sampleStep.x * float(i);
currentPos.y += sampleStep.y * float(j);
result += colorBiomorph((currentPos) * 4.0, constant);
}
}
return result / float(ANTIALIAS_AMOUNT * ANTIALIAS_AMOUNT);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.y;
//Position the Biomorph
if(iResolution.x > iResolution.y)
{
uv.x -= 0.5 * (iResolution.x / iResolution.y) - 0.1777;
uv.y -= 0.5;
}
else
{
uv.y -= 0.5 * (iResolution.y / iResolution.x);
uv.x -= 0.3333;
}
//Render the Biomorph
if(iMouse.z < 0.5)
{
fragColor = antiAliasedBiomorph(uv, vec2(0.01 * sin(iTime / 4.0) + 0.15, 0.8));
}
else
{
fragColor = antiAliasedBiomorph(uv, iMouse.xy / iResolution.xy);
}
}
| mit | [
1511,
1563,
1615,
1683,
2423
] | [
[
1147,
1202,
1230,
1230,
1509
],
[
1511,
1563,
1615,
1683,
2423
],
[
2425,
2550,
2600,
2600,
3127
],
[
3129,
3129,
3186,
3186,
3720
]
] | //Returns the color of a biomorph at position coord
| vec4 colorBiomorph(vec2 coord, vec2 morphConstant)
{ |
vec2 z = coord;
for(int i = 0; i < ITERATIONS_MAX; i++)
{
if((z.x * z.x < EXIT_NUMBER * EXIT_NUMBER) && (z.y * z.y < EXIT_NUMBER * EXIT_NUMBER) && ((z.x * z.x) + (z.y * z.y) < EXIT_NUMBER * EXIT_NUMBER))
{
//z = z^5 + c
z = complexPower5(z) + morphConstant;
}
}
//Unlike mandelbrot and likes this is not colored according to the number of iterations
//it took to reach the exit number, but rather the according to the number itself after
//these iterations
if((z.x * z.x < EXIT_NUMBER * EXIT_NUMBER) || (z.y * z.y < EXIT_NUMBER * EXIT_NUMBER))
{
return vec4(0.0, 0.0, 0.0, 1.0);
}
else
{
return vec4(1.0, 1.0, 1.0, 1.0);
}
} | //Returns the color of a biomorph at position coord
vec4 colorBiomorph(vec2 coord, vec2 morphConstant)
{ | 1 | 1 |
ltVGWG | vmednis | 2016-10-15T10:36:55 | /*
Copyright (c) 2016 Valters Mednis
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#define ITERATIONS_MAX 100
#define EXIT_NUMBER 10.0
#define ANTIALIAS_AMOUNT 2
//Function that returns a complex number to power of 5
vec2 complexPower5(vec2 c)
{
vec2 cRes = c;
for(int i = 1; i < 5; i++)
{
//Multiply the result by the original complex number
vec2 cResCopy = cRes;
cRes.x = (c.x * cResCopy.x) - (c.y * cResCopy.y);
cRes.y = (c.x * cResCopy.y) + (c.y * cResCopy.x);
}
return cRes;
}
//Returns the color of a biomorph at position coord
vec4 colorBiomorph(vec2 coord, vec2 morphConstant)
{
//This part is very similar to crude mandlebrot implementations
vec2 z = coord;
for(int i = 0; i < ITERATIONS_MAX; i++)
{
if((z.x * z.x < EXIT_NUMBER * EXIT_NUMBER) && (z.y * z.y < EXIT_NUMBER * EXIT_NUMBER) && ((z.x * z.x) + (z.y * z.y) < EXIT_NUMBER * EXIT_NUMBER))
{
//z = z^5 + c
z = complexPower5(z) + morphConstant;
}
}
//Unlike mandelbrot and likes this is not colored according to the number of iterations
//it took to reach the exit number, but rather the according to the number itself after
//these iterations
if((z.x * z.x < EXIT_NUMBER * EXIT_NUMBER) || (z.y * z.y < EXIT_NUMBER * EXIT_NUMBER))
{
return vec4(0.0, 0.0, 0.0, 1.0);
}
else
{
return vec4(1.0, 1.0, 1.0, 1.0);
}
}
//Simple multisampling-antialising
//Effectively the same as rendering the thing in a larger resolution and then downscaling
vec4 antiAliasedBiomorph(vec2 uv, vec2 constant)
{
vec4 result = vec4(0.0, 0.0, 0.0, 0.0);
vec2 sampleStep = 1.0 / iResolution.xy / float(ANTIALIAS_AMOUNT + 1);
for(int i = 1; i < ANTIALIAS_AMOUNT + 1; i++)
{
for(int j = 1; j < ANTIALIAS_AMOUNT + 1; j++)
{
vec2 currentPos = uv;
currentPos.x += sampleStep.x * float(i);
currentPos.y += sampleStep.y * float(j);
result += colorBiomorph((currentPos) * 4.0, constant);
}
}
return result / float(ANTIALIAS_AMOUNT * ANTIALIAS_AMOUNT);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 uv = fragCoord.xy / iResolution.y;
//Position the Biomorph
if(iResolution.x > iResolution.y)
{
uv.x -= 0.5 * (iResolution.x / iResolution.y) - 0.1777;
uv.y -= 0.5;
}
else
{
uv.y -= 0.5 * (iResolution.y / iResolution.x);
uv.x -= 0.3333;
}
//Render the Biomorph
if(iMouse.z < 0.5)
{
fragColor = antiAliasedBiomorph(uv, vec2(0.01 * sin(iTime / 4.0) + 0.15, 0.8));
}
else
{
fragColor = antiAliasedBiomorph(uv, iMouse.xy / iResolution.xy);
}
}
| mit | [
2425,
2550,
2600,
2600,
3127
] | [
[
1147,
1202,
1230,
1230,
1509
],
[
1511,
1563,
1615,
1683,
2423
],
[
2425,
2550,
2600,
2600,
3127
],
[
3129,
3129,
3186,
3186,
3720
]
] | //Simple multisampling-antialising
//Effectively the same as rendering the thing in a larger resolution and then downscaling
| vec4 antiAliasedBiomorph(vec2 uv, vec2 constant)
{ |
vec4 result = vec4(0.0, 0.0, 0.0, 0.0);
vec2 sampleStep = 1.0 / iResolution.xy / float(ANTIALIAS_AMOUNT + 1);
for(int i = 1; i < ANTIALIAS_AMOUNT + 1; i++)
{
for(int j = 1; j < ANTIALIAS_AMOUNT + 1; j++)
{
vec2 currentPos = uv;
currentPos.x += sampleStep.x * float(i);
currentPos.y += sampleStep.y * float(j);
result += colorBiomorph((currentPos) * 4.0, constant);
}
}
return result / float(ANTIALIAS_AMOUNT * ANTIALIAS_AMOUNT);
} | //Simple multisampling-antialising
//Effectively the same as rendering the thing in a larger resolution and then downscaling
vec4 antiAliasedBiomorph(vec2 uv, vec2 constant)
{ | 1 | 1 |
4tc3DX | otaviogood | 2016-11-01T07:02:43 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
**************** Glorious Line Algorithm ****************
This is an attempt to solve everything anyone could want from a line in one function.
Glorious features:
- antialiasing
- rectangles, squares, lines, circles, rounded rectangles
- square or rounded endpoints
- outline shapes (might have some bugs still)
- dashed, animated lines
- resolution dependent or independent - some functions work in pixel units, some in UV coordinates.
- efficient
*/
// Clamp [0..1] range
#define saturate(a) clamp(a, 0.0, 1.0)
// Basically a triangle wave
float repeat(float x) { return abs(fract(x*0.5+0.5)-0.5)*2.0; }
// This is it... what you have been waiting for... _The_ Glorious Line Algorithm.
// This function will make a signed distance field that says how far you are from the edge
// of the line at any point U,V.
// Pass it UVs, line end points, line thickness (x is along the line and y is perpendicular),
// How rounded the end points should be (0.0 is rectangular, setting rounded to thick.y will be circular),
// dashOn is just 1.0 or 0.0 to turn on the dashed lines.
float LineDistField(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float dashOn) {
// Don't let it get more round than circular.
rounded = min(thick.y, rounded);
// midpoint
vec2 mid = (pB + pA) * 0.5;
// vector from point A to B
vec2 delta = pB - pA;
// Distance between endpoints
float lenD = length(delta);
// unit vector pointing in the line's direction
vec2 unit = delta / lenD;
// Check for when line endpoints are the same
if (lenD < 0.0001) unit = vec2(1.0, 0.0); // if pA and pB are same
// Perpendicular vector to unit - also length 1.0
vec2 perp = unit.yx * vec2(-1.0, 1.0);
// position along line from midpoint
float dpx = dot(unit, uv - mid);
// distance away from line at a right angle
float dpy = dot(perp, uv - mid);
// Make a distance function that is 0 at the transition from black to white
float disty = abs(dpy) - thick.y + rounded;
float distx = abs(dpx) - lenD * 0.5 - thick.x + rounded;
// Too tired to remember what this does. Something like rounded endpoints for distance function.
float dist = length(vec2(max(0.0, distx), max(0.0,disty))) - rounded;
dist = min(dist, max(distx, disty));
// This is for animated dashed lines. Delete if you don't like dashes.
float dashScale = 2.0*thick.y;
// Make a distance function for the dashes
float dash = (repeat(dpx/dashScale + iTime)-0.5)*dashScale;
// Combine this distance function with the line's.
dist = max(dist, dash-(1.0-dashOn*1.0)*10000.0);
return dist;
}
// This makes a filled line in pixel units. A 1.0 thick line will be 1 pixel thick.
float FillLinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / scale);
}
// This makes an outlined line in pixel units. A 1.0 thick outline will be 1 pixel thick.
float DrawOutlinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
rounded = (rounded * 0.5 - 0.5) * scale;
outlineThick = (outlineThick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / scale);
}
// This makes a line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLine(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes a dashed line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLineDash(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 1.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes an outlined line in UV units. A 1.0 thick outline will span 0..1 in UV space.
float DrawOutline(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / abs(dFdy(uv).y));
}
// This just draws a point for debugging using a different technique that is less glorious.
void DrawPoint(vec2 uv, vec2 p, inout vec3 col) {
col = mix(col, vec3(1.0, 0.25, 0.25), saturate(abs(dFdy(uv).y)*8.0/distance(uv, p)-4.0));
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// Adjust UV space so it's a nice size and square.
vec2 uv = fragCoord.xy / iResolution.xy;
uv -= 0.5;
uv.x *= iResolution.x / iResolution.y;
uv *= 16.0;
// Make things that rotate with time.
vec2 rotA = vec2(cos(iTime*0.82), sin(iTime*0.82));
vec2 rotB = vec2(sin(iTime*0.82), -cos(iTime*0.82));
// Make a bunch of line endpoints to use.
vec2 pA = vec2(-4.0, 0.0) - rotA;
vec2 pB = vec2(4.0, 0.0) + rotA;
vec2 pC = pA + vec2(0.0, 4.0);
vec2 pD = pB + vec2(0.0, 4.0);
// Debugging code
//float df = LineDistField(uv, pA, pB, vec2(28.0 * dFdy(uv).y), 0.1, 0.0);
//float df = DistField(uv, pA, pB, 25.000625 * dFdx(uv).x, 0.5);
//vec3 finalColor = vec3(df*1.0, -df*1.0, 0.0);
//finalColor = vec3(1.0) * saturate(df / dFdy(uv).y);
//finalColor = vec3(1.0) * saturate((abs(df+0.009)-0.009) / dFdy(uv).y);
// Clear to white.
vec3 finalColor = vec3(1.0);
// Lots of sample lines
// 1 pixel thick regardless of screen scale.
finalColor *= FillLinePix(uv, pA, pB, vec2(1.0, 1.0), 0.0);
// Rounded rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(32.0), 16.0, 1.0);
// square-cornered rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(64.0), 0.0, 1.0);
// Fully rounded endpoint with outline 8 pixels thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(128.0), 128.0, 8.0);
// Dashed line with rectangular endpoints that touch pC and pD, 0.5 radius thickness in UV units
finalColor *= FillLineDash(uv, pC, pD, vec2(0.0, 0.5), 0.0);
// Rounded endpoint dashed line with radius 0.125 in UV units
finalColor *= FillLineDash(uv, pC + vec2(0.0, 2.0), pD + vec2(0.0, 2.0), vec2(0.125), 1.0);
finalColor *= DrawOutline(uv, (pA + pB) * 0.5 + vec2(0.0, -4.5), (pA + pB) * 0.5 + vec2(0.0, -4.5), vec2(2.0, 2.0), 2.0, 0.8);
finalColor *= FillLine(uv, pA - vec2(4.0, 0.0), pC - vec2(4.0, 0.0)+rotA, vec2(0.125), 1.0);
finalColor *= FillLine(uv, pB + vec2(4.0, 0.0), pD + vec2(4.0, 0.0)-rotA, vec2(0.125), 1.0);
DrawPoint(uv, pA, finalColor);
DrawPoint(uv, pB, finalColor);
DrawPoint(uv, pC, finalColor);
DrawPoint(uv, pD, finalColor);
// Blue grid lines
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.x*2.0) - 0.92)*4.0;
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.y*2.0) - 0.92)*4.0;
//finalColor *= saturate(mod(fragCoord.y + 0.5, 2.0) + mod(fragCoord.x + 0.5, 2.0));
fragColor = vec4(sqrt(saturate(finalColor)), 1.0);
}
| cc0-1.0 | [
1074,
1103,
1126,
1126,
1166
] | [
[
1074,
1103,
1126,
1126,
1166
],
[
1168,
1633,
1722,
1772,
3200
],
[
3202,
3286,
3359,
3359,
3539
],
[
3541,
3631,
3727,
3727,
4044
],
[
4046,
4133,
4203,
4203,
4317
],
[
4319,
4413,
4487,
4487,
4601
],
[
4603,
4695,
4788,
4788,
4939
],
[
4941,
5033,
5082,
5082,
5178
],
[
5180,
5180,
5237,
5292,
7805
]
] | // Basically a triangle wave
| float repeat(float x) { | return abs(fract(x*0.5+0.5)-0.5)*2.0; } | // Basically a triangle wave
float repeat(float x) { | 1 | 1 |
4tc3DX | otaviogood | 2016-11-01T07:02:43 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
**************** Glorious Line Algorithm ****************
This is an attempt to solve everything anyone could want from a line in one function.
Glorious features:
- antialiasing
- rectangles, squares, lines, circles, rounded rectangles
- square or rounded endpoints
- outline shapes (might have some bugs still)
- dashed, animated lines
- resolution dependent or independent - some functions work in pixel units, some in UV coordinates.
- efficient
*/
// Clamp [0..1] range
#define saturate(a) clamp(a, 0.0, 1.0)
// Basically a triangle wave
float repeat(float x) { return abs(fract(x*0.5+0.5)-0.5)*2.0; }
// This is it... what you have been waiting for... _The_ Glorious Line Algorithm.
// This function will make a signed distance field that says how far you are from the edge
// of the line at any point U,V.
// Pass it UVs, line end points, line thickness (x is along the line and y is perpendicular),
// How rounded the end points should be (0.0 is rectangular, setting rounded to thick.y will be circular),
// dashOn is just 1.0 or 0.0 to turn on the dashed lines.
float LineDistField(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float dashOn) {
// Don't let it get more round than circular.
rounded = min(thick.y, rounded);
// midpoint
vec2 mid = (pB + pA) * 0.5;
// vector from point A to B
vec2 delta = pB - pA;
// Distance between endpoints
float lenD = length(delta);
// unit vector pointing in the line's direction
vec2 unit = delta / lenD;
// Check for when line endpoints are the same
if (lenD < 0.0001) unit = vec2(1.0, 0.0); // if pA and pB are same
// Perpendicular vector to unit - also length 1.0
vec2 perp = unit.yx * vec2(-1.0, 1.0);
// position along line from midpoint
float dpx = dot(unit, uv - mid);
// distance away from line at a right angle
float dpy = dot(perp, uv - mid);
// Make a distance function that is 0 at the transition from black to white
float disty = abs(dpy) - thick.y + rounded;
float distx = abs(dpx) - lenD * 0.5 - thick.x + rounded;
// Too tired to remember what this does. Something like rounded endpoints for distance function.
float dist = length(vec2(max(0.0, distx), max(0.0,disty))) - rounded;
dist = min(dist, max(distx, disty));
// This is for animated dashed lines. Delete if you don't like dashes.
float dashScale = 2.0*thick.y;
// Make a distance function for the dashes
float dash = (repeat(dpx/dashScale + iTime)-0.5)*dashScale;
// Combine this distance function with the line's.
dist = max(dist, dash-(1.0-dashOn*1.0)*10000.0);
return dist;
}
// This makes a filled line in pixel units. A 1.0 thick line will be 1 pixel thick.
float FillLinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / scale);
}
// This makes an outlined line in pixel units. A 1.0 thick outline will be 1 pixel thick.
float DrawOutlinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
rounded = (rounded * 0.5 - 0.5) * scale;
outlineThick = (outlineThick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / scale);
}
// This makes a line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLine(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes a dashed line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLineDash(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 1.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes an outlined line in UV units. A 1.0 thick outline will span 0..1 in UV space.
float DrawOutline(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / abs(dFdy(uv).y));
}
// This just draws a point for debugging using a different technique that is less glorious.
void DrawPoint(vec2 uv, vec2 p, inout vec3 col) {
col = mix(col, vec3(1.0, 0.25, 0.25), saturate(abs(dFdy(uv).y)*8.0/distance(uv, p)-4.0));
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// Adjust UV space so it's a nice size and square.
vec2 uv = fragCoord.xy / iResolution.xy;
uv -= 0.5;
uv.x *= iResolution.x / iResolution.y;
uv *= 16.0;
// Make things that rotate with time.
vec2 rotA = vec2(cos(iTime*0.82), sin(iTime*0.82));
vec2 rotB = vec2(sin(iTime*0.82), -cos(iTime*0.82));
// Make a bunch of line endpoints to use.
vec2 pA = vec2(-4.0, 0.0) - rotA;
vec2 pB = vec2(4.0, 0.0) + rotA;
vec2 pC = pA + vec2(0.0, 4.0);
vec2 pD = pB + vec2(0.0, 4.0);
// Debugging code
//float df = LineDistField(uv, pA, pB, vec2(28.0 * dFdy(uv).y), 0.1, 0.0);
//float df = DistField(uv, pA, pB, 25.000625 * dFdx(uv).x, 0.5);
//vec3 finalColor = vec3(df*1.0, -df*1.0, 0.0);
//finalColor = vec3(1.0) * saturate(df / dFdy(uv).y);
//finalColor = vec3(1.0) * saturate((abs(df+0.009)-0.009) / dFdy(uv).y);
// Clear to white.
vec3 finalColor = vec3(1.0);
// Lots of sample lines
// 1 pixel thick regardless of screen scale.
finalColor *= FillLinePix(uv, pA, pB, vec2(1.0, 1.0), 0.0);
// Rounded rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(32.0), 16.0, 1.0);
// square-cornered rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(64.0), 0.0, 1.0);
// Fully rounded endpoint with outline 8 pixels thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(128.0), 128.0, 8.0);
// Dashed line with rectangular endpoints that touch pC and pD, 0.5 radius thickness in UV units
finalColor *= FillLineDash(uv, pC, pD, vec2(0.0, 0.5), 0.0);
// Rounded endpoint dashed line with radius 0.125 in UV units
finalColor *= FillLineDash(uv, pC + vec2(0.0, 2.0), pD + vec2(0.0, 2.0), vec2(0.125), 1.0);
finalColor *= DrawOutline(uv, (pA + pB) * 0.5 + vec2(0.0, -4.5), (pA + pB) * 0.5 + vec2(0.0, -4.5), vec2(2.0, 2.0), 2.0, 0.8);
finalColor *= FillLine(uv, pA - vec2(4.0, 0.0), pC - vec2(4.0, 0.0)+rotA, vec2(0.125), 1.0);
finalColor *= FillLine(uv, pB + vec2(4.0, 0.0), pD + vec2(4.0, 0.0)-rotA, vec2(0.125), 1.0);
DrawPoint(uv, pA, finalColor);
DrawPoint(uv, pB, finalColor);
DrawPoint(uv, pC, finalColor);
DrawPoint(uv, pD, finalColor);
// Blue grid lines
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.x*2.0) - 0.92)*4.0;
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.y*2.0) - 0.92)*4.0;
//finalColor *= saturate(mod(fragCoord.y + 0.5, 2.0) + mod(fragCoord.x + 0.5, 2.0));
fragColor = vec4(sqrt(saturate(finalColor)), 1.0);
}
| cc0-1.0 | [
1168,
1633,
1722,
1772,
3200
] | [
[
1074,
1103,
1126,
1126,
1166
],
[
1168,
1633,
1722,
1772,
3200
],
[
3202,
3286,
3359,
3359,
3539
],
[
3541,
3631,
3727,
3727,
4044
],
[
4046,
4133,
4203,
4203,
4317
],
[
4319,
4413,
4487,
4487,
4601
],
[
4603,
4695,
4788,
4788,
4939
],
[
4941,
5033,
5082,
5082,
5178
],
[
5180,
5180,
5237,
5292,
7805
]
] | // This is it... what you have been waiting for... _The_ Glorious Line Algorithm.
// This function will make a signed distance field that says how far you are from the edge
// of the line at any point U,V.
// Pass it UVs, line end points, line thickness (x is along the line and y is perpendicular),
// How rounded the end points should be (0.0 is rectangular, setting rounded to thick.y will be circular),
// dashOn is just 1.0 or 0.0 to turn on the dashed lines.
| float LineDistField(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float dashOn) { |
rounded = min(thick.y, rounded);
// midpoint
vec2 mid = (pB + pA) * 0.5;
// vector from point A to B
vec2 delta = pB - pA;
// Distance between endpoints
float lenD = length(delta);
// unit vector pointing in the line's direction
vec2 unit = delta / lenD;
// Check for when line endpoints are the same
if (lenD < 0.0001) unit = vec2(1.0, 0.0); // if pA and pB are same
// Perpendicular vector to unit - also length 1.0
vec2 perp = unit.yx * vec2(-1.0, 1.0);
// position along line from midpoint
float dpx = dot(unit, uv - mid);
// distance away from line at a right angle
float dpy = dot(perp, uv - mid);
// Make a distance function that is 0 at the transition from black to white
float disty = abs(dpy) - thick.y + rounded;
float distx = abs(dpx) - lenD * 0.5 - thick.x + rounded;
// Too tired to remember what this does. Something like rounded endpoints for distance function.
float dist = length(vec2(max(0.0, distx), max(0.0,disty))) - rounded;
dist = min(dist, max(distx, disty));
// This is for animated dashed lines. Delete if you don't like dashes.
float dashScale = 2.0*thick.y;
// Make a distance function for the dashes
float dash = (repeat(dpx/dashScale + iTime)-0.5)*dashScale;
// Combine this distance function with the line's.
dist = max(dist, dash-(1.0-dashOn*1.0)*10000.0);
return dist;
} | // This is it... what you have been waiting for... _The_ Glorious Line Algorithm.
// This function will make a signed distance field that says how far you are from the edge
// of the line at any point U,V.
// Pass it UVs, line end points, line thickness (x is along the line and y is perpendicular),
// How rounded the end points should be (0.0 is rectangular, setting rounded to thick.y will be circular),
// dashOn is just 1.0 or 0.0 to turn on the dashed lines.
float LineDistField(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float dashOn) { | 1 | 2 |
4tc3DX | otaviogood | 2016-11-01T07:02:43 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
**************** Glorious Line Algorithm ****************
This is an attempt to solve everything anyone could want from a line in one function.
Glorious features:
- antialiasing
- rectangles, squares, lines, circles, rounded rectangles
- square or rounded endpoints
- outline shapes (might have some bugs still)
- dashed, animated lines
- resolution dependent or independent - some functions work in pixel units, some in UV coordinates.
- efficient
*/
// Clamp [0..1] range
#define saturate(a) clamp(a, 0.0, 1.0)
// Basically a triangle wave
float repeat(float x) { return abs(fract(x*0.5+0.5)-0.5)*2.0; }
// This is it... what you have been waiting for... _The_ Glorious Line Algorithm.
// This function will make a signed distance field that says how far you are from the edge
// of the line at any point U,V.
// Pass it UVs, line end points, line thickness (x is along the line and y is perpendicular),
// How rounded the end points should be (0.0 is rectangular, setting rounded to thick.y will be circular),
// dashOn is just 1.0 or 0.0 to turn on the dashed lines.
float LineDistField(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float dashOn) {
// Don't let it get more round than circular.
rounded = min(thick.y, rounded);
// midpoint
vec2 mid = (pB + pA) * 0.5;
// vector from point A to B
vec2 delta = pB - pA;
// Distance between endpoints
float lenD = length(delta);
// unit vector pointing in the line's direction
vec2 unit = delta / lenD;
// Check for when line endpoints are the same
if (lenD < 0.0001) unit = vec2(1.0, 0.0); // if pA and pB are same
// Perpendicular vector to unit - also length 1.0
vec2 perp = unit.yx * vec2(-1.0, 1.0);
// position along line from midpoint
float dpx = dot(unit, uv - mid);
// distance away from line at a right angle
float dpy = dot(perp, uv - mid);
// Make a distance function that is 0 at the transition from black to white
float disty = abs(dpy) - thick.y + rounded;
float distx = abs(dpx) - lenD * 0.5 - thick.x + rounded;
// Too tired to remember what this does. Something like rounded endpoints for distance function.
float dist = length(vec2(max(0.0, distx), max(0.0,disty))) - rounded;
dist = min(dist, max(distx, disty));
// This is for animated dashed lines. Delete if you don't like dashes.
float dashScale = 2.0*thick.y;
// Make a distance function for the dashes
float dash = (repeat(dpx/dashScale + iTime)-0.5)*dashScale;
// Combine this distance function with the line's.
dist = max(dist, dash-(1.0-dashOn*1.0)*10000.0);
return dist;
}
// This makes a filled line in pixel units. A 1.0 thick line will be 1 pixel thick.
float FillLinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / scale);
}
// This makes an outlined line in pixel units. A 1.0 thick outline will be 1 pixel thick.
float DrawOutlinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
rounded = (rounded * 0.5 - 0.5) * scale;
outlineThick = (outlineThick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / scale);
}
// This makes a line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLine(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes a dashed line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLineDash(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 1.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes an outlined line in UV units. A 1.0 thick outline will span 0..1 in UV space.
float DrawOutline(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / abs(dFdy(uv).y));
}
// This just draws a point for debugging using a different technique that is less glorious.
void DrawPoint(vec2 uv, vec2 p, inout vec3 col) {
col = mix(col, vec3(1.0, 0.25, 0.25), saturate(abs(dFdy(uv).y)*8.0/distance(uv, p)-4.0));
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// Adjust UV space so it's a nice size and square.
vec2 uv = fragCoord.xy / iResolution.xy;
uv -= 0.5;
uv.x *= iResolution.x / iResolution.y;
uv *= 16.0;
// Make things that rotate with time.
vec2 rotA = vec2(cos(iTime*0.82), sin(iTime*0.82));
vec2 rotB = vec2(sin(iTime*0.82), -cos(iTime*0.82));
// Make a bunch of line endpoints to use.
vec2 pA = vec2(-4.0, 0.0) - rotA;
vec2 pB = vec2(4.0, 0.0) + rotA;
vec2 pC = pA + vec2(0.0, 4.0);
vec2 pD = pB + vec2(0.0, 4.0);
// Debugging code
//float df = LineDistField(uv, pA, pB, vec2(28.0 * dFdy(uv).y), 0.1, 0.0);
//float df = DistField(uv, pA, pB, 25.000625 * dFdx(uv).x, 0.5);
//vec3 finalColor = vec3(df*1.0, -df*1.0, 0.0);
//finalColor = vec3(1.0) * saturate(df / dFdy(uv).y);
//finalColor = vec3(1.0) * saturate((abs(df+0.009)-0.009) / dFdy(uv).y);
// Clear to white.
vec3 finalColor = vec3(1.0);
// Lots of sample lines
// 1 pixel thick regardless of screen scale.
finalColor *= FillLinePix(uv, pA, pB, vec2(1.0, 1.0), 0.0);
// Rounded rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(32.0), 16.0, 1.0);
// square-cornered rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(64.0), 0.0, 1.0);
// Fully rounded endpoint with outline 8 pixels thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(128.0), 128.0, 8.0);
// Dashed line with rectangular endpoints that touch pC and pD, 0.5 radius thickness in UV units
finalColor *= FillLineDash(uv, pC, pD, vec2(0.0, 0.5), 0.0);
// Rounded endpoint dashed line with radius 0.125 in UV units
finalColor *= FillLineDash(uv, pC + vec2(0.0, 2.0), pD + vec2(0.0, 2.0), vec2(0.125), 1.0);
finalColor *= DrawOutline(uv, (pA + pB) * 0.5 + vec2(0.0, -4.5), (pA + pB) * 0.5 + vec2(0.0, -4.5), vec2(2.0, 2.0), 2.0, 0.8);
finalColor *= FillLine(uv, pA - vec2(4.0, 0.0), pC - vec2(4.0, 0.0)+rotA, vec2(0.125), 1.0);
finalColor *= FillLine(uv, pB + vec2(4.0, 0.0), pD + vec2(4.0, 0.0)-rotA, vec2(0.125), 1.0);
DrawPoint(uv, pA, finalColor);
DrawPoint(uv, pB, finalColor);
DrawPoint(uv, pC, finalColor);
DrawPoint(uv, pD, finalColor);
// Blue grid lines
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.x*2.0) - 0.92)*4.0;
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.y*2.0) - 0.92)*4.0;
//finalColor *= saturate(mod(fragCoord.y + 0.5, 2.0) + mod(fragCoord.x + 0.5, 2.0));
fragColor = vec4(sqrt(saturate(finalColor)), 1.0);
}
| cc0-1.0 | [
3202,
3286,
3359,
3359,
3539
] | [
[
1074,
1103,
1126,
1126,
1166
],
[
1168,
1633,
1722,
1772,
3200
],
[
3202,
3286,
3359,
3359,
3539
],
[
3541,
3631,
3727,
3727,
4044
],
[
4046,
4133,
4203,
4203,
4317
],
[
4319,
4413,
4487,
4487,
4601
],
[
4603,
4695,
4788,
4788,
4939
],
[
4941,
5033,
5082,
5082,
5178
],
[
5180,
5180,
5237,
5292,
7805
]
] | // This makes a filled line in pixel units. A 1.0 thick line will be 1 pixel thick.
| float FillLinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) { |
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / scale);
} | // This makes a filled line in pixel units. A 1.0 thick line will be 1 pixel thick.
float FillLinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) { | 1 | 1 |
4tc3DX | otaviogood | 2016-11-01T07:02:43 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
**************** Glorious Line Algorithm ****************
This is an attempt to solve everything anyone could want from a line in one function.
Glorious features:
- antialiasing
- rectangles, squares, lines, circles, rounded rectangles
- square or rounded endpoints
- outline shapes (might have some bugs still)
- dashed, animated lines
- resolution dependent or independent - some functions work in pixel units, some in UV coordinates.
- efficient
*/
// Clamp [0..1] range
#define saturate(a) clamp(a, 0.0, 1.0)
// Basically a triangle wave
float repeat(float x) { return abs(fract(x*0.5+0.5)-0.5)*2.0; }
// This is it... what you have been waiting for... _The_ Glorious Line Algorithm.
// This function will make a signed distance field that says how far you are from the edge
// of the line at any point U,V.
// Pass it UVs, line end points, line thickness (x is along the line and y is perpendicular),
// How rounded the end points should be (0.0 is rectangular, setting rounded to thick.y will be circular),
// dashOn is just 1.0 or 0.0 to turn on the dashed lines.
float LineDistField(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float dashOn) {
// Don't let it get more round than circular.
rounded = min(thick.y, rounded);
// midpoint
vec2 mid = (pB + pA) * 0.5;
// vector from point A to B
vec2 delta = pB - pA;
// Distance between endpoints
float lenD = length(delta);
// unit vector pointing in the line's direction
vec2 unit = delta / lenD;
// Check for when line endpoints are the same
if (lenD < 0.0001) unit = vec2(1.0, 0.0); // if pA and pB are same
// Perpendicular vector to unit - also length 1.0
vec2 perp = unit.yx * vec2(-1.0, 1.0);
// position along line from midpoint
float dpx = dot(unit, uv - mid);
// distance away from line at a right angle
float dpy = dot(perp, uv - mid);
// Make a distance function that is 0 at the transition from black to white
float disty = abs(dpy) - thick.y + rounded;
float distx = abs(dpx) - lenD * 0.5 - thick.x + rounded;
// Too tired to remember what this does. Something like rounded endpoints for distance function.
float dist = length(vec2(max(0.0, distx), max(0.0,disty))) - rounded;
dist = min(dist, max(distx, disty));
// This is for animated dashed lines. Delete if you don't like dashes.
float dashScale = 2.0*thick.y;
// Make a distance function for the dashes
float dash = (repeat(dpx/dashScale + iTime)-0.5)*dashScale;
// Combine this distance function with the line's.
dist = max(dist, dash-(1.0-dashOn*1.0)*10000.0);
return dist;
}
// This makes a filled line in pixel units. A 1.0 thick line will be 1 pixel thick.
float FillLinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / scale);
}
// This makes an outlined line in pixel units. A 1.0 thick outline will be 1 pixel thick.
float DrawOutlinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
rounded = (rounded * 0.5 - 0.5) * scale;
outlineThick = (outlineThick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / scale);
}
// This makes a line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLine(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes a dashed line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLineDash(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 1.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes an outlined line in UV units. A 1.0 thick outline will span 0..1 in UV space.
float DrawOutline(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / abs(dFdy(uv).y));
}
// This just draws a point for debugging using a different technique that is less glorious.
void DrawPoint(vec2 uv, vec2 p, inout vec3 col) {
col = mix(col, vec3(1.0, 0.25, 0.25), saturate(abs(dFdy(uv).y)*8.0/distance(uv, p)-4.0));
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// Adjust UV space so it's a nice size and square.
vec2 uv = fragCoord.xy / iResolution.xy;
uv -= 0.5;
uv.x *= iResolution.x / iResolution.y;
uv *= 16.0;
// Make things that rotate with time.
vec2 rotA = vec2(cos(iTime*0.82), sin(iTime*0.82));
vec2 rotB = vec2(sin(iTime*0.82), -cos(iTime*0.82));
// Make a bunch of line endpoints to use.
vec2 pA = vec2(-4.0, 0.0) - rotA;
vec2 pB = vec2(4.0, 0.0) + rotA;
vec2 pC = pA + vec2(0.0, 4.0);
vec2 pD = pB + vec2(0.0, 4.0);
// Debugging code
//float df = LineDistField(uv, pA, pB, vec2(28.0 * dFdy(uv).y), 0.1, 0.0);
//float df = DistField(uv, pA, pB, 25.000625 * dFdx(uv).x, 0.5);
//vec3 finalColor = vec3(df*1.0, -df*1.0, 0.0);
//finalColor = vec3(1.0) * saturate(df / dFdy(uv).y);
//finalColor = vec3(1.0) * saturate((abs(df+0.009)-0.009) / dFdy(uv).y);
// Clear to white.
vec3 finalColor = vec3(1.0);
// Lots of sample lines
// 1 pixel thick regardless of screen scale.
finalColor *= FillLinePix(uv, pA, pB, vec2(1.0, 1.0), 0.0);
// Rounded rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(32.0), 16.0, 1.0);
// square-cornered rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(64.0), 0.0, 1.0);
// Fully rounded endpoint with outline 8 pixels thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(128.0), 128.0, 8.0);
// Dashed line with rectangular endpoints that touch pC and pD, 0.5 radius thickness in UV units
finalColor *= FillLineDash(uv, pC, pD, vec2(0.0, 0.5), 0.0);
// Rounded endpoint dashed line with radius 0.125 in UV units
finalColor *= FillLineDash(uv, pC + vec2(0.0, 2.0), pD + vec2(0.0, 2.0), vec2(0.125), 1.0);
finalColor *= DrawOutline(uv, (pA + pB) * 0.5 + vec2(0.0, -4.5), (pA + pB) * 0.5 + vec2(0.0, -4.5), vec2(2.0, 2.0), 2.0, 0.8);
finalColor *= FillLine(uv, pA - vec2(4.0, 0.0), pC - vec2(4.0, 0.0)+rotA, vec2(0.125), 1.0);
finalColor *= FillLine(uv, pB + vec2(4.0, 0.0), pD + vec2(4.0, 0.0)-rotA, vec2(0.125), 1.0);
DrawPoint(uv, pA, finalColor);
DrawPoint(uv, pB, finalColor);
DrawPoint(uv, pC, finalColor);
DrawPoint(uv, pD, finalColor);
// Blue grid lines
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.x*2.0) - 0.92)*4.0;
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.y*2.0) - 0.92)*4.0;
//finalColor *= saturate(mod(fragCoord.y + 0.5, 2.0) + mod(fragCoord.x + 0.5, 2.0));
fragColor = vec4(sqrt(saturate(finalColor)), 1.0);
}
| cc0-1.0 | [
3541,
3631,
3727,
3727,
4044
] | [
[
1074,
1103,
1126,
1126,
1166
],
[
1168,
1633,
1722,
1772,
3200
],
[
3202,
3286,
3359,
3359,
3539
],
[
3541,
3631,
3727,
3727,
4044
],
[
4046,
4133,
4203,
4203,
4317
],
[
4319,
4413,
4487,
4487,
4601
],
[
4603,
4695,
4788,
4788,
4939
],
[
4941,
5033,
5082,
5082,
5178
],
[
5180,
5180,
5237,
5292,
7805
]
] | // This makes an outlined line in pixel units. A 1.0 thick outline will be 1 pixel thick.
| float DrawOutlinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) { |
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
rounded = (rounded * 0.5 - 0.5) * scale;
outlineThick = (outlineThick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / scale);
} | // This makes an outlined line in pixel units. A 1.0 thick outline will be 1 pixel thick.
float DrawOutlinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) { | 1 | 1 |
4tc3DX | otaviogood | 2016-11-01T07:02:43 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
**************** Glorious Line Algorithm ****************
This is an attempt to solve everything anyone could want from a line in one function.
Glorious features:
- antialiasing
- rectangles, squares, lines, circles, rounded rectangles
- square or rounded endpoints
- outline shapes (might have some bugs still)
- dashed, animated lines
- resolution dependent or independent - some functions work in pixel units, some in UV coordinates.
- efficient
*/
// Clamp [0..1] range
#define saturate(a) clamp(a, 0.0, 1.0)
// Basically a triangle wave
float repeat(float x) { return abs(fract(x*0.5+0.5)-0.5)*2.0; }
// This is it... what you have been waiting for... _The_ Glorious Line Algorithm.
// This function will make a signed distance field that says how far you are from the edge
// of the line at any point U,V.
// Pass it UVs, line end points, line thickness (x is along the line and y is perpendicular),
// How rounded the end points should be (0.0 is rectangular, setting rounded to thick.y will be circular),
// dashOn is just 1.0 or 0.0 to turn on the dashed lines.
float LineDistField(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float dashOn) {
// Don't let it get more round than circular.
rounded = min(thick.y, rounded);
// midpoint
vec2 mid = (pB + pA) * 0.5;
// vector from point A to B
vec2 delta = pB - pA;
// Distance between endpoints
float lenD = length(delta);
// unit vector pointing in the line's direction
vec2 unit = delta / lenD;
// Check for when line endpoints are the same
if (lenD < 0.0001) unit = vec2(1.0, 0.0); // if pA and pB are same
// Perpendicular vector to unit - also length 1.0
vec2 perp = unit.yx * vec2(-1.0, 1.0);
// position along line from midpoint
float dpx = dot(unit, uv - mid);
// distance away from line at a right angle
float dpy = dot(perp, uv - mid);
// Make a distance function that is 0 at the transition from black to white
float disty = abs(dpy) - thick.y + rounded;
float distx = abs(dpx) - lenD * 0.5 - thick.x + rounded;
// Too tired to remember what this does. Something like rounded endpoints for distance function.
float dist = length(vec2(max(0.0, distx), max(0.0,disty))) - rounded;
dist = min(dist, max(distx, disty));
// This is for animated dashed lines. Delete if you don't like dashes.
float dashScale = 2.0*thick.y;
// Make a distance function for the dashes
float dash = (repeat(dpx/dashScale + iTime)-0.5)*dashScale;
// Combine this distance function with the line's.
dist = max(dist, dash-(1.0-dashOn*1.0)*10000.0);
return dist;
}
// This makes a filled line in pixel units. A 1.0 thick line will be 1 pixel thick.
float FillLinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / scale);
}
// This makes an outlined line in pixel units. A 1.0 thick outline will be 1 pixel thick.
float DrawOutlinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
rounded = (rounded * 0.5 - 0.5) * scale;
outlineThick = (outlineThick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / scale);
}
// This makes a line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLine(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes a dashed line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLineDash(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 1.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes an outlined line in UV units. A 1.0 thick outline will span 0..1 in UV space.
float DrawOutline(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / abs(dFdy(uv).y));
}
// This just draws a point for debugging using a different technique that is less glorious.
void DrawPoint(vec2 uv, vec2 p, inout vec3 col) {
col = mix(col, vec3(1.0, 0.25, 0.25), saturate(abs(dFdy(uv).y)*8.0/distance(uv, p)-4.0));
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// Adjust UV space so it's a nice size and square.
vec2 uv = fragCoord.xy / iResolution.xy;
uv -= 0.5;
uv.x *= iResolution.x / iResolution.y;
uv *= 16.0;
// Make things that rotate with time.
vec2 rotA = vec2(cos(iTime*0.82), sin(iTime*0.82));
vec2 rotB = vec2(sin(iTime*0.82), -cos(iTime*0.82));
// Make a bunch of line endpoints to use.
vec2 pA = vec2(-4.0, 0.0) - rotA;
vec2 pB = vec2(4.0, 0.0) + rotA;
vec2 pC = pA + vec2(0.0, 4.0);
vec2 pD = pB + vec2(0.0, 4.0);
// Debugging code
//float df = LineDistField(uv, pA, pB, vec2(28.0 * dFdy(uv).y), 0.1, 0.0);
//float df = DistField(uv, pA, pB, 25.000625 * dFdx(uv).x, 0.5);
//vec3 finalColor = vec3(df*1.0, -df*1.0, 0.0);
//finalColor = vec3(1.0) * saturate(df / dFdy(uv).y);
//finalColor = vec3(1.0) * saturate((abs(df+0.009)-0.009) / dFdy(uv).y);
// Clear to white.
vec3 finalColor = vec3(1.0);
// Lots of sample lines
// 1 pixel thick regardless of screen scale.
finalColor *= FillLinePix(uv, pA, pB, vec2(1.0, 1.0), 0.0);
// Rounded rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(32.0), 16.0, 1.0);
// square-cornered rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(64.0), 0.0, 1.0);
// Fully rounded endpoint with outline 8 pixels thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(128.0), 128.0, 8.0);
// Dashed line with rectangular endpoints that touch pC and pD, 0.5 radius thickness in UV units
finalColor *= FillLineDash(uv, pC, pD, vec2(0.0, 0.5), 0.0);
// Rounded endpoint dashed line with radius 0.125 in UV units
finalColor *= FillLineDash(uv, pC + vec2(0.0, 2.0), pD + vec2(0.0, 2.0), vec2(0.125), 1.0);
finalColor *= DrawOutline(uv, (pA + pB) * 0.5 + vec2(0.0, -4.5), (pA + pB) * 0.5 + vec2(0.0, -4.5), vec2(2.0, 2.0), 2.0, 0.8);
finalColor *= FillLine(uv, pA - vec2(4.0, 0.0), pC - vec2(4.0, 0.0)+rotA, vec2(0.125), 1.0);
finalColor *= FillLine(uv, pB + vec2(4.0, 0.0), pD + vec2(4.0, 0.0)-rotA, vec2(0.125), 1.0);
DrawPoint(uv, pA, finalColor);
DrawPoint(uv, pB, finalColor);
DrawPoint(uv, pC, finalColor);
DrawPoint(uv, pD, finalColor);
// Blue grid lines
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.x*2.0) - 0.92)*4.0;
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.y*2.0) - 0.92)*4.0;
//finalColor *= saturate(mod(fragCoord.y + 0.5, 2.0) + mod(fragCoord.x + 0.5, 2.0));
fragColor = vec4(sqrt(saturate(finalColor)), 1.0);
}
| cc0-1.0 | [
4046,
4133,
4203,
4203,
4317
] | [
[
1074,
1103,
1126,
1126,
1166
],
[
1168,
1633,
1722,
1772,
3200
],
[
3202,
3286,
3359,
3359,
3539
],
[
3541,
3631,
3727,
3727,
4044
],
[
4046,
4133,
4203,
4203,
4317
],
[
4319,
4413,
4487,
4487,
4601
],
[
4603,
4695,
4788,
4788,
4939
],
[
4941,
5033,
5082,
5082,
5178
],
[
5180,
5180,
5237,
5292,
7805
]
] | // This makes a line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
| float FillLine(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) { |
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / abs(dFdy(uv).y));
} | // This makes a line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLine(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) { | 1 | 1 |
4tc3DX | otaviogood | 2016-11-01T07:02:43 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
**************** Glorious Line Algorithm ****************
This is an attempt to solve everything anyone could want from a line in one function.
Glorious features:
- antialiasing
- rectangles, squares, lines, circles, rounded rectangles
- square or rounded endpoints
- outline shapes (might have some bugs still)
- dashed, animated lines
- resolution dependent or independent - some functions work in pixel units, some in UV coordinates.
- efficient
*/
// Clamp [0..1] range
#define saturate(a) clamp(a, 0.0, 1.0)
// Basically a triangle wave
float repeat(float x) { return abs(fract(x*0.5+0.5)-0.5)*2.0; }
// This is it... what you have been waiting for... _The_ Glorious Line Algorithm.
// This function will make a signed distance field that says how far you are from the edge
// of the line at any point U,V.
// Pass it UVs, line end points, line thickness (x is along the line and y is perpendicular),
// How rounded the end points should be (0.0 is rectangular, setting rounded to thick.y will be circular),
// dashOn is just 1.0 or 0.0 to turn on the dashed lines.
float LineDistField(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float dashOn) {
// Don't let it get more round than circular.
rounded = min(thick.y, rounded);
// midpoint
vec2 mid = (pB + pA) * 0.5;
// vector from point A to B
vec2 delta = pB - pA;
// Distance between endpoints
float lenD = length(delta);
// unit vector pointing in the line's direction
vec2 unit = delta / lenD;
// Check for when line endpoints are the same
if (lenD < 0.0001) unit = vec2(1.0, 0.0); // if pA and pB are same
// Perpendicular vector to unit - also length 1.0
vec2 perp = unit.yx * vec2(-1.0, 1.0);
// position along line from midpoint
float dpx = dot(unit, uv - mid);
// distance away from line at a right angle
float dpy = dot(perp, uv - mid);
// Make a distance function that is 0 at the transition from black to white
float disty = abs(dpy) - thick.y + rounded;
float distx = abs(dpx) - lenD * 0.5 - thick.x + rounded;
// Too tired to remember what this does. Something like rounded endpoints for distance function.
float dist = length(vec2(max(0.0, distx), max(0.0,disty))) - rounded;
dist = min(dist, max(distx, disty));
// This is for animated dashed lines. Delete if you don't like dashes.
float dashScale = 2.0*thick.y;
// Make a distance function for the dashes
float dash = (repeat(dpx/dashScale + iTime)-0.5)*dashScale;
// Combine this distance function with the line's.
dist = max(dist, dash-(1.0-dashOn*1.0)*10000.0);
return dist;
}
// This makes a filled line in pixel units. A 1.0 thick line will be 1 pixel thick.
float FillLinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / scale);
}
// This makes an outlined line in pixel units. A 1.0 thick outline will be 1 pixel thick.
float DrawOutlinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
rounded = (rounded * 0.5 - 0.5) * scale;
outlineThick = (outlineThick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / scale);
}
// This makes a line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLine(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes a dashed line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLineDash(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 1.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes an outlined line in UV units. A 1.0 thick outline will span 0..1 in UV space.
float DrawOutline(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / abs(dFdy(uv).y));
}
// This just draws a point for debugging using a different technique that is less glorious.
void DrawPoint(vec2 uv, vec2 p, inout vec3 col) {
col = mix(col, vec3(1.0, 0.25, 0.25), saturate(abs(dFdy(uv).y)*8.0/distance(uv, p)-4.0));
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// Adjust UV space so it's a nice size and square.
vec2 uv = fragCoord.xy / iResolution.xy;
uv -= 0.5;
uv.x *= iResolution.x / iResolution.y;
uv *= 16.0;
// Make things that rotate with time.
vec2 rotA = vec2(cos(iTime*0.82), sin(iTime*0.82));
vec2 rotB = vec2(sin(iTime*0.82), -cos(iTime*0.82));
// Make a bunch of line endpoints to use.
vec2 pA = vec2(-4.0, 0.0) - rotA;
vec2 pB = vec2(4.0, 0.0) + rotA;
vec2 pC = pA + vec2(0.0, 4.0);
vec2 pD = pB + vec2(0.0, 4.0);
// Debugging code
//float df = LineDistField(uv, pA, pB, vec2(28.0 * dFdy(uv).y), 0.1, 0.0);
//float df = DistField(uv, pA, pB, 25.000625 * dFdx(uv).x, 0.5);
//vec3 finalColor = vec3(df*1.0, -df*1.0, 0.0);
//finalColor = vec3(1.0) * saturate(df / dFdy(uv).y);
//finalColor = vec3(1.0) * saturate((abs(df+0.009)-0.009) / dFdy(uv).y);
// Clear to white.
vec3 finalColor = vec3(1.0);
// Lots of sample lines
// 1 pixel thick regardless of screen scale.
finalColor *= FillLinePix(uv, pA, pB, vec2(1.0, 1.0), 0.0);
// Rounded rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(32.0), 16.0, 1.0);
// square-cornered rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(64.0), 0.0, 1.0);
// Fully rounded endpoint with outline 8 pixels thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(128.0), 128.0, 8.0);
// Dashed line with rectangular endpoints that touch pC and pD, 0.5 radius thickness in UV units
finalColor *= FillLineDash(uv, pC, pD, vec2(0.0, 0.5), 0.0);
// Rounded endpoint dashed line with radius 0.125 in UV units
finalColor *= FillLineDash(uv, pC + vec2(0.0, 2.0), pD + vec2(0.0, 2.0), vec2(0.125), 1.0);
finalColor *= DrawOutline(uv, (pA + pB) * 0.5 + vec2(0.0, -4.5), (pA + pB) * 0.5 + vec2(0.0, -4.5), vec2(2.0, 2.0), 2.0, 0.8);
finalColor *= FillLine(uv, pA - vec2(4.0, 0.0), pC - vec2(4.0, 0.0)+rotA, vec2(0.125), 1.0);
finalColor *= FillLine(uv, pB + vec2(4.0, 0.0), pD + vec2(4.0, 0.0)-rotA, vec2(0.125), 1.0);
DrawPoint(uv, pA, finalColor);
DrawPoint(uv, pB, finalColor);
DrawPoint(uv, pC, finalColor);
DrawPoint(uv, pD, finalColor);
// Blue grid lines
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.x*2.0) - 0.92)*4.0;
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.y*2.0) - 0.92)*4.0;
//finalColor *= saturate(mod(fragCoord.y + 0.5, 2.0) + mod(fragCoord.x + 0.5, 2.0));
fragColor = vec4(sqrt(saturate(finalColor)), 1.0);
}
| cc0-1.0 | [
4319,
4413,
4487,
4487,
4601
] | [
[
1074,
1103,
1126,
1126,
1166
],
[
1168,
1633,
1722,
1772,
3200
],
[
3202,
3286,
3359,
3359,
3539
],
[
3541,
3631,
3727,
3727,
4044
],
[
4046,
4133,
4203,
4203,
4317
],
[
4319,
4413,
4487,
4487,
4601
],
[
4603,
4695,
4788,
4788,
4939
],
[
4941,
5033,
5082,
5082,
5178
],
[
5180,
5180,
5237,
5292,
7805
]
] | // This makes a dashed line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
| float FillLineDash(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) { |
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 1.0);
return saturate(df / abs(dFdy(uv).y));
} | // This makes a dashed line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLineDash(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) { | 1 | 1 |
4tc3DX | otaviogood | 2016-11-01T07:02:43 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
**************** Glorious Line Algorithm ****************
This is an attempt to solve everything anyone could want from a line in one function.
Glorious features:
- antialiasing
- rectangles, squares, lines, circles, rounded rectangles
- square or rounded endpoints
- outline shapes (might have some bugs still)
- dashed, animated lines
- resolution dependent or independent - some functions work in pixel units, some in UV coordinates.
- efficient
*/
// Clamp [0..1] range
#define saturate(a) clamp(a, 0.0, 1.0)
// Basically a triangle wave
float repeat(float x) { return abs(fract(x*0.5+0.5)-0.5)*2.0; }
// This is it... what you have been waiting for... _The_ Glorious Line Algorithm.
// This function will make a signed distance field that says how far you are from the edge
// of the line at any point U,V.
// Pass it UVs, line end points, line thickness (x is along the line and y is perpendicular),
// How rounded the end points should be (0.0 is rectangular, setting rounded to thick.y will be circular),
// dashOn is just 1.0 or 0.0 to turn on the dashed lines.
float LineDistField(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float dashOn) {
// Don't let it get more round than circular.
rounded = min(thick.y, rounded);
// midpoint
vec2 mid = (pB + pA) * 0.5;
// vector from point A to B
vec2 delta = pB - pA;
// Distance between endpoints
float lenD = length(delta);
// unit vector pointing in the line's direction
vec2 unit = delta / lenD;
// Check for when line endpoints are the same
if (lenD < 0.0001) unit = vec2(1.0, 0.0); // if pA and pB are same
// Perpendicular vector to unit - also length 1.0
vec2 perp = unit.yx * vec2(-1.0, 1.0);
// position along line from midpoint
float dpx = dot(unit, uv - mid);
// distance away from line at a right angle
float dpy = dot(perp, uv - mid);
// Make a distance function that is 0 at the transition from black to white
float disty = abs(dpy) - thick.y + rounded;
float distx = abs(dpx) - lenD * 0.5 - thick.x + rounded;
// Too tired to remember what this does. Something like rounded endpoints for distance function.
float dist = length(vec2(max(0.0, distx), max(0.0,disty))) - rounded;
dist = min(dist, max(distx, disty));
// This is for animated dashed lines. Delete if you don't like dashes.
float dashScale = 2.0*thick.y;
// Make a distance function for the dashes
float dash = (repeat(dpx/dashScale + iTime)-0.5)*dashScale;
// Combine this distance function with the line's.
dist = max(dist, dash-(1.0-dashOn*1.0)*10000.0);
return dist;
}
// This makes a filled line in pixel units. A 1.0 thick line will be 1 pixel thick.
float FillLinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / scale);
}
// This makes an outlined line in pixel units. A 1.0 thick outline will be 1 pixel thick.
float DrawOutlinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
rounded = (rounded * 0.5 - 0.5) * scale;
outlineThick = (outlineThick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / scale);
}
// This makes a line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLine(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes a dashed line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLineDash(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 1.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes an outlined line in UV units. A 1.0 thick outline will span 0..1 in UV space.
float DrawOutline(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / abs(dFdy(uv).y));
}
// This just draws a point for debugging using a different technique that is less glorious.
void DrawPoint(vec2 uv, vec2 p, inout vec3 col) {
col = mix(col, vec3(1.0, 0.25, 0.25), saturate(abs(dFdy(uv).y)*8.0/distance(uv, p)-4.0));
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// Adjust UV space so it's a nice size and square.
vec2 uv = fragCoord.xy / iResolution.xy;
uv -= 0.5;
uv.x *= iResolution.x / iResolution.y;
uv *= 16.0;
// Make things that rotate with time.
vec2 rotA = vec2(cos(iTime*0.82), sin(iTime*0.82));
vec2 rotB = vec2(sin(iTime*0.82), -cos(iTime*0.82));
// Make a bunch of line endpoints to use.
vec2 pA = vec2(-4.0, 0.0) - rotA;
vec2 pB = vec2(4.0, 0.0) + rotA;
vec2 pC = pA + vec2(0.0, 4.0);
vec2 pD = pB + vec2(0.0, 4.0);
// Debugging code
//float df = LineDistField(uv, pA, pB, vec2(28.0 * dFdy(uv).y), 0.1, 0.0);
//float df = DistField(uv, pA, pB, 25.000625 * dFdx(uv).x, 0.5);
//vec3 finalColor = vec3(df*1.0, -df*1.0, 0.0);
//finalColor = vec3(1.0) * saturate(df / dFdy(uv).y);
//finalColor = vec3(1.0) * saturate((abs(df+0.009)-0.009) / dFdy(uv).y);
// Clear to white.
vec3 finalColor = vec3(1.0);
// Lots of sample lines
// 1 pixel thick regardless of screen scale.
finalColor *= FillLinePix(uv, pA, pB, vec2(1.0, 1.0), 0.0);
// Rounded rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(32.0), 16.0, 1.0);
// square-cornered rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(64.0), 0.0, 1.0);
// Fully rounded endpoint with outline 8 pixels thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(128.0), 128.0, 8.0);
// Dashed line with rectangular endpoints that touch pC and pD, 0.5 radius thickness in UV units
finalColor *= FillLineDash(uv, pC, pD, vec2(0.0, 0.5), 0.0);
// Rounded endpoint dashed line with radius 0.125 in UV units
finalColor *= FillLineDash(uv, pC + vec2(0.0, 2.0), pD + vec2(0.0, 2.0), vec2(0.125), 1.0);
finalColor *= DrawOutline(uv, (pA + pB) * 0.5 + vec2(0.0, -4.5), (pA + pB) * 0.5 + vec2(0.0, -4.5), vec2(2.0, 2.0), 2.0, 0.8);
finalColor *= FillLine(uv, pA - vec2(4.0, 0.0), pC - vec2(4.0, 0.0)+rotA, vec2(0.125), 1.0);
finalColor *= FillLine(uv, pB + vec2(4.0, 0.0), pD + vec2(4.0, 0.0)-rotA, vec2(0.125), 1.0);
DrawPoint(uv, pA, finalColor);
DrawPoint(uv, pB, finalColor);
DrawPoint(uv, pC, finalColor);
DrawPoint(uv, pD, finalColor);
// Blue grid lines
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.x*2.0) - 0.92)*4.0;
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.y*2.0) - 0.92)*4.0;
//finalColor *= saturate(mod(fragCoord.y + 0.5, 2.0) + mod(fragCoord.x + 0.5, 2.0));
fragColor = vec4(sqrt(saturate(finalColor)), 1.0);
}
| cc0-1.0 | [
4603,
4695,
4788,
4788,
4939
] | [
[
1074,
1103,
1126,
1126,
1166
],
[
1168,
1633,
1722,
1772,
3200
],
[
3202,
3286,
3359,
3359,
3539
],
[
3541,
3631,
3727,
3727,
4044
],
[
4046,
4133,
4203,
4203,
4317
],
[
4319,
4413,
4487,
4487,
4601
],
[
4603,
4695,
4788,
4788,
4939
],
[
4941,
5033,
5082,
5082,
5178
],
[
5180,
5180,
5237,
5292,
7805
]
] | // This makes an outlined line in UV units. A 1.0 thick outline will span 0..1 in UV space.
| float DrawOutline(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) { |
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / abs(dFdy(uv).y));
} | // This makes an outlined line in UV units. A 1.0 thick outline will span 0..1 in UV space.
float DrawOutline(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) { | 1 | 1 |
4tc3DX | otaviogood | 2016-11-01T07:02:43 | /*--------------------------------------------------------------------------------------
License CC0 - http://creativecommons.org/publicdomain/zero/1.0/
To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty.
----------------------------------------------------------------------------------------
^ This means do ANYTHING YOU WANT with this code. Because we are programmers, not lawyers.
-Otavio Good
**************** Glorious Line Algorithm ****************
This is an attempt to solve everything anyone could want from a line in one function.
Glorious features:
- antialiasing
- rectangles, squares, lines, circles, rounded rectangles
- square or rounded endpoints
- outline shapes (might have some bugs still)
- dashed, animated lines
- resolution dependent or independent - some functions work in pixel units, some in UV coordinates.
- efficient
*/
// Clamp [0..1] range
#define saturate(a) clamp(a, 0.0, 1.0)
// Basically a triangle wave
float repeat(float x) { return abs(fract(x*0.5+0.5)-0.5)*2.0; }
// This is it... what you have been waiting for... _The_ Glorious Line Algorithm.
// This function will make a signed distance field that says how far you are from the edge
// of the line at any point U,V.
// Pass it UVs, line end points, line thickness (x is along the line and y is perpendicular),
// How rounded the end points should be (0.0 is rectangular, setting rounded to thick.y will be circular),
// dashOn is just 1.0 or 0.0 to turn on the dashed lines.
float LineDistField(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float dashOn) {
// Don't let it get more round than circular.
rounded = min(thick.y, rounded);
// midpoint
vec2 mid = (pB + pA) * 0.5;
// vector from point A to B
vec2 delta = pB - pA;
// Distance between endpoints
float lenD = length(delta);
// unit vector pointing in the line's direction
vec2 unit = delta / lenD;
// Check for when line endpoints are the same
if (lenD < 0.0001) unit = vec2(1.0, 0.0); // if pA and pB are same
// Perpendicular vector to unit - also length 1.0
vec2 perp = unit.yx * vec2(-1.0, 1.0);
// position along line from midpoint
float dpx = dot(unit, uv - mid);
// distance away from line at a right angle
float dpy = dot(perp, uv - mid);
// Make a distance function that is 0 at the transition from black to white
float disty = abs(dpy) - thick.y + rounded;
float distx = abs(dpx) - lenD * 0.5 - thick.x + rounded;
// Too tired to remember what this does. Something like rounded endpoints for distance function.
float dist = length(vec2(max(0.0, distx), max(0.0,disty))) - rounded;
dist = min(dist, max(distx, disty));
// This is for animated dashed lines. Delete if you don't like dashes.
float dashScale = 2.0*thick.y;
// Make a distance function for the dashes
float dash = (repeat(dpx/dashScale + iTime)-0.5)*dashScale;
// Combine this distance function with the line's.
dist = max(dist, dash-(1.0-dashOn*1.0)*10000.0);
return dist;
}
// This makes a filled line in pixel units. A 1.0 thick line will be 1 pixel thick.
float FillLinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / scale);
}
// This makes an outlined line in pixel units. A 1.0 thick outline will be 1 pixel thick.
float DrawOutlinePix(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float scale = abs(dFdy(uv).y);
thick = (thick * 0.5 - 0.5) * scale;
rounded = (rounded * 0.5 - 0.5) * scale;
outlineThick = (outlineThick * 0.5 - 0.5) * scale;
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / scale);
}
// This makes a line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLine(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes a dashed line in UV units. A 1.0 thick line will span a whole 0..1 in UV space.
float FillLineDash(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 1.0);
return saturate(df / abs(dFdy(uv).y));
}
// This makes an outlined line in UV units. A 1.0 thick outline will span 0..1 in UV space.
float DrawOutline(vec2 uv, vec2 pA, vec2 pB, vec2 thick, float rounded, float outlineThick) {
float df = LineDistField(uv, pA, pB, vec2(thick), rounded, 0.0);
return saturate((abs(df + outlineThick) - outlineThick) / abs(dFdy(uv).y));
}
// This just draws a point for debugging using a different technique that is less glorious.
void DrawPoint(vec2 uv, vec2 p, inout vec3 col) {
col = mix(col, vec3(1.0, 0.25, 0.25), saturate(abs(dFdy(uv).y)*8.0/distance(uv, p)-4.0));
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// Adjust UV space so it's a nice size and square.
vec2 uv = fragCoord.xy / iResolution.xy;
uv -= 0.5;
uv.x *= iResolution.x / iResolution.y;
uv *= 16.0;
// Make things that rotate with time.
vec2 rotA = vec2(cos(iTime*0.82), sin(iTime*0.82));
vec2 rotB = vec2(sin(iTime*0.82), -cos(iTime*0.82));
// Make a bunch of line endpoints to use.
vec2 pA = vec2(-4.0, 0.0) - rotA;
vec2 pB = vec2(4.0, 0.0) + rotA;
vec2 pC = pA + vec2(0.0, 4.0);
vec2 pD = pB + vec2(0.0, 4.0);
// Debugging code
//float df = LineDistField(uv, pA, pB, vec2(28.0 * dFdy(uv).y), 0.1, 0.0);
//float df = DistField(uv, pA, pB, 25.000625 * dFdx(uv).x, 0.5);
//vec3 finalColor = vec3(df*1.0, -df*1.0, 0.0);
//finalColor = vec3(1.0) * saturate(df / dFdy(uv).y);
//finalColor = vec3(1.0) * saturate((abs(df+0.009)-0.009) / dFdy(uv).y);
// Clear to white.
vec3 finalColor = vec3(1.0);
// Lots of sample lines
// 1 pixel thick regardless of screen scale.
finalColor *= FillLinePix(uv, pA, pB, vec2(1.0, 1.0), 0.0);
// Rounded rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(32.0), 16.0, 1.0);
// square-cornered rectangle outline, 1 pixel thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(64.0), 0.0, 1.0);
// Fully rounded endpoint with outline 8 pixels thick
finalColor *= DrawOutlinePix(uv, pA, pB, vec2(128.0), 128.0, 8.0);
// Dashed line with rectangular endpoints that touch pC and pD, 0.5 radius thickness in UV units
finalColor *= FillLineDash(uv, pC, pD, vec2(0.0, 0.5), 0.0);
// Rounded endpoint dashed line with radius 0.125 in UV units
finalColor *= FillLineDash(uv, pC + vec2(0.0, 2.0), pD + vec2(0.0, 2.0), vec2(0.125), 1.0);
finalColor *= DrawOutline(uv, (pA + pB) * 0.5 + vec2(0.0, -4.5), (pA + pB) * 0.5 + vec2(0.0, -4.5), vec2(2.0, 2.0), 2.0, 0.8);
finalColor *= FillLine(uv, pA - vec2(4.0, 0.0), pC - vec2(4.0, 0.0)+rotA, vec2(0.125), 1.0);
finalColor *= FillLine(uv, pB + vec2(4.0, 0.0), pD + vec2(4.0, 0.0)-rotA, vec2(0.125), 1.0);
DrawPoint(uv, pA, finalColor);
DrawPoint(uv, pB, finalColor);
DrawPoint(uv, pC, finalColor);
DrawPoint(uv, pD, finalColor);
// Blue grid lines
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.x*2.0) - 0.92)*4.0;
finalColor -= vec3(1.0, 1.0, 0.2) * saturate(repeat(uv.y*2.0) - 0.92)*4.0;
//finalColor *= saturate(mod(fragCoord.y + 0.5, 2.0) + mod(fragCoord.x + 0.5, 2.0));
fragColor = vec4(sqrt(saturate(finalColor)), 1.0);
}
| cc0-1.0 | [
4941,
5033,
5082,
5082,
5178
] | [
[
1074,
1103,
1126,
1126,
1166
],
[
1168,
1633,
1722,
1772,
3200
],
[
3202,
3286,
3359,
3359,
3539
],
[
3541,
3631,
3727,
3727,
4044
],
[
4046,
4133,
4203,
4203,
4317
],
[
4319,
4413,
4487,
4487,
4601
],
[
4603,
4695,
4788,
4788,
4939
],
[
4941,
5033,
5082,
5082,
5178
],
[
5180,
5180,
5237,
5292,
7805
]
] | // This just draws a point for debugging using a different technique that is less glorious.
| void DrawPoint(vec2 uv, vec2 p, inout vec3 col) { |
col = mix(col, vec3(1.0, 0.25, 0.25), saturate(abs(dFdy(uv).y)*8.0/distance(uv, p)-4.0));
} | // This just draws a point for debugging using a different technique that is less glorious.
void DrawPoint(vec2 uv, vec2 p, inout vec3 col) { | 1 | 1 |
ll3Xzf | iq | 2016-12-05T05:42:03 | // The MIT License
// Copyright © 2016 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// See http://iquilezles.org/www/articles/diskbbox/diskbbox.htm
//
//
// Analytical computation of the exact bounding box for an arbitrarily oriented disk.
// It took me a good two hours to find the symmetries and term cancellations that
// simplified the original monster equation into something pretty compact in its final form.
//
// For a disk of raius r centerd in the origin oriented in the direction n, has extent e:
//
// e = r·sqrt(1-n²)
//
// Derivation and more info in the link above
// Other bounding box functions:
//
// Disk - 3D BBox : https://www.shadertoy.com/view/ll3Xzf
// Cylinder - 3D BBox : https://www.shadertoy.com/view/MtcXRf
// Ellipse - 3D BBox : https://www.shadertoy.com/view/Xtjczw
// Cone boundong - 3D BBox : https://www.shadertoy.com/view/WdjSRK
// Cubic Bezier - 2D BBox : https://www.shadertoy.com/view/XdVBWd
// Quadratic Bezier - 3D BBox : https://www.shadertoy.com/view/ldj3Wh
// Quadratic Bezier - 2D BBox : https://www.shadertoy.com/view/lsyfWc
#define AA 3
struct bound3
{
vec3 mMin;
vec3 mMax;
};
//---------------------------------------------------------------------------------------
// bounding box for a disk (http://iquilezles.org/www/articles/diskbbox/diskbbox.htm)
//---------------------------------------------------------------------------------------
bound3 DiskAABB( in vec3 cen, in vec3 nor, float rad ) // disk: center, normal, radius
{
vec3 e = rad*sqrt( 1.0 - nor*nor );
return bound3( cen-e, cen+e );
}
// ray-disk intersection
float iDisk( in vec3 ro, in vec3 rd, // ray: origin, direction
in vec3 cen, in vec3 nor, float rad ) // disk: center, normal, radius
{
vec3 q = ro - cen;
float t = -dot(nor,q)/dot(rd,nor);
if( t<0.0 ) return -1.0;
vec3 d = q + rd*t;
if( dot(d,d)>(rad*rad) ) return -1.0;
return t;
}
// ray-box intersection (simplified)
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 cen, in vec3 rad )
{
// ray-box intersection in box space
vec3 m = 1.0/rd;
vec3 n = m*(ro-cen);
vec3 k = abs(m)*rad;
vec3 t1 = -n - k;
vec3 t2 = -n + k;
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );
if( tN > tF || tF < 0.0) return vec2(-1.0);
return vec2( tN, tF );
}
float hash1( in vec2 p )
{
return fract(sin(dot(p, vec2(12.9898, 78.233)))*43758.5453);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec3 tot = vec3(0.0);
#if AA>1
for( int m=0; m<AA; m++ )
for( int n=0; n<AA; n++ )
{
// pixel coordinates
vec2 o = vec2(float(m),float(n)) / float(AA) - 0.5;
vec2 p = (-iResolution.xy + 2.0*(fragCoord+o))/iResolution.y;
#else
vec2 p = (-iResolution.xy + 2.0*fragCoord)/iResolution.y;
#endif
// camera position
vec3 ro = vec3( -0.5, 0.4, 1.5 );
vec3 ta = vec3( 0.0, 0.0, 0.0 );
// camera matrix
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(0.0,1.0,0.0) ) );
vec3 vv = normalize( cross(uu,ww));
// create view ray
vec3 rd = normalize( p.x*uu + p.y*vv + 1.5*ww );
// disk animation
vec3 disk_center = 0.3*sin(iTime*vec3(1.11,1.27,1.47)+vec3(2.0,5.0,6.0));
vec3 disk_axis = normalize( sin(iTime*vec3(1.23,1.41,1.07)+vec3(0.0,1.0,3.0)) );
float disk_radius = 0.4 + 0.2*sin(iTime*1.3+0.5);
// render
vec3 col = vec3(0.4)*(1.0-0.3*length(p));
// raytrace disk
float t = iDisk( ro, rd, disk_center, disk_axis, disk_radius );
float tmin = 1e10;
if( t>0.0 )
{
tmin = t;
col = vec3(1.0,0.75,0.3)*(0.7+0.2*abs(disk_axis.y));
}
// compute bounding box for disk
bound3 bbox = DiskAABB( disk_center, disk_axis, disk_radius );
// raytrace bounding box
vec3 bcen = 0.5*(bbox.mMin+bbox.mMax);
vec3 brad = 0.5*(bbox.mMax-bbox.mMin);
vec2 tbox = iBox( ro, rd, bcen, brad );
if( tbox.x>0.0 )
{
// back face
if( tbox.y < tmin )
{
vec3 pos = ro + rd*tbox.y;
vec3 e = smoothstep( brad-0.03, brad-0.02, abs(pos-bcen) );
float al = 1.0 - (1.0-e.x*e.y)*(1.0-e.y*e.z)*(1.0-e.z*e.x);
col = mix( col, vec3(0.0), 0.25 + 0.75*al );
}
// front face
if( tbox.x < tmin )
{
vec3 pos = ro + rd*tbox.x;
vec3 e = smoothstep( brad-0.03, brad-0.02, abs(pos-bcen) );
float al = 1.0 - (1.0-e.x*e.y)*(1.0-e.y*e.z)*(1.0-e.z*e.x);
col = mix( col, vec3(0.0), 0.15 + 0.85*al );
}
}
// no gamma required here, it's done in line 118
tot += col;
#if AA>1
}
tot /= float(AA*AA);
#endif
// dithering
tot += ((hash1(fragCoord.xy)+hash1(fragCoord.yx+13.1))/2.0-0.5)/256.0;
fragColor = vec4( tot, 1.0 );
} | mit | [
2610,
2635,
2796,
2796,
2966
] | [
[
2175,
2441,
2530,
2530,
2607
],
[
2610,
2635,
2796,
2796,
2966
],
[
2969,
3006,
3070,
3108,
3388
],
[
3390,
3390,
3416,
3416,
3483
]
] | // ray-disk intersection
| float iDisk( in vec3 ro, in vec3 rd, // ray: origin, direction
in vec3 cen, in vec3 nor, float rad ) // disk: center, normal, radius
{ |
vec3 q = ro - cen;
float t = -dot(nor,q)/dot(rd,nor);
if( t<0.0 ) return -1.0;
vec3 d = q + rd*t;
if( dot(d,d)>(rad*rad) ) return -1.0;
return t;
} | // ray-disk intersection
float iDisk( in vec3 ro, in vec3 rd, // ray: origin, direction
in vec3 cen, in vec3 nor, float rad ) // disk: center, normal, radius
{ | 2 | 2 |
ll3Xzf | iq | 2016-12-05T05:42:03 | // The MIT License
// Copyright © 2016 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// See http://iquilezles.org/www/articles/diskbbox/diskbbox.htm
//
//
// Analytical computation of the exact bounding box for an arbitrarily oriented disk.
// It took me a good two hours to find the symmetries and term cancellations that
// simplified the original monster equation into something pretty compact in its final form.
//
// For a disk of raius r centerd in the origin oriented in the direction n, has extent e:
//
// e = r·sqrt(1-n²)
//
// Derivation and more info in the link above
// Other bounding box functions:
//
// Disk - 3D BBox : https://www.shadertoy.com/view/ll3Xzf
// Cylinder - 3D BBox : https://www.shadertoy.com/view/MtcXRf
// Ellipse - 3D BBox : https://www.shadertoy.com/view/Xtjczw
// Cone boundong - 3D BBox : https://www.shadertoy.com/view/WdjSRK
// Cubic Bezier - 2D BBox : https://www.shadertoy.com/view/XdVBWd
// Quadratic Bezier - 3D BBox : https://www.shadertoy.com/view/ldj3Wh
// Quadratic Bezier - 2D BBox : https://www.shadertoy.com/view/lsyfWc
#define AA 3
struct bound3
{
vec3 mMin;
vec3 mMax;
};
//---------------------------------------------------------------------------------------
// bounding box for a disk (http://iquilezles.org/www/articles/diskbbox/diskbbox.htm)
//---------------------------------------------------------------------------------------
bound3 DiskAABB( in vec3 cen, in vec3 nor, float rad ) // disk: center, normal, radius
{
vec3 e = rad*sqrt( 1.0 - nor*nor );
return bound3( cen-e, cen+e );
}
// ray-disk intersection
float iDisk( in vec3 ro, in vec3 rd, // ray: origin, direction
in vec3 cen, in vec3 nor, float rad ) // disk: center, normal, radius
{
vec3 q = ro - cen;
float t = -dot(nor,q)/dot(rd,nor);
if( t<0.0 ) return -1.0;
vec3 d = q + rd*t;
if( dot(d,d)>(rad*rad) ) return -1.0;
return t;
}
// ray-box intersection (simplified)
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 cen, in vec3 rad )
{
// ray-box intersection in box space
vec3 m = 1.0/rd;
vec3 n = m*(ro-cen);
vec3 k = abs(m)*rad;
vec3 t1 = -n - k;
vec3 t2 = -n + k;
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );
if( tN > tF || tF < 0.0) return vec2(-1.0);
return vec2( tN, tF );
}
float hash1( in vec2 p )
{
return fract(sin(dot(p, vec2(12.9898, 78.233)))*43758.5453);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec3 tot = vec3(0.0);
#if AA>1
for( int m=0; m<AA; m++ )
for( int n=0; n<AA; n++ )
{
// pixel coordinates
vec2 o = vec2(float(m),float(n)) / float(AA) - 0.5;
vec2 p = (-iResolution.xy + 2.0*(fragCoord+o))/iResolution.y;
#else
vec2 p = (-iResolution.xy + 2.0*fragCoord)/iResolution.y;
#endif
// camera position
vec3 ro = vec3( -0.5, 0.4, 1.5 );
vec3 ta = vec3( 0.0, 0.0, 0.0 );
// camera matrix
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(0.0,1.0,0.0) ) );
vec3 vv = normalize( cross(uu,ww));
// create view ray
vec3 rd = normalize( p.x*uu + p.y*vv + 1.5*ww );
// disk animation
vec3 disk_center = 0.3*sin(iTime*vec3(1.11,1.27,1.47)+vec3(2.0,5.0,6.0));
vec3 disk_axis = normalize( sin(iTime*vec3(1.23,1.41,1.07)+vec3(0.0,1.0,3.0)) );
float disk_radius = 0.4 + 0.2*sin(iTime*1.3+0.5);
// render
vec3 col = vec3(0.4)*(1.0-0.3*length(p));
// raytrace disk
float t = iDisk( ro, rd, disk_center, disk_axis, disk_radius );
float tmin = 1e10;
if( t>0.0 )
{
tmin = t;
col = vec3(1.0,0.75,0.3)*(0.7+0.2*abs(disk_axis.y));
}
// compute bounding box for disk
bound3 bbox = DiskAABB( disk_center, disk_axis, disk_radius );
// raytrace bounding box
vec3 bcen = 0.5*(bbox.mMin+bbox.mMax);
vec3 brad = 0.5*(bbox.mMax-bbox.mMin);
vec2 tbox = iBox( ro, rd, bcen, brad );
if( tbox.x>0.0 )
{
// back face
if( tbox.y < tmin )
{
vec3 pos = ro + rd*tbox.y;
vec3 e = smoothstep( brad-0.03, brad-0.02, abs(pos-bcen) );
float al = 1.0 - (1.0-e.x*e.y)*(1.0-e.y*e.z)*(1.0-e.z*e.x);
col = mix( col, vec3(0.0), 0.25 + 0.75*al );
}
// front face
if( tbox.x < tmin )
{
vec3 pos = ro + rd*tbox.x;
vec3 e = smoothstep( brad-0.03, brad-0.02, abs(pos-bcen) );
float al = 1.0 - (1.0-e.x*e.y)*(1.0-e.y*e.z)*(1.0-e.z*e.x);
col = mix( col, vec3(0.0), 0.15 + 0.85*al );
}
}
// no gamma required here, it's done in line 118
tot += col;
#if AA>1
}
tot /= float(AA*AA);
#endif
// dithering
tot += ((hash1(fragCoord.xy)+hash1(fragCoord.yx+13.1))/2.0-0.5)/256.0;
fragColor = vec4( tot, 1.0 );
} | mit | [
2969,
3006,
3070,
3108,
3388
] | [
[
2175,
2441,
2530,
2530,
2607
],
[
2610,
2635,
2796,
2796,
2966
],
[
2969,
3006,
3070,
3108,
3388
],
[
3390,
3390,
3416,
3416,
3483
]
] | // ray-box intersection (simplified)
| vec2 iBox( in vec3 ro, in vec3 rd, in vec3 cen, in vec3 rad )
{ |
vec3 m = 1.0/rd;
vec3 n = m*(ro-cen);
vec3 k = abs(m)*rad;
vec3 t1 = -n - k;
vec3 t2 = -n + k;
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );
if( tN > tF || tF < 0.0) return vec2(-1.0);
return vec2( tN, tF );
} | // ray-box intersection (simplified)
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 cen, in vec3 rad )
{ | 5 | 5 |
MtcXRf | iq | 2016-12-05T05:43:39 | // The MIT License
// Copyright © 2016 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// See http://iquilezles.org/www/articles/diskbbox/diskbbox.htm
//
//
// Analytical computation of the exact bounding box for an arbitrarily oriented disk.
// It took me a good two hours to find the symmetries and term cancellations that
// simplified the original monster equation into something pretty compact in its final form.
//
// For a disk of raius r centerd in the origin oriented in the direction n, has extent e:
//
// e = r·sqrt(1-n²)
//
// Derivation and more info in the link above
// Disk - 3D BBox : https://www.shadertoy.com/view/ll3Xzf
// Cylinder - 3D BBox : https://www.shadertoy.com/view/MtcXRf
// Ellipse - 3D BBox : https://www.shadertoy.com/view/Xtjczw
// Cone boundong - 3D BBox : https://www.shadertoy.com/view/WdjSRK
// Cubic Bezier - 2D BBox : https://www.shadertoy.com/view/XdVBWd
// Quadratic Bezier - 3D BBox : https://www.shadertoy.com/view/ldj3Wh
// Quadratic Bezier - 2D BBox : https://www.shadertoy.com/view/lsyfWc
// Cylinder intersection: https://www.shadertoy.com/view/4lcSRn
// Cylinder bounding box: https://www.shadertoy.com/view/MtcXRf
// Cylinder distance: https://www.shadertoy.com/view/wdXGDr
#define AA 3
struct bound3
{
vec3 mMin;
vec3 mMax;
};
//---------------------------------------------------------------------------------------
// bounding box for a cylinder (http://iquilezles.org/www/articles/diskbbox/diskbbox.htm)
//---------------------------------------------------------------------------------------
bound3 CylinderAABB( in vec3 pa, in vec3 pb, in float ra )
{
vec3 a = pb - pa;
vec3 e = ra*sqrt( 1.0 - a*a/dot(a,a) );
return bound3( min( pa - e, pb - e ),
max( pa + e, pb + e ) );
}
// ray-cylinder intersetion (returns t and normal)
vec4 iCylinder( in vec3 ro, in vec3 rd,
in vec3 pa, in vec3 pb, in float ra ) // point a, point b, radius
{
// center the cylinder, normalize axis
vec3 cc = 0.5*(pa+pb);
float ch = length(pb-pa);
vec3 ca = (pb-pa)/ch;
ch *= 0.5;
vec3 oc = ro - cc;
float card = dot(ca,rd);
float caoc = dot(ca,oc);
float a = 1.0 - card*card;
float b = dot( oc, rd) - caoc*card;
float c = dot( oc, oc) - caoc*caoc - ra*ra;
float h = b*b - a*c;
if( h<0.0 ) return vec4(-1.0);
h = sqrt(h);
float t1 = (-b-h)/a;
//float t2 = (-b+h)/a; // exit point
float y = caoc + t1*card;
// body
if( abs(y)<ch ) return vec4( t1, normalize( oc+t1*rd - ca*y ) );
// caps
float sy = sign(y);
float tp = (sy*ch - caoc)/card;
if( abs(b+a*tp)<h )
{
return vec4( tp, ca*sy );
}
return vec4(-1.0);
}
// ray-box intersection
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 cen, in vec3 rad )
{
vec3 m = 1.0/rd;
vec3 n = m*(ro-cen);
vec3 k = abs(m)*rad;
vec3 t1 = -n - k;
vec3 t2 = -n + k;
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );
if( tN > tF || tF < 0.0) return vec2(-1.0);
return vec2( tN, tF );
}
float hash1( in vec2 p )
{
return fract(sin(dot(p, vec2(12.9898, 78.233)))*43758.5453);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec3 tot = vec3(0.0);
#if AA>1
for( int m=0; m<AA; m++ )
for( int n=0; n<AA; n++ )
{
// pixel coordinates
vec2 o = vec2(float(m),float(n)) / float(AA) - 0.5;
vec2 p = (-iResolution.xy + 2.0*(fragCoord+o))/iResolution.y;
#else
vec2 p = (-iResolution.xy + 2.0*fragCoord)/iResolution.y;
#endif
// camera position
vec3 ro = vec3( -0.5, 0.4, 1.5 );
vec3 ta = vec3( 0.0, 0.0, 0.0 );
// camera matrix
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(0.0,1.0,0.0) ) );
vec3 vv = normalize( cross(uu,ww));
// create view ray
vec3 rd = normalize( p.x*uu + p.y*vv + 1.5*ww );
// cylidner animation
vec3 c_a = 0.2 + 0.3*sin(iTime*vec3(1.11,1.27,1.47)+vec3(2.0,5.0,6.0));
vec3 c_b = -0.2 + 0.3*sin(iTime*vec3(1.23,1.41,1.07)+vec3(0.0,1.0,3.0));
float c_r = 0.3 + 0.2*sin(iTime*1.3+0.5);
// render
vec3 col = vec3(0.4)*(1.0-0.3*length(p));
// raytrace
vec4 tnor = iCylinder( ro, rd, c_a, c_b, c_r );
float t = tnor.x;
float tmin = 1e10;
if( t>0.0 )
{
tmin = t;
// shading/lighting
vec3 pos = ro + t*rd;
vec3 nor = tnor.yzw;
float dif = clamp( dot(nor,vec3(0.5,0.7,0.2)), 0.0, 1.0 );
float amb = 0.5 + 0.5*dot(nor,vec3(0.0,1.0,0.0));
col = sqrt( vec3(0.2,0.3,0.4)*amb + vec3(0.8,0.7,0.5)*dif );
col *= vec3(1.0,0.75,0.3);
}
// compute bounding box of cylinder
bound3 bbox = CylinderAABB( c_a, c_b, c_r );
// raytrace bounding box
vec3 bcen = 0.5*(bbox.mMin+bbox.mMax);
vec3 brad = 0.5*(bbox.mMax-bbox.mMin);
vec2 tbox = iBox( ro, rd, bcen, brad );
if( tbox.x>0.0 )
{
// back face
if( tbox.y < tmin )
{
vec3 pos = ro + rd*tbox.y;
vec3 e = smoothstep( brad-0.03, brad-0.02, abs(pos-bcen) );
float al = 1.0 - (1.0-e.x*e.y)*(1.0-e.y*e.z)*(1.0-e.z*e.x);
col = mix( col, vec3(0.0), 0.25 + 0.75*al );
}
// front face
if( tbox.x < tmin )
{
vec3 pos = ro + rd*tbox.x;
vec3 e = smoothstep( brad-0.03, brad-0.02, abs(pos-bcen) );
float al = 1.0 - (1.0-e.x*e.y)*(1.0-e.y*e.z)*(1.0-e.z*e.x);
col = mix( col, vec3(0.0), 0.15 + 0.85*al );
}
}
// no gamma required here, it's done in line 118
tot += col;
#if AA>1
}
tot /= float(AA*AA);
#endif
// dithering
tot += ((hash1(fragCoord.xy)+hash1(fragCoord.yx+13.1))/2.0 - 0.5)/256.0;
fragColor = vec4( tot, 1.0 );
} | mit | [
2337,
2607,
2667,
2667,
2826
] | [
[
2337,
2607,
2667,
2667,
2826
],
[
2828,
2879,
3003,
3046,
3781
],
[
3784,
3808,
3872,
3872,
4152
],
[
4155,
4155,
4181,
4181,
4248
]
] | //---------------------------------------------------------------------------------------
// bounding box for a cylinder (http://iquilezles.org/www/articles/diskbbox/diskbbox.htm)
//---------------------------------------------------------------------------------------
| bound3 CylinderAABB( in vec3 pa, in vec3 pb, in float ra )
{ |
vec3 a = pb - pa;
vec3 e = ra*sqrt( 1.0 - a*a/dot(a,a) );
return bound3( min( pa - e, pb - e ),
max( pa + e, pb + e ) );
} | //---------------------------------------------------------------------------------------
// bounding box for a cylinder (http://iquilezles.org/www/articles/diskbbox/diskbbox.htm)
//---------------------------------------------------------------------------------------
bound3 CylinderAABB( in vec3 pa, in vec3 pb, in float ra )
{ | 1 | 1 |
MtcXRf | iq | 2016-12-05T05:43:39 | // The MIT License
// Copyright © 2016 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// See http://iquilezles.org/www/articles/diskbbox/diskbbox.htm
//
//
// Analytical computation of the exact bounding box for an arbitrarily oriented disk.
// It took me a good two hours to find the symmetries and term cancellations that
// simplified the original monster equation into something pretty compact in its final form.
//
// For a disk of raius r centerd in the origin oriented in the direction n, has extent e:
//
// e = r·sqrt(1-n²)
//
// Derivation and more info in the link above
// Disk - 3D BBox : https://www.shadertoy.com/view/ll3Xzf
// Cylinder - 3D BBox : https://www.shadertoy.com/view/MtcXRf
// Ellipse - 3D BBox : https://www.shadertoy.com/view/Xtjczw
// Cone boundong - 3D BBox : https://www.shadertoy.com/view/WdjSRK
// Cubic Bezier - 2D BBox : https://www.shadertoy.com/view/XdVBWd
// Quadratic Bezier - 3D BBox : https://www.shadertoy.com/view/ldj3Wh
// Quadratic Bezier - 2D BBox : https://www.shadertoy.com/view/lsyfWc
// Cylinder intersection: https://www.shadertoy.com/view/4lcSRn
// Cylinder bounding box: https://www.shadertoy.com/view/MtcXRf
// Cylinder distance: https://www.shadertoy.com/view/wdXGDr
#define AA 3
struct bound3
{
vec3 mMin;
vec3 mMax;
};
//---------------------------------------------------------------------------------------
// bounding box for a cylinder (http://iquilezles.org/www/articles/diskbbox/diskbbox.htm)
//---------------------------------------------------------------------------------------
bound3 CylinderAABB( in vec3 pa, in vec3 pb, in float ra )
{
vec3 a = pb - pa;
vec3 e = ra*sqrt( 1.0 - a*a/dot(a,a) );
return bound3( min( pa - e, pb - e ),
max( pa + e, pb + e ) );
}
// ray-cylinder intersetion (returns t and normal)
vec4 iCylinder( in vec3 ro, in vec3 rd,
in vec3 pa, in vec3 pb, in float ra ) // point a, point b, radius
{
// center the cylinder, normalize axis
vec3 cc = 0.5*(pa+pb);
float ch = length(pb-pa);
vec3 ca = (pb-pa)/ch;
ch *= 0.5;
vec3 oc = ro - cc;
float card = dot(ca,rd);
float caoc = dot(ca,oc);
float a = 1.0 - card*card;
float b = dot( oc, rd) - caoc*card;
float c = dot( oc, oc) - caoc*caoc - ra*ra;
float h = b*b - a*c;
if( h<0.0 ) return vec4(-1.0);
h = sqrt(h);
float t1 = (-b-h)/a;
//float t2 = (-b+h)/a; // exit point
float y = caoc + t1*card;
// body
if( abs(y)<ch ) return vec4( t1, normalize( oc+t1*rd - ca*y ) );
// caps
float sy = sign(y);
float tp = (sy*ch - caoc)/card;
if( abs(b+a*tp)<h )
{
return vec4( tp, ca*sy );
}
return vec4(-1.0);
}
// ray-box intersection
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 cen, in vec3 rad )
{
vec3 m = 1.0/rd;
vec3 n = m*(ro-cen);
vec3 k = abs(m)*rad;
vec3 t1 = -n - k;
vec3 t2 = -n + k;
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );
if( tN > tF || tF < 0.0) return vec2(-1.0);
return vec2( tN, tF );
}
float hash1( in vec2 p )
{
return fract(sin(dot(p, vec2(12.9898, 78.233)))*43758.5453);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec3 tot = vec3(0.0);
#if AA>1
for( int m=0; m<AA; m++ )
for( int n=0; n<AA; n++ )
{
// pixel coordinates
vec2 o = vec2(float(m),float(n)) / float(AA) - 0.5;
vec2 p = (-iResolution.xy + 2.0*(fragCoord+o))/iResolution.y;
#else
vec2 p = (-iResolution.xy + 2.0*fragCoord)/iResolution.y;
#endif
// camera position
vec3 ro = vec3( -0.5, 0.4, 1.5 );
vec3 ta = vec3( 0.0, 0.0, 0.0 );
// camera matrix
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(0.0,1.0,0.0) ) );
vec3 vv = normalize( cross(uu,ww));
// create view ray
vec3 rd = normalize( p.x*uu + p.y*vv + 1.5*ww );
// cylidner animation
vec3 c_a = 0.2 + 0.3*sin(iTime*vec3(1.11,1.27,1.47)+vec3(2.0,5.0,6.0));
vec3 c_b = -0.2 + 0.3*sin(iTime*vec3(1.23,1.41,1.07)+vec3(0.0,1.0,3.0));
float c_r = 0.3 + 0.2*sin(iTime*1.3+0.5);
// render
vec3 col = vec3(0.4)*(1.0-0.3*length(p));
// raytrace
vec4 tnor = iCylinder( ro, rd, c_a, c_b, c_r );
float t = tnor.x;
float tmin = 1e10;
if( t>0.0 )
{
tmin = t;
// shading/lighting
vec3 pos = ro + t*rd;
vec3 nor = tnor.yzw;
float dif = clamp( dot(nor,vec3(0.5,0.7,0.2)), 0.0, 1.0 );
float amb = 0.5 + 0.5*dot(nor,vec3(0.0,1.0,0.0));
col = sqrt( vec3(0.2,0.3,0.4)*amb + vec3(0.8,0.7,0.5)*dif );
col *= vec3(1.0,0.75,0.3);
}
// compute bounding box of cylinder
bound3 bbox = CylinderAABB( c_a, c_b, c_r );
// raytrace bounding box
vec3 bcen = 0.5*(bbox.mMin+bbox.mMax);
vec3 brad = 0.5*(bbox.mMax-bbox.mMin);
vec2 tbox = iBox( ro, rd, bcen, brad );
if( tbox.x>0.0 )
{
// back face
if( tbox.y < tmin )
{
vec3 pos = ro + rd*tbox.y;
vec3 e = smoothstep( brad-0.03, brad-0.02, abs(pos-bcen) );
float al = 1.0 - (1.0-e.x*e.y)*(1.0-e.y*e.z)*(1.0-e.z*e.x);
col = mix( col, vec3(0.0), 0.25 + 0.75*al );
}
// front face
if( tbox.x < tmin )
{
vec3 pos = ro + rd*tbox.x;
vec3 e = smoothstep( brad-0.03, brad-0.02, abs(pos-bcen) );
float al = 1.0 - (1.0-e.x*e.y)*(1.0-e.y*e.z)*(1.0-e.z*e.x);
col = mix( col, vec3(0.0), 0.15 + 0.85*al );
}
}
// no gamma required here, it's done in line 118
tot += col;
#if AA>1
}
tot /= float(AA*AA);
#endif
// dithering
tot += ((hash1(fragCoord.xy)+hash1(fragCoord.yx+13.1))/2.0 - 0.5)/256.0;
fragColor = vec4( tot, 1.0 );
} | mit | [
2828,
2879,
3003,
3046,
3781
] | [
[
2337,
2607,
2667,
2667,
2826
],
[
2828,
2879,
3003,
3046,
3781
],
[
3784,
3808,
3872,
3872,
4152
],
[
4155,
4155,
4181,
4181,
4248
]
] | // ray-cylinder intersetion (returns t and normal)
| vec4 iCylinder( in vec3 ro, in vec3 rd,
in vec3 pa, in vec3 pb, in float ra ) // point a, point b, radius
{ |
vec3 cc = 0.5*(pa+pb);
float ch = length(pb-pa);
vec3 ca = (pb-pa)/ch;
ch *= 0.5;
vec3 oc = ro - cc;
float card = dot(ca,rd);
float caoc = dot(ca,oc);
float a = 1.0 - card*card;
float b = dot( oc, rd) - caoc*card;
float c = dot( oc, oc) - caoc*caoc - ra*ra;
float h = b*b - a*c;
if( h<0.0 ) return vec4(-1.0);
h = sqrt(h);
float t1 = (-b-h)/a;
//float t2 = (-b+h)/a; // exit point
float y = caoc + t1*card;
// body
if( abs(y)<ch ) return vec4( t1, normalize( oc+t1*rd - ca*y ) );
// caps
float sy = sign(y);
float tp = (sy*ch - caoc)/card;
if( abs(b+a*tp)<h )
{
return vec4( tp, ca*sy );
}
return vec4(-1.0);
} | // ray-cylinder intersetion (returns t and normal)
vec4 iCylinder( in vec3 ro, in vec3 rd,
in vec3 pa, in vec3 pb, in float ra ) // point a, point b, radius
{ | 1 | 1 |
MtcXRf | iq | 2016-12-05T05:43:39 | // The MIT License
// Copyright © 2016 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// See http://iquilezles.org/www/articles/diskbbox/diskbbox.htm
//
//
// Analytical computation of the exact bounding box for an arbitrarily oriented disk.
// It took me a good two hours to find the symmetries and term cancellations that
// simplified the original monster equation into something pretty compact in its final form.
//
// For a disk of raius r centerd in the origin oriented in the direction n, has extent e:
//
// e = r·sqrt(1-n²)
//
// Derivation and more info in the link above
// Disk - 3D BBox : https://www.shadertoy.com/view/ll3Xzf
// Cylinder - 3D BBox : https://www.shadertoy.com/view/MtcXRf
// Ellipse - 3D BBox : https://www.shadertoy.com/view/Xtjczw
// Cone boundong - 3D BBox : https://www.shadertoy.com/view/WdjSRK
// Cubic Bezier - 2D BBox : https://www.shadertoy.com/view/XdVBWd
// Quadratic Bezier - 3D BBox : https://www.shadertoy.com/view/ldj3Wh
// Quadratic Bezier - 2D BBox : https://www.shadertoy.com/view/lsyfWc
// Cylinder intersection: https://www.shadertoy.com/view/4lcSRn
// Cylinder bounding box: https://www.shadertoy.com/view/MtcXRf
// Cylinder distance: https://www.shadertoy.com/view/wdXGDr
#define AA 3
struct bound3
{
vec3 mMin;
vec3 mMax;
};
//---------------------------------------------------------------------------------------
// bounding box for a cylinder (http://iquilezles.org/www/articles/diskbbox/diskbbox.htm)
//---------------------------------------------------------------------------------------
bound3 CylinderAABB( in vec3 pa, in vec3 pb, in float ra )
{
vec3 a = pb - pa;
vec3 e = ra*sqrt( 1.0 - a*a/dot(a,a) );
return bound3( min( pa - e, pb - e ),
max( pa + e, pb + e ) );
}
// ray-cylinder intersetion (returns t and normal)
vec4 iCylinder( in vec3 ro, in vec3 rd,
in vec3 pa, in vec3 pb, in float ra ) // point a, point b, radius
{
// center the cylinder, normalize axis
vec3 cc = 0.5*(pa+pb);
float ch = length(pb-pa);
vec3 ca = (pb-pa)/ch;
ch *= 0.5;
vec3 oc = ro - cc;
float card = dot(ca,rd);
float caoc = dot(ca,oc);
float a = 1.0 - card*card;
float b = dot( oc, rd) - caoc*card;
float c = dot( oc, oc) - caoc*caoc - ra*ra;
float h = b*b - a*c;
if( h<0.0 ) return vec4(-1.0);
h = sqrt(h);
float t1 = (-b-h)/a;
//float t2 = (-b+h)/a; // exit point
float y = caoc + t1*card;
// body
if( abs(y)<ch ) return vec4( t1, normalize( oc+t1*rd - ca*y ) );
// caps
float sy = sign(y);
float tp = (sy*ch - caoc)/card;
if( abs(b+a*tp)<h )
{
return vec4( tp, ca*sy );
}
return vec4(-1.0);
}
// ray-box intersection
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 cen, in vec3 rad )
{
vec3 m = 1.0/rd;
vec3 n = m*(ro-cen);
vec3 k = abs(m)*rad;
vec3 t1 = -n - k;
vec3 t2 = -n + k;
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );
if( tN > tF || tF < 0.0) return vec2(-1.0);
return vec2( tN, tF );
}
float hash1( in vec2 p )
{
return fract(sin(dot(p, vec2(12.9898, 78.233)))*43758.5453);
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec3 tot = vec3(0.0);
#if AA>1
for( int m=0; m<AA; m++ )
for( int n=0; n<AA; n++ )
{
// pixel coordinates
vec2 o = vec2(float(m),float(n)) / float(AA) - 0.5;
vec2 p = (-iResolution.xy + 2.0*(fragCoord+o))/iResolution.y;
#else
vec2 p = (-iResolution.xy + 2.0*fragCoord)/iResolution.y;
#endif
// camera position
vec3 ro = vec3( -0.5, 0.4, 1.5 );
vec3 ta = vec3( 0.0, 0.0, 0.0 );
// camera matrix
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(0.0,1.0,0.0) ) );
vec3 vv = normalize( cross(uu,ww));
// create view ray
vec3 rd = normalize( p.x*uu + p.y*vv + 1.5*ww );
// cylidner animation
vec3 c_a = 0.2 + 0.3*sin(iTime*vec3(1.11,1.27,1.47)+vec3(2.0,5.0,6.0));
vec3 c_b = -0.2 + 0.3*sin(iTime*vec3(1.23,1.41,1.07)+vec3(0.0,1.0,3.0));
float c_r = 0.3 + 0.2*sin(iTime*1.3+0.5);
// render
vec3 col = vec3(0.4)*(1.0-0.3*length(p));
// raytrace
vec4 tnor = iCylinder( ro, rd, c_a, c_b, c_r );
float t = tnor.x;
float tmin = 1e10;
if( t>0.0 )
{
tmin = t;
// shading/lighting
vec3 pos = ro + t*rd;
vec3 nor = tnor.yzw;
float dif = clamp( dot(nor,vec3(0.5,0.7,0.2)), 0.0, 1.0 );
float amb = 0.5 + 0.5*dot(nor,vec3(0.0,1.0,0.0));
col = sqrt( vec3(0.2,0.3,0.4)*amb + vec3(0.8,0.7,0.5)*dif );
col *= vec3(1.0,0.75,0.3);
}
// compute bounding box of cylinder
bound3 bbox = CylinderAABB( c_a, c_b, c_r );
// raytrace bounding box
vec3 bcen = 0.5*(bbox.mMin+bbox.mMax);
vec3 brad = 0.5*(bbox.mMax-bbox.mMin);
vec2 tbox = iBox( ro, rd, bcen, brad );
if( tbox.x>0.0 )
{
// back face
if( tbox.y < tmin )
{
vec3 pos = ro + rd*tbox.y;
vec3 e = smoothstep( brad-0.03, brad-0.02, abs(pos-bcen) );
float al = 1.0 - (1.0-e.x*e.y)*(1.0-e.y*e.z)*(1.0-e.z*e.x);
col = mix( col, vec3(0.0), 0.25 + 0.75*al );
}
// front face
if( tbox.x < tmin )
{
vec3 pos = ro + rd*tbox.x;
vec3 e = smoothstep( brad-0.03, brad-0.02, abs(pos-bcen) );
float al = 1.0 - (1.0-e.x*e.y)*(1.0-e.y*e.z)*(1.0-e.z*e.x);
col = mix( col, vec3(0.0), 0.15 + 0.85*al );
}
}
// no gamma required here, it's done in line 118
tot += col;
#if AA>1
}
tot /= float(AA*AA);
#endif
// dithering
tot += ((hash1(fragCoord.xy)+hash1(fragCoord.yx+13.1))/2.0 - 0.5)/256.0;
fragColor = vec4( tot, 1.0 );
} | mit | [
3784,
3808,
3872,
3872,
4152
] | [
[
2337,
2607,
2667,
2667,
2826
],
[
2828,
2879,
3003,
3046,
3781
],
[
3784,
3808,
3872,
3872,
4152
],
[
4155,
4155,
4181,
4181,
4248
]
] | // ray-box intersection
| vec2 iBox( in vec3 ro, in vec3 rd, in vec3 cen, in vec3 rad )
{ |
vec3 m = 1.0/rd;
vec3 n = m*(ro-cen);
vec3 k = abs(m)*rad;
vec3 t1 = -n - k;
vec3 t2 = -n + k;
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );
if( tN > tF || tF < 0.0) return vec2(-1.0);
return vec2( tN, tF );
} | // ray-box intersection
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 cen, in vec3 rad )
{ | 5 | 5 |
Xt3SzX | iq | 2016-12-03T01:02:35 | // The MIT License
// Copyright © 2016 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Intersection of a ray and a capped cylinder oriented in an arbitrary direction. There's
// only one sphere involved, not two.
// Other capsule functions:
//
// Capsule intersection: https://www.shadertoy.com/view/Xt3SzX
// Capsule bounding box: https://www.shadertoy.com/view/3s2SRV
// Capsule distance: https://www.shadertoy.com/view/Xds3zN
// Capsule occlusion: https://www.shadertoy.com/view/llGyzG
// List of ray-surface intersectors at https://www.shadertoy.com/playlist/l3dXRf
// and http://iquilezles.org/www/articles/intersectors/intersectors.htm
// intersect capsule : http://www.iquilezles.org/www/articles/intersectors/intersectors.htm
float capIntersect( in vec3 ro, in vec3 rd, in vec3 pa, in vec3 pb, in float r )
{
vec3 ba = pb - pa;
vec3 oa = ro - pa;
float baba = dot(ba,ba);
float bard = dot(ba,rd);
float baoa = dot(ba,oa);
float rdoa = dot(rd,oa);
float oaoa = dot(oa,oa);
float a = baba - bard*bard;
float b = baba*rdoa - baoa*bard;
float c = baba*oaoa - baoa*baoa - r*r*baba;
float h = b*b - a*c;
if( h>=0.0 )
{
float t = (-b-sqrt(h))/a;
float y = baoa + t*bard;
// body
if( y>0.0 && y<baba ) return t;
// caps
vec3 oc = (y<=0.0) ? oa : ro - pb;
b = dot(rd,oc);
c = dot(oc,oc) - r*r;
h = b*b - c;
if( h>0.0 ) return -b - sqrt(h);
}
return -1.0;
}
// compute normal
vec3 capNormal( in vec3 pos, in vec3 a, in vec3 b, in float r )
{
vec3 ba = b - a;
vec3 pa = pos - a;
float h = clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);
return (pa - h*ba)/r;
}
// fake occlusion
float capOcclusion( in vec3 p, in vec3 n, in vec3 a, in vec3 b, in float r )
{
vec3 ba = b - a, pa = p - a;
float h = clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);
vec3 d = pa - h*ba;
float l = length(d);
float o = 1.0 - max(0.0,dot(-d,n))*r*r/(l*l*l);
return sqrt(o*o*o);
}
vec3 pattern( in vec2 uv )
{
vec3 col = vec3(0.6);
col += 0.4*smoothstep(-0.01,0.01,cos(uv.x*0.5)*cos(uv.y*0.5));
col *= smoothstep(-1.0,-0.98,cos(uv.x))*smoothstep(-1.0,-0.98,cos(uv.y));
return col;
}
#define AA 3
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera movement
float an = 0.5*iTime;
vec3 ro = vec3( 1.0*cos(an), 0.4, 1.0*sin(an) );
vec3 ta = vec3( 0.0, 0.0, 0.0 );
// camera matrix
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(0.0,1.0,0.0) ) );
vec3 vv = normalize( cross(uu,ww));
vec3 tot = vec3(0.0);
#if AA>1
for( int m=0; m<AA; m++ )
for( int n=0; n<AA; n++ )
{
// pixel coordinates
vec2 o = vec2(float(m),float(n)) / float(AA) - 0.5;
vec2 p = (-iResolution.xy + 2.0*(fragCoord+o))/iResolution.y;
#else
vec2 p = (-iResolution.xy + 2.0*fragCoord)/iResolution.y;
#endif
// create view ray
vec3 rd = normalize( p.x*uu + p.y*vv + 1.5*ww );
const vec3 capA = vec3(-0.3,-0.1,-0.1);
const vec3 capB = vec3(0.3,0.1,0.4);
const float capR = 0.2;
vec3 col = vec3(0.08)*(1.0-0.3*length(p)) + 0.02*rd.y;
float t = capIntersect( ro, rd, capA, capB, capR );
if( t>0.0 )
{
vec3 pos = ro + t*rd;
vec3 nor = capNormal(pos, capA, capB, capR );
vec3 lig = normalize(vec3(0.7,0.6,0.3));
vec3 hal = normalize(-rd+lig);
float dif = clamp( dot(nor,lig), 0.0, 1.0 );
float amb = clamp( 0.5 + 0.5*dot(nor,vec3(0.0,1.0,0.0)), 0.0, 1.0 );
float occ = 0.5 + 0.5*nor.y;
vec3 w = normalize(capB-capA);
vec3 u = normalize(cross(w,vec3(0,0,1)));
vec3 v = normalize(cross(u,w) );
vec3 q = (pos-capA)*mat3(u,v,w);
col = pattern( vec2(12.0,64.0)*vec2(atan(q.y,q.x),q.z) );
col *= vec3(0.2,0.3,0.4)*amb*occ + vec3(1.0,0.9,0.7)*dif;
col += 0.4*pow(clamp(dot(hal,nor),0.0,1.0),12.0)*dif;
}
col = sqrt( col );
tot += col;
#if AA>1
}
tot /= float(AA*AA);
#endif
// dither to remove banding in the background
tot += fract(sin(fragCoord.x*vec3(13,1,11)+fragCoord.y*vec3(1,7,5))*158.391832)/255.0;
fragColor = vec4( tot, 1.0 );
} | mit | [
1650,
1742,
1824,
1824,
2512
] | [
[
1650,
1742,
1824,
1824,
2512
],
[
2514,
2532,
2597,
2597,
2723
],
[
2726,
2744,
2822,
2822,
3036
],
[
3038,
3038,
3066,
3066,
3256
]
] | // intersect capsule : http://www.iquilezles.org/www/articles/intersectors/intersectors.htm
| float capIntersect( in vec3 ro, in vec3 rd, in vec3 pa, in vec3 pb, in float r )
{ |
vec3 ba = pb - pa;
vec3 oa = ro - pa;
float baba = dot(ba,ba);
float bard = dot(ba,rd);
float baoa = dot(ba,oa);
float rdoa = dot(rd,oa);
float oaoa = dot(oa,oa);
float a = baba - bard*bard;
float b = baba*rdoa - baoa*bard;
float c = baba*oaoa - baoa*baoa - r*r*baba;
float h = b*b - a*c;
if( h>=0.0 )
{
float t = (-b-sqrt(h))/a;
float y = baoa + t*bard;
// body
if( y>0.0 && y<baba ) return t;
// caps
vec3 oc = (y<=0.0) ? oa : ro - pb;
b = dot(rd,oc);
c = dot(oc,oc) - r*r;
h = b*b - c;
if( h>0.0 ) return -b - sqrt(h);
}
return -1.0;
} | // intersect capsule : http://www.iquilezles.org/www/articles/intersectors/intersectors.htm
float capIntersect( in vec3 ro, in vec3 rd, in vec3 pa, in vec3 pb, in float r )
{ | 2 | 6 |
Xt3SzX | iq | 2016-12-03T01:02:35 | // The MIT License
// Copyright © 2016 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Intersection of a ray and a capped cylinder oriented in an arbitrary direction. There's
// only one sphere involved, not two.
// Other capsule functions:
//
// Capsule intersection: https://www.shadertoy.com/view/Xt3SzX
// Capsule bounding box: https://www.shadertoy.com/view/3s2SRV
// Capsule distance: https://www.shadertoy.com/view/Xds3zN
// Capsule occlusion: https://www.shadertoy.com/view/llGyzG
// List of ray-surface intersectors at https://www.shadertoy.com/playlist/l3dXRf
// and http://iquilezles.org/www/articles/intersectors/intersectors.htm
// intersect capsule : http://www.iquilezles.org/www/articles/intersectors/intersectors.htm
float capIntersect( in vec3 ro, in vec3 rd, in vec3 pa, in vec3 pb, in float r )
{
vec3 ba = pb - pa;
vec3 oa = ro - pa;
float baba = dot(ba,ba);
float bard = dot(ba,rd);
float baoa = dot(ba,oa);
float rdoa = dot(rd,oa);
float oaoa = dot(oa,oa);
float a = baba - bard*bard;
float b = baba*rdoa - baoa*bard;
float c = baba*oaoa - baoa*baoa - r*r*baba;
float h = b*b - a*c;
if( h>=0.0 )
{
float t = (-b-sqrt(h))/a;
float y = baoa + t*bard;
// body
if( y>0.0 && y<baba ) return t;
// caps
vec3 oc = (y<=0.0) ? oa : ro - pb;
b = dot(rd,oc);
c = dot(oc,oc) - r*r;
h = b*b - c;
if( h>0.0 ) return -b - sqrt(h);
}
return -1.0;
}
// compute normal
vec3 capNormal( in vec3 pos, in vec3 a, in vec3 b, in float r )
{
vec3 ba = b - a;
vec3 pa = pos - a;
float h = clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);
return (pa - h*ba)/r;
}
// fake occlusion
float capOcclusion( in vec3 p, in vec3 n, in vec3 a, in vec3 b, in float r )
{
vec3 ba = b - a, pa = p - a;
float h = clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);
vec3 d = pa - h*ba;
float l = length(d);
float o = 1.0 - max(0.0,dot(-d,n))*r*r/(l*l*l);
return sqrt(o*o*o);
}
vec3 pattern( in vec2 uv )
{
vec3 col = vec3(0.6);
col += 0.4*smoothstep(-0.01,0.01,cos(uv.x*0.5)*cos(uv.y*0.5));
col *= smoothstep(-1.0,-0.98,cos(uv.x))*smoothstep(-1.0,-0.98,cos(uv.y));
return col;
}
#define AA 3
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
// camera movement
float an = 0.5*iTime;
vec3 ro = vec3( 1.0*cos(an), 0.4, 1.0*sin(an) );
vec3 ta = vec3( 0.0, 0.0, 0.0 );
// camera matrix
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(0.0,1.0,0.0) ) );
vec3 vv = normalize( cross(uu,ww));
vec3 tot = vec3(0.0);
#if AA>1
for( int m=0; m<AA; m++ )
for( int n=0; n<AA; n++ )
{
// pixel coordinates
vec2 o = vec2(float(m),float(n)) / float(AA) - 0.5;
vec2 p = (-iResolution.xy + 2.0*(fragCoord+o))/iResolution.y;
#else
vec2 p = (-iResolution.xy + 2.0*fragCoord)/iResolution.y;
#endif
// create view ray
vec3 rd = normalize( p.x*uu + p.y*vv + 1.5*ww );
const vec3 capA = vec3(-0.3,-0.1,-0.1);
const vec3 capB = vec3(0.3,0.1,0.4);
const float capR = 0.2;
vec3 col = vec3(0.08)*(1.0-0.3*length(p)) + 0.02*rd.y;
float t = capIntersect( ro, rd, capA, capB, capR );
if( t>0.0 )
{
vec3 pos = ro + t*rd;
vec3 nor = capNormal(pos, capA, capB, capR );
vec3 lig = normalize(vec3(0.7,0.6,0.3));
vec3 hal = normalize(-rd+lig);
float dif = clamp( dot(nor,lig), 0.0, 1.0 );
float amb = clamp( 0.5 + 0.5*dot(nor,vec3(0.0,1.0,0.0)), 0.0, 1.0 );
float occ = 0.5 + 0.5*nor.y;
vec3 w = normalize(capB-capA);
vec3 u = normalize(cross(w,vec3(0,0,1)));
vec3 v = normalize(cross(u,w) );
vec3 q = (pos-capA)*mat3(u,v,w);
col = pattern( vec2(12.0,64.0)*vec2(atan(q.y,q.x),q.z) );
col *= vec3(0.2,0.3,0.4)*amb*occ + vec3(1.0,0.9,0.7)*dif;
col += 0.4*pow(clamp(dot(hal,nor),0.0,1.0),12.0)*dif;
}
col = sqrt( col );
tot += col;
#if AA>1
}
tot /= float(AA*AA);
#endif
// dither to remove banding in the background
tot += fract(sin(fragCoord.x*vec3(13,1,11)+fragCoord.y*vec3(1,7,5))*158.391832)/255.0;
fragColor = vec4( tot, 1.0 );
} | mit | [
2514,
2532,
2597,
2597,
2723
] | [
[
1650,
1742,
1824,
1824,
2512
],
[
2514,
2532,
2597,
2597,
2723
],
[
2726,
2744,
2822,
2822,
3036
],
[
3038,
3038,
3066,
3066,
3256
]
] | // compute normal
| vec3 capNormal( in vec3 pos, in vec3 a, in vec3 b, in float r )
{ |
vec3 ba = b - a;
vec3 pa = pos - a;
float h = clamp(dot(pa,ba)/dot(ba,ba),0.0,1.0);
return (pa - h*ba)/r;
} | // compute normal
vec3 capNormal( in vec3 pos, in vec3 a, in vec3 b, in float r )
{ | 5 | 5 |
XttSz2 | iq | 2016-12-02T07:48:27 | // The MIT License
// Copyright © 2016 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Computing normals analytically has the benefit of being faster if you need them often,
// while numerical normals are easier to filter for antialiasing. See line 200.
//
// More info: http://iquilezles.org/www/articles/morenoise/morenoise.htm
//
// See this too: https://www.shadertoy.com/view/XsXfRH
//
// Proper noise code isolated here: https://www.shadertoy.com/view/XsXfRH
//
//#define SHOW_NUMERICAL_NORMALS // for comparison purposes
float hash( float n ) { return fract(sin(n)*753.5453123); }
//---------------------------------------------------------------
// value noise, and its analytical derivatives
//---------------------------------------------------------------
vec4 noised( in vec3 x )
{
vec3 p = floor(x);
vec3 w = fract(x);
vec3 u = w*w*(3.0-2.0*w);
vec3 du = 6.0*w*(1.0-w);
float n = p.x + p.y*157.0 + 113.0*p.z;
float a = hash(n+ 0.0);
float b = hash(n+ 1.0);
float c = hash(n+157.0);
float d = hash(n+158.0);
float e = hash(n+113.0);
float f = hash(n+114.0);
float g = hash(n+270.0);
float h = hash(n+271.0);
float k0 = a;
float k1 = b - a;
float k2 = c - a;
float k3 = e - a;
float k4 = a - b - c + d;
float k5 = a - c - e + g;
float k6 = a - b - e + f;
float k7 = - a + b + c - d + e - f - g + h;
return vec4( k0 + k1*u.x + k2*u.y + k3*u.z + k4*u.x*u.y + k5*u.y*u.z + k6*u.z*u.x + k7*u.x*u.y*u.z,
du * (vec3(k1,k2,k3) + u.yzx*vec3(k4,k5,k6) + u.zxy*vec3(k6,k4,k5) + k7*u.yzx*u.zxy ));
}
//---------------------------------------------------------------
vec4 sdBox( vec3 p, vec3 b ) // distance and normal
{
vec3 d = abs(p) - b;
float x = min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
vec3 n = step(d.yzx,d.xyz)*step(d.zxy,d.xyz)*sign(p);
return vec4( x, n );
}
vec4 fbmd( in vec3 x )
{
const float scale = 1.5;
float a = 0.0;
float b = 0.5;
float f = 1.0;
vec3 d = vec3(0.0);
for( int i=0; i<8; i++ )
{
vec4 n = noised(f*x*scale);
a += b*n.x; // accumulate values
d += b*n.yzw*f*scale; // accumulate derivatives
b *= 0.5; // amplitude decrease
f *= 1.8; // frequency increase
}
return vec4( a, d );
}
vec4 map( in vec3 p )
{
vec4 d1 = fbmd( p );
d1.x -= 0.37;
d1.x *= 0.7;
d1.yzw = normalize(d1.yzw);
// clip to box
vec4 d2 = sdBox( p, vec3(1.5) );
return (d1.x>d2.x) ? d1 : d2;
}
// ray-box intersection in box space
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 rad )
{
vec3 m = 1.0/rd;
vec3 n = m*ro;
vec3 k = abs(m)*rad;
vec3 t1 = -n - k;
vec3 t2 = -n + k;
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );
if( tN > tF || tF < 0.0) return vec2(-1.0);
return vec2( tN, tF );
}
// raymarch
vec4 interesect( in vec3 ro, in vec3 rd )
{
vec4 res = vec4(-1.0);
// bounding volume
vec2 dis = iBox( ro, rd, vec3(1.5) ) ;
if( dis.y<0.0 ) return res;
// raymarch
float tmax = dis.y;
float t = dis.x;
for( int i=0; i<128; i++ )
{
vec3 pos = ro + t*rd;
vec4 hnor = map( pos );
res = vec4(t,hnor.yzw);
if( hnor.x<0.001 ) break;
t += hnor.x;
if( t>tmax ) break;
}
if( t>tmax ) res = vec4(-1.0);
return res;
}
// compute normal numerically
#ifdef SHOW_NUMERICAL_NORMALS
vec3 calcNormal( in vec3 pos )
{
vec2 eps = vec2( 0.0001, 0.0 );
vec3 nor = vec3( map(pos+eps.xyy).x - map(pos-eps.xyy).x,
map(pos+eps.yxy).x - map(pos-eps.yxy).x,
map(pos+eps.yyx).x - map(pos-eps.yyx).x );
return normalize(nor);
}
#endif
// fibonazzi points in s aphsre, more info:
// http://lgdv.cs.fau.de/uploads/publications/spherical_fibonacci_mapping_opt.pdf
vec3 forwardSF( float i, float n)
{
const float PI = 3.141592653589793238;
const float PHI = 1.618033988749894848;
float phi = 2.0*PI*fract(i/PHI);
float zi = 1.0 - (2.0*i+1.0)/n;
float sinTheta = sqrt( 1.0 - zi*zi);
return vec3( cos(phi)*sinTheta, sin(phi)*sinTheta, zi);
}
float calcAO( in vec3 pos, in vec3 nor )
{
float ao = 0.0;
for( int i=0; i<32; i++ )
{
vec3 ap = forwardSF( float(i), 32.0 );
float h = hash(float(i));
ap *= sign( dot(ap,nor) ) * h*0.25;
ao += clamp( map( pos + nor*0.001 + ap ).x*3.0, 0.0, 1.0 );
}
ao /= 32.0;
return clamp( ao*5.0, 0.0, 1.0 );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 p = (2.0*fragCoord-iResolution.xy) / iResolution.y;
// camera anim
float an = 0.1*iTime;
vec3 ro = 3.0*vec3( cos(an), 0.8, sin(an) );
vec3 ta = vec3( 0.0 );
// camera matrix
vec3 cw = normalize( ta-ro );
vec3 cu = normalize( cross(cw,vec3(0.0,1.0,0.0)) );
vec3 cv = normalize( cross(cu,cw) );
vec3 rd = normalize( p.x*cu + p.y*cv + 1.7*cw );
// render
vec3 col = vec3(0.0);
vec4 tnor = interesect( ro, rd );
float t = tnor.x;
if( t>0.0 )
{
vec3 pos = ro + t*rd;
#ifndef SHOW_NUMERICAL_NORMALS
vec3 nor = tnor.yzw; // no need to call calcNormal( pos );
#else
vec3 nor = calcNormal( pos );
#endif
float occ = calcAO( pos, nor );
float fre = clamp( 1.0+dot(rd,nor), 0.0, 1.0 );
float fro = clamp( dot(nor,-rd), 0.0, 1.0 );
col = mix( vec3(0.05,0.2,0.3), vec3(1.0,0.95,0.85), 0.5+0.5*nor.y );
//col = 0.5+0.5*nor;
col += 10.0*pow(fro,12.0)*(0.04+0.96*pow(fre,5.0));
col *= pow(vec3(occ),vec3(1.0,1.1,1.1) );
}
col = sqrt(col);
fragColor=vec4(col,1.0);
} | mit | [
3586,
3623,
3674,
3674,
3942
] | [
[
1526,
1526,
1549,
1549,
1585
],
[
1768,
1768,
1794,
1794,
2629
],
[
2698,
2698,
2751,
2751,
2929
],
[
2931,
2931,
2955,
2955,
3380
],
[
3382,
3382,
3405,
3405,
3584
],
[
3586,
3623,
3674,
3674,
3942
],
[
3944,
3956,
3999,
3999,
4438
],
[
4779,
4905,
4941,
4941,
5205
],
[
5207,
5207,
5249,
5249,
5550
],
[
5552,
5552,
5609,
5609,
6718
]
] | // ray-box intersection in box space
| vec2 iBox( in vec3 ro, in vec3 rd, in vec3 rad )
{ |
vec3 m = 1.0/rd;
vec3 n = m*ro;
vec3 k = abs(m)*rad;
vec3 t1 = -n - k;
vec3 t2 = -n + k;
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );
if( tN > tF || tF < 0.0) return vec2(-1.0);
return vec2( tN, tF );
} | // ray-box intersection in box space
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 rad )
{ | 4 | 24 |
XttSz2 | iq | 2016-12-02T07:48:27 | // The MIT License
// Copyright © 2016 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Computing normals analytically has the benefit of being faster if you need them often,
// while numerical normals are easier to filter for antialiasing. See line 200.
//
// More info: http://iquilezles.org/www/articles/morenoise/morenoise.htm
//
// See this too: https://www.shadertoy.com/view/XsXfRH
//
// Proper noise code isolated here: https://www.shadertoy.com/view/XsXfRH
//
//#define SHOW_NUMERICAL_NORMALS // for comparison purposes
float hash( float n ) { return fract(sin(n)*753.5453123); }
//---------------------------------------------------------------
// value noise, and its analytical derivatives
//---------------------------------------------------------------
vec4 noised( in vec3 x )
{
vec3 p = floor(x);
vec3 w = fract(x);
vec3 u = w*w*(3.0-2.0*w);
vec3 du = 6.0*w*(1.0-w);
float n = p.x + p.y*157.0 + 113.0*p.z;
float a = hash(n+ 0.0);
float b = hash(n+ 1.0);
float c = hash(n+157.0);
float d = hash(n+158.0);
float e = hash(n+113.0);
float f = hash(n+114.0);
float g = hash(n+270.0);
float h = hash(n+271.0);
float k0 = a;
float k1 = b - a;
float k2 = c - a;
float k3 = e - a;
float k4 = a - b - c + d;
float k5 = a - c - e + g;
float k6 = a - b - e + f;
float k7 = - a + b + c - d + e - f - g + h;
return vec4( k0 + k1*u.x + k2*u.y + k3*u.z + k4*u.x*u.y + k5*u.y*u.z + k6*u.z*u.x + k7*u.x*u.y*u.z,
du * (vec3(k1,k2,k3) + u.yzx*vec3(k4,k5,k6) + u.zxy*vec3(k6,k4,k5) + k7*u.yzx*u.zxy ));
}
//---------------------------------------------------------------
vec4 sdBox( vec3 p, vec3 b ) // distance and normal
{
vec3 d = abs(p) - b;
float x = min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
vec3 n = step(d.yzx,d.xyz)*step(d.zxy,d.xyz)*sign(p);
return vec4( x, n );
}
vec4 fbmd( in vec3 x )
{
const float scale = 1.5;
float a = 0.0;
float b = 0.5;
float f = 1.0;
vec3 d = vec3(0.0);
for( int i=0; i<8; i++ )
{
vec4 n = noised(f*x*scale);
a += b*n.x; // accumulate values
d += b*n.yzw*f*scale; // accumulate derivatives
b *= 0.5; // amplitude decrease
f *= 1.8; // frequency increase
}
return vec4( a, d );
}
vec4 map( in vec3 p )
{
vec4 d1 = fbmd( p );
d1.x -= 0.37;
d1.x *= 0.7;
d1.yzw = normalize(d1.yzw);
// clip to box
vec4 d2 = sdBox( p, vec3(1.5) );
return (d1.x>d2.x) ? d1 : d2;
}
// ray-box intersection in box space
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 rad )
{
vec3 m = 1.0/rd;
vec3 n = m*ro;
vec3 k = abs(m)*rad;
vec3 t1 = -n - k;
vec3 t2 = -n + k;
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );
if( tN > tF || tF < 0.0) return vec2(-1.0);
return vec2( tN, tF );
}
// raymarch
vec4 interesect( in vec3 ro, in vec3 rd )
{
vec4 res = vec4(-1.0);
// bounding volume
vec2 dis = iBox( ro, rd, vec3(1.5) ) ;
if( dis.y<0.0 ) return res;
// raymarch
float tmax = dis.y;
float t = dis.x;
for( int i=0; i<128; i++ )
{
vec3 pos = ro + t*rd;
vec4 hnor = map( pos );
res = vec4(t,hnor.yzw);
if( hnor.x<0.001 ) break;
t += hnor.x;
if( t>tmax ) break;
}
if( t>tmax ) res = vec4(-1.0);
return res;
}
// compute normal numerically
#ifdef SHOW_NUMERICAL_NORMALS
vec3 calcNormal( in vec3 pos )
{
vec2 eps = vec2( 0.0001, 0.0 );
vec3 nor = vec3( map(pos+eps.xyy).x - map(pos-eps.xyy).x,
map(pos+eps.yxy).x - map(pos-eps.yxy).x,
map(pos+eps.yyx).x - map(pos-eps.yyx).x );
return normalize(nor);
}
#endif
// fibonazzi points in s aphsre, more info:
// http://lgdv.cs.fau.de/uploads/publications/spherical_fibonacci_mapping_opt.pdf
vec3 forwardSF( float i, float n)
{
const float PI = 3.141592653589793238;
const float PHI = 1.618033988749894848;
float phi = 2.0*PI*fract(i/PHI);
float zi = 1.0 - (2.0*i+1.0)/n;
float sinTheta = sqrt( 1.0 - zi*zi);
return vec3( cos(phi)*sinTheta, sin(phi)*sinTheta, zi);
}
float calcAO( in vec3 pos, in vec3 nor )
{
float ao = 0.0;
for( int i=0; i<32; i++ )
{
vec3 ap = forwardSF( float(i), 32.0 );
float h = hash(float(i));
ap *= sign( dot(ap,nor) ) * h*0.25;
ao += clamp( map( pos + nor*0.001 + ap ).x*3.0, 0.0, 1.0 );
}
ao /= 32.0;
return clamp( ao*5.0, 0.0, 1.0 );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 p = (2.0*fragCoord-iResolution.xy) / iResolution.y;
// camera anim
float an = 0.1*iTime;
vec3 ro = 3.0*vec3( cos(an), 0.8, sin(an) );
vec3 ta = vec3( 0.0 );
// camera matrix
vec3 cw = normalize( ta-ro );
vec3 cu = normalize( cross(cw,vec3(0.0,1.0,0.0)) );
vec3 cv = normalize( cross(cu,cw) );
vec3 rd = normalize( p.x*cu + p.y*cv + 1.7*cw );
// render
vec3 col = vec3(0.0);
vec4 tnor = interesect( ro, rd );
float t = tnor.x;
if( t>0.0 )
{
vec3 pos = ro + t*rd;
#ifndef SHOW_NUMERICAL_NORMALS
vec3 nor = tnor.yzw; // no need to call calcNormal( pos );
#else
vec3 nor = calcNormal( pos );
#endif
float occ = calcAO( pos, nor );
float fre = clamp( 1.0+dot(rd,nor), 0.0, 1.0 );
float fro = clamp( dot(nor,-rd), 0.0, 1.0 );
col = mix( vec3(0.05,0.2,0.3), vec3(1.0,0.95,0.85), 0.5+0.5*nor.y );
//col = 0.5+0.5*nor;
col += 10.0*pow(fro,12.0)*(0.04+0.96*pow(fre,5.0));
col *= pow(vec3(occ),vec3(1.0,1.1,1.1) );
}
col = sqrt(col);
fragColor=vec4(col,1.0);
} | mit | [
3944,
3956,
3999,
3999,
4438
] | [
[
1526,
1526,
1549,
1549,
1585
],
[
1768,
1768,
1794,
1794,
2629
],
[
2698,
2698,
2751,
2751,
2929
],
[
2931,
2931,
2955,
2955,
3380
],
[
3382,
3382,
3405,
3405,
3584
],
[
3586,
3623,
3674,
3674,
3942
],
[
3944,
3956,
3999,
3999,
4438
],
[
4779,
4905,
4941,
4941,
5205
],
[
5207,
5207,
5249,
5249,
5550
],
[
5552,
5552,
5609,
5609,
6718
]
] | // raymarch
| vec4 interesect( in vec3 ro, in vec3 rd )
{ |
vec4 res = vec4(-1.0);
// bounding volume
vec2 dis = iBox( ro, rd, vec3(1.5) ) ;
if( dis.y<0.0 ) return res;
// raymarch
float tmax = dis.y;
float t = dis.x;
for( int i=0; i<128; i++ )
{
vec3 pos = ro + t*rd;
vec4 hnor = map( pos );
res = vec4(t,hnor.yzw);
if( hnor.x<0.001 ) break;
t += hnor.x;
if( t>tmax ) break;
}
if( t>tmax ) res = vec4(-1.0);
return res;
} | // raymarch
vec4 interesect( in vec3 ro, in vec3 rd )
{ | 1 | 3 |
XttSz2 | iq | 2016-12-02T07:48:27 | // The MIT License
// Copyright © 2016 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Computing normals analytically has the benefit of being faster if you need them often,
// while numerical normals are easier to filter for antialiasing. See line 200.
//
// More info: http://iquilezles.org/www/articles/morenoise/morenoise.htm
//
// See this too: https://www.shadertoy.com/view/XsXfRH
//
// Proper noise code isolated here: https://www.shadertoy.com/view/XsXfRH
//
//#define SHOW_NUMERICAL_NORMALS // for comparison purposes
float hash( float n ) { return fract(sin(n)*753.5453123); }
//---------------------------------------------------------------
// value noise, and its analytical derivatives
//---------------------------------------------------------------
vec4 noised( in vec3 x )
{
vec3 p = floor(x);
vec3 w = fract(x);
vec3 u = w*w*(3.0-2.0*w);
vec3 du = 6.0*w*(1.0-w);
float n = p.x + p.y*157.0 + 113.0*p.z;
float a = hash(n+ 0.0);
float b = hash(n+ 1.0);
float c = hash(n+157.0);
float d = hash(n+158.0);
float e = hash(n+113.0);
float f = hash(n+114.0);
float g = hash(n+270.0);
float h = hash(n+271.0);
float k0 = a;
float k1 = b - a;
float k2 = c - a;
float k3 = e - a;
float k4 = a - b - c + d;
float k5 = a - c - e + g;
float k6 = a - b - e + f;
float k7 = - a + b + c - d + e - f - g + h;
return vec4( k0 + k1*u.x + k2*u.y + k3*u.z + k4*u.x*u.y + k5*u.y*u.z + k6*u.z*u.x + k7*u.x*u.y*u.z,
du * (vec3(k1,k2,k3) + u.yzx*vec3(k4,k5,k6) + u.zxy*vec3(k6,k4,k5) + k7*u.yzx*u.zxy ));
}
//---------------------------------------------------------------
vec4 sdBox( vec3 p, vec3 b ) // distance and normal
{
vec3 d = abs(p) - b;
float x = min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
vec3 n = step(d.yzx,d.xyz)*step(d.zxy,d.xyz)*sign(p);
return vec4( x, n );
}
vec4 fbmd( in vec3 x )
{
const float scale = 1.5;
float a = 0.0;
float b = 0.5;
float f = 1.0;
vec3 d = vec3(0.0);
for( int i=0; i<8; i++ )
{
vec4 n = noised(f*x*scale);
a += b*n.x; // accumulate values
d += b*n.yzw*f*scale; // accumulate derivatives
b *= 0.5; // amplitude decrease
f *= 1.8; // frequency increase
}
return vec4( a, d );
}
vec4 map( in vec3 p )
{
vec4 d1 = fbmd( p );
d1.x -= 0.37;
d1.x *= 0.7;
d1.yzw = normalize(d1.yzw);
// clip to box
vec4 d2 = sdBox( p, vec3(1.5) );
return (d1.x>d2.x) ? d1 : d2;
}
// ray-box intersection in box space
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 rad )
{
vec3 m = 1.0/rd;
vec3 n = m*ro;
vec3 k = abs(m)*rad;
vec3 t1 = -n - k;
vec3 t2 = -n + k;
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );
if( tN > tF || tF < 0.0) return vec2(-1.0);
return vec2( tN, tF );
}
// raymarch
vec4 interesect( in vec3 ro, in vec3 rd )
{
vec4 res = vec4(-1.0);
// bounding volume
vec2 dis = iBox( ro, rd, vec3(1.5) ) ;
if( dis.y<0.0 ) return res;
// raymarch
float tmax = dis.y;
float t = dis.x;
for( int i=0; i<128; i++ )
{
vec3 pos = ro + t*rd;
vec4 hnor = map( pos );
res = vec4(t,hnor.yzw);
if( hnor.x<0.001 ) break;
t += hnor.x;
if( t>tmax ) break;
}
if( t>tmax ) res = vec4(-1.0);
return res;
}
// compute normal numerically
#ifdef SHOW_NUMERICAL_NORMALS
vec3 calcNormal( in vec3 pos )
{
vec2 eps = vec2( 0.0001, 0.0 );
vec3 nor = vec3( map(pos+eps.xyy).x - map(pos-eps.xyy).x,
map(pos+eps.yxy).x - map(pos-eps.yxy).x,
map(pos+eps.yyx).x - map(pos-eps.yyx).x );
return normalize(nor);
}
#endif
// fibonazzi points in s aphsre, more info:
// http://lgdv.cs.fau.de/uploads/publications/spherical_fibonacci_mapping_opt.pdf
vec3 forwardSF( float i, float n)
{
const float PI = 3.141592653589793238;
const float PHI = 1.618033988749894848;
float phi = 2.0*PI*fract(i/PHI);
float zi = 1.0 - (2.0*i+1.0)/n;
float sinTheta = sqrt( 1.0 - zi*zi);
return vec3( cos(phi)*sinTheta, sin(phi)*sinTheta, zi);
}
float calcAO( in vec3 pos, in vec3 nor )
{
float ao = 0.0;
for( int i=0; i<32; i++ )
{
vec3 ap = forwardSF( float(i), 32.0 );
float h = hash(float(i));
ap *= sign( dot(ap,nor) ) * h*0.25;
ao += clamp( map( pos + nor*0.001 + ap ).x*3.0, 0.0, 1.0 );
}
ao /= 32.0;
return clamp( ao*5.0, 0.0, 1.0 );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 p = (2.0*fragCoord-iResolution.xy) / iResolution.y;
// camera anim
float an = 0.1*iTime;
vec3 ro = 3.0*vec3( cos(an), 0.8, sin(an) );
vec3 ta = vec3( 0.0 );
// camera matrix
vec3 cw = normalize( ta-ro );
vec3 cu = normalize( cross(cw,vec3(0.0,1.0,0.0)) );
vec3 cv = normalize( cross(cu,cw) );
vec3 rd = normalize( p.x*cu + p.y*cv + 1.7*cw );
// render
vec3 col = vec3(0.0);
vec4 tnor = interesect( ro, rd );
float t = tnor.x;
if( t>0.0 )
{
vec3 pos = ro + t*rd;
#ifndef SHOW_NUMERICAL_NORMALS
vec3 nor = tnor.yzw; // no need to call calcNormal( pos );
#else
vec3 nor = calcNormal( pos );
#endif
float occ = calcAO( pos, nor );
float fre = clamp( 1.0+dot(rd,nor), 0.0, 1.0 );
float fro = clamp( dot(nor,-rd), 0.0, 1.0 );
col = mix( vec3(0.05,0.2,0.3), vec3(1.0,0.95,0.85), 0.5+0.5*nor.y );
//col = 0.5+0.5*nor;
col += 10.0*pow(fro,12.0)*(0.04+0.96*pow(fre,5.0));
col *= pow(vec3(occ),vec3(1.0,1.1,1.1) );
}
col = sqrt(col);
fragColor=vec4(col,1.0);
} | mit | [
4779,
4905,
4941,
4941,
5205
] | [
[
1526,
1526,
1549,
1549,
1585
],
[
1768,
1768,
1794,
1794,
2629
],
[
2698,
2698,
2751,
2751,
2929
],
[
2931,
2931,
2955,
2955,
3380
],
[
3382,
3382,
3405,
3405,
3584
],
[
3586,
3623,
3674,
3674,
3942
],
[
3944,
3956,
3999,
3999,
4438
],
[
4779,
4905,
4941,
4941,
5205
],
[
5207,
5207,
5249,
5249,
5550
],
[
5552,
5552,
5609,
5609,
6718
]
] | // fibonazzi points in s aphsre, more info:
// http://lgdv.cs.fau.de/uploads/publications/spherical_fibonacci_mapping_opt.pdf
| vec3 forwardSF( float i, float n)
{ |
const float PI = 3.141592653589793238;
const float PHI = 1.618033988749894848;
float phi = 2.0*PI*fract(i/PHI);
float zi = 1.0 - (2.0*i+1.0)/n;
float sinTheta = sqrt( 1.0 - zi*zi);
return vec3( cos(phi)*sinTheta, sin(phi)*sinTheta, zi);
} | // fibonazzi points in s aphsre, more info:
// http://lgdv.cs.fau.de/uploads/publications/spherical_fibonacci_mapping_opt.pdf
vec3 forwardSF( float i, float n)
{ | 15 | 21 |
Mt3SWX | iq | 2017-01-08T04:48:49 | // The MIT License
// Copyright © 2016 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Analytical second derivatibes of value noise and fbm made with it. Used second
// derivatives to compute curvature.
float hash( float n ) { return fract(sin(n)*753.5453123); }
//---------------------------------------------------------------
// return.x = value noise
// return.xyz = derivatives
// out dd = hessian (second derivatives)
//---------------------------------------------------------------
vec4 noised( in vec3 x, out mat3 dd )
{
vec3 p = floor(x);
vec3 w = fract(x);
// cubic interpolation vs quintic interpolation
#if 0
vec3 u = w*w*(3.0-2.0*w);
vec3 du = 6.0*w*(1.0-w);
vec3 ddu = 6.0 - 12.0*w;
#else
vec3 u = w*w*w*(w*(w*6.0-15.0)+10.0);
vec3 du = 30.0*w*w*(w*(w-2.0)+1.0);
vec3 ddu = 60.0*w*(1.0+w*(-3.0+2.0*w));
#endif
float n = p.x + p.y*157.0 + 113.0*p.z;
float a = hash(n+ 0.0);
float b = hash(n+ 1.0);
float c = hash(n+157.0);
float d = hash(n+158.0);
float e = hash(n+113.0);
float f = hash(n+114.0);
float g = hash(n+270.0);
float h = hash(n+271.0);
float k0 = a;
float k1 = b - a;
float k2 = c - a;
float k3 = e - a;
float k4 = a - b - c + d;
float k5 = a - c - e + g;
float k6 = a - b - e + f;
float k7 = - a + b + c - d + e - f - g + h;
dd = mat3( ddu.x*(k1 + k4*u.y + k6*u.z + k7*u.y*u.z),
du.x*(k4+k7*u.z)*du.y,
du.x*(k6+k7*u.y)*du.z,
du.y*(k4+k7*u.z)*du.x,
ddu.y*(k2 + k5*u.z + k4*u.x + k7*u.z*u.x),
du.y*(k5+k7*u.x)*du.z,
du.z*(k6+k7*u.y)*du.x,
du.z*(k5+k7*u.x)*du.y,
ddu.z*(k3 + k6*u.x + k5*u.y + k7*u.x*u.y) );
return vec4( k0 + k1*u.x + k2*u.y + k3*u.z + k4*u.x*u.y + k5*u.y*u.z + k6*u.z*u.x + k7*u.x*u.y*u.z,
du * vec3( k1 + k4*u.y + k6*u.z + k7*u.y*u.z,
k2 + k5*u.z + k4*u.x + k7*u.z*u.x,
k3 + k6*u.x + k5*u.y + k7*u.x*u.y ) );
}
//---------------------------------------------------------------
vec4 sdBox( vec3 p, vec3 b ) // distance and normal
{
vec3 d = abs(p) - b;
float x = min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
vec3 n = step(d.yzx,d.xyz)*step(d.zxy,d.xyz)*sign(p);
return vec4( x, n );
}
vec4 fbmd( in vec3 x, out mat3 s )
{
const float scale = 1.5;
float a = 0.0;
float b = 0.5;
float f = 1.0;
vec3 d = vec3(0.0);
s = mat3(0.0);
for( int i=0; i<3; i++ )
{
mat3 dd;
vec4 n = noised(f*x*scale,dd);
a += b*n.x; // accumulate values
d += b*n.yzw*f*scale; // accumulate derivatives
s += b*dd*f*f*scale*scale; // accumulate second derivative
b *= 0.5;
f *= 1.8;
}
return vec4( a, d );
}
vec4 map( in vec3 p, out mat3 s )
{
mat3 dd;
vec4 d1 = fbmd( p, dd );
d1.x -= 0.33;
d1.x *= 0.7;
d1.yzw = 0.7*d1.yzw;
dd *= 0.7;
// clip to box
vec4 d2 = sdBox( p, vec3(1.5) );
if(d1.x>d2.x)
{
s = dd;
return d1;
}
s = mat3(0.0);
return d2;
}
// ray-box intersection in box space
vec2 iBox( in vec3 ro, in vec3 rd, in vec3 rad )
{
vec3 m = 1.0/rd;
vec3 n = m*ro;
vec3 k = abs(m)*rad;
vec3 t1 = -n - k;
vec3 t2 = -n + k;
float tN = max( max( t1.x, t1.y ), t1.z );
float tF = min( min( t2.x, t2.y ), t2.z );
if( tN > tF || tF < 0.0) return vec2(-1.0);
return vec2( tN, tF );
}
// raymarch
vec4 interesect( in vec3 ro, in vec3 rd, out mat3 resS )
{
vec4 res = vec4(-1.0);
resS = mat3(0.0);
// bounding volume
vec2 dis = iBox( ro, rd, vec3(1.5) ) ;
if( dis.y<0.0 ) return res;
// raymarch
float tmax = dis.y;
float t = dis.x;
for( int i=0; i<128; i++ )
{
vec3 pos = ro + t*rd;
mat3 dd;
vec4 hnor = map( pos, dd );
res = vec4(t,hnor.yzw);
resS = dd;
if( hnor.x<0.0001 ) break;
t += hnor.x;
if( t>tmax ) break;
}
if( t>tmax ) res = vec4(-1.0);
return res;
}
// fibonazzi points in s aphsre, more info:
// http://lgdv.cs.fau.de/uploads/publications/spherical_fibonacci_mapping_opt.pdf
vec3 forwardSF( float i, float n)
{
const float PI = 3.141592653589793238;
const float PHI = 1.618033988749894848;
float phi = 2.0*PI*fract(i/PHI);
float zi = 1.0 - (2.0*i+1.0)/n;
float sinTheta = sqrt( 1.0 - zi*zi);
return vec3( cos(phi)*sinTheta, sin(phi)*sinTheta, zi);
}
float calcAO( in vec3 pos, in vec3 nor )
{
float ao = 0.0;
for( int i=0; i<32; i++ )
{
vec3 ap = forwardSF( float(i), 32.0 );
float h = hash(float(i));
ap *= sign( dot(ap,nor) ) * h*0.25;
mat3 kk;
ao += clamp( map( pos + nor*0.001 + ap, kk ).x*3.0, 0.0, 1.0 );
}
ao /= 32.0;
return clamp( ao*5.0, 0.0, 1.0 );
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 p = (-iResolution.xy + 2.0*fragCoord.xy) / iResolution.y;
// camera anim
float an = 0.1*iTime;
vec3 ro = 3.0*vec3( cos(an), 0.8, sin(an) );
vec3 ta = vec3( 0.0 );
// camera matrix
vec3 cw = normalize( ta-ro );
vec3 cu = normalize( cross(cw,vec3(0.0,1.0,0.0)) );
vec3 cv = normalize( cross(cu,cw) );
vec3 rd = normalize( p.x*cu + p.y*cv + 1.7*cw );
// render
vec3 col = vec3(0.0);
mat3 dd;
vec4 tnor = interesect( ro, rd, dd );
float t = tnor.x;
if( t>0.0 )
{
vec3 pos = ro + t*rd;
vec3 nor = normalize(tnor.yzw);
float occ = calcAO( pos, nor );
vec3 d = tnor.yzw;
// compute curvature
mat4 mm = mat4( dd[0].x, dd[0].y, dd[0].z, d.x,
dd[1].x, dd[1].y, dd[1].z, d.y,
dd[2].x, dd[2].y, dd[2].z, d.z,
d.x, d.y, d.z, 0.0 );
float k = -determinant(mm)/(dot(d,d)*dot(d,d));
// shape it a bit
k = sign(k)*pow( abs(k), 1.0/3.0 );
if( k<0.0) col = vec3(1.0,0.7,0.2); else col = vec3(0.2,0.8,1.0); col *= abs(k*0.2);
if( abs(k)<0.0001 ) col = vec3(0.1);
col *= occ;
col *= 0.7 + 0.3*nor.y;
}
col = sqrt(col);
fragColor=vec4(col,1.0);
} | mit | [
4619,
4631,
4689,
4689,
5181
] | [
[
1201,
1201,
1224,
1224,
1260
],
[
1494,
1494,
1533,
1533,
3128
],
[
3197,
3197,
3250,
3250,
3428
],
[
3430,
3430,
3466,
3466,
3939
],
[
3941,
3941,
3976,
3976,
4259
],
[
4261,
4298,
4349,
4349,
4617
],
[
4619,
4631,
4689,
4689,
5181
],
[
5184,
5310,
5346,
5346,
5610
],
[
5612,
5612,
5654,
5654,
5976
],
[
5979,
5979,
6036,
6036,
7308
]
] | // raymarch
| vec4 interesect( in vec3 ro, in vec3 rd, out mat3 resS )
{ |
vec4 res = vec4(-1.0);
resS = mat3(0.0);
// bounding volume
vec2 dis = iBox( ro, rd, vec3(1.5) ) ;
if( dis.y<0.0 ) return res;
// raymarch
float tmax = dis.y;
float t = dis.x;
for( int i=0; i<128; i++ )
{
vec3 pos = ro + t*rd;
mat3 dd;
vec4 hnor = map( pos, dd );
res = vec4(t,hnor.yzw);
resS = dd;
if( hnor.x<0.0001 ) break;
t += hnor.x;
if( t>tmax ) break;
}
if( t>tmax ) res = vec4(-1.0);
return res;
} | // raymarch
vec4 interesect( in vec3 ro, in vec3 rd, out mat3 resS )
{ | 1 | 1 |
XdXBRH | iq | 2017-05-14T07:01:57 | // The MIT License
// Copyright © 2017 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// https://www.youtube.com/c/InigoQuilez
// https://iquilezles.org
// Computes the analytic derivatives of a 2D Gradient Noise
// Value Noise 2D, Derivatives: https://www.shadertoy.com/view/4dXBRH
// Gradient Noise 2D, Derivatives: https://www.shadertoy.com/view/XdXBRH
// Value Noise 3D, Derivatives: https://www.shadertoy.com/view/XsXfRH
// Gradient Noise 3D, Derivatives: https://www.shadertoy.com/view/4dffRH
// Value Noise 2D : https://www.shadertoy.com/view/lsf3WH
// Value Noise 3D : https://www.shadertoy.com/view/4sfGzS
// Gradient Noise 2D : https://www.shadertoy.com/view/XdXGW8
// Gradient Noise 3D : https://www.shadertoy.com/view/Xsl3Dl
// Simplex Noise 2D : https://www.shadertoy.com/view/Msf3WH
// Wave Noise 2D : https://www.shadertoy.com/view/tldSRj
vec2 hash( in vec2 x ) // replace this by something better
{
const vec2 k = vec2( 0.3183099, 0.3678794 );
x = x*k + k.yx;
return -1.0 + 2.0*fract( 16.0 * k*fract( x.x*x.y*(x.x+x.y)) );
}
// return gradient noise (in x) and its derivatives (in yz)
vec3 noised( in vec2 p )
{
vec2 i = floor( p );
vec2 f = fract( p );
#if 1
// quintic interpolation
vec2 u = f*f*f*(f*(f*6.0-15.0)+10.0);
vec2 du = 30.0*f*f*(f*(f-2.0)+1.0);
#else
// cubic interpolation
vec2 u = f*f*(3.0-2.0*f);
vec2 du = 6.0*f*(1.0-f);
#endif
vec2 ga = hash( i + vec2(0.0,0.0) );
vec2 gb = hash( i + vec2(1.0,0.0) );
vec2 gc = hash( i + vec2(0.0,1.0) );
vec2 gd = hash( i + vec2(1.0,1.0) );
float va = dot( ga, f - vec2(0.0,0.0) );
float vb = dot( gb, f - vec2(1.0,0.0) );
float vc = dot( gc, f - vec2(0.0,1.0) );
float vd = dot( gd, f - vec2(1.0,1.0) );
return vec3( va + u.x*(vb-va) + u.y*(vc-va) + u.x*u.y*(va-vb-vc+vd), // value
ga + u.x*(gb-ga) + u.y*(gc-ga) + u.x*u.y*(ga-gb-gc+gd) + // derivatives
du * (u.yx*(va-vb-vc+vd) + vec2(vb,vc) - va));
}
// -----------------------------------------------
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 p = (2.0*fragCoord-iResolution.xy)/iResolution.y;
vec3 n = noised( 8.0*p + iTime*4.0 );
vec3 col = 0.5 + 0.5*((p.x>0.0) ? n.yzx : n.xxx);
fragColor = vec4( col, 1.0 );
} | mit | [
2142,
2202,
2228,
2228,
3094
] | [
[
1940,
1940,
2001,
2001,
2139
],
[
2142,
2202,
2228,
2228,
3094
],
[
3148,
3148,
3205,
3205,
3404
]
] | // return gradient noise (in x) and its derivatives (in yz)
| vec3 noised( in vec2 p )
{ |
vec2 i = floor( p );
vec2 f = fract( p );
#if 1
// quintic interpolation
vec2 u = f*f*f*(f*(f*6.0-15.0)+10.0);
vec2 du = 30.0*f*f*(f*(f-2.0)+1.0);
#else
// cubic interpolation
vec2 u = f*f*(3.0-2.0*f);
vec2 du = 6.0*f*(1.0-f);
#endif
vec2 ga = hash( i + vec2(0.0,0.0) );
vec2 gb = hash( i + vec2(1.0,0.0) );
vec2 gc = hash( i + vec2(0.0,1.0) );
vec2 gd = hash( i + vec2(1.0,1.0) );
float va = dot( ga, f - vec2(0.0,0.0) );
float vb = dot( gb, f - vec2(1.0,0.0) );
float vc = dot( gc, f - vec2(0.0,1.0) );
float vd = dot( gd, f - vec2(1.0,1.0) );
return vec3( va + u.x*(vb-va) + u.y*(vc-va) + u.x*u.y*(va-vb-vc+vd), // value
ga + u.x*(gb-ga) + u.y*(gc-ga) + u.x*u.y*(ga-gb-gc+gd) + // derivatives
du * (u.yx*(va-vb-vc+vd) + vec2(vb,vc) - va));
} | // return gradient noise (in x) and its derivatives (in yz)
vec3 noised( in vec2 p )
{ | 23 | 26 |
XtBfzz | iq | 2017-12-25T05:25:25 | // The MIT License
// Copyright © 2017 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Analiyically filtering a grid pattern (ie, not using supersampling or mipmapping.
//
// Info: http://iquilezles.org/www/articles/filterableprocedurals/filterableprocedurals.htm
//
// More filtered patterns: https://www.shadertoy.com/playlist/l3KXR1
// --- analytically box-filtered grid ---
const float N = 10.0; // grid ratio
float gridTextureGradBox( in vec2 p, in vec2 ddx, in vec2 ddy )
{
// filter kernel
vec2 w = max(abs(ddx), abs(ddy)) + 0.01;
// analytic (box) filtering
vec2 a = p + 0.5*w;
vec2 b = p - 0.5*w;
vec2 i = (floor(a)+min(fract(a)*N,1.0)-
floor(b)-min(fract(b)*N,1.0))/(N*w);
//pattern
return (1.0-i.x)*(1.0-i.y);
}
// --- unfiltered grid ---
float gridTexture( in vec2 p )
{
// coordinates
vec2 i = step( fract(p), vec2(1.0/N) );
//pattern
return (1.0-i.x)*(1.0-i.y); // grid (N=10)
// other possible patterns are these
//return 1.0-i.x*i.y; // squares (N=4)
//return 1.0-i.x-i.y+2.0*i.x*i.y; // checker (N=2)
}
//===============================================================================================
//===============================================================================================
// sphere implementation
//===============================================================================================
//===============================================================================================
float softShadowSphere( in vec3 ro, in vec3 rd, in vec4 sph )
{
vec3 oc = sph.xyz - ro;
float b = dot( oc, rd );
float res = 1.0;
if( b>0.0 )
{
float h = dot(oc,oc) - b*b - sph.w*sph.w;
res = smoothstep( 0.0, 1.0, 2.0*h/b );
}
return res;
}
float occSphere( in vec4 sph, in vec3 pos, in vec3 nor )
{
vec3 di = sph.xyz - pos;
float l = length(di);
return 1.0 - dot(nor,di/l)*sph.w*sph.w/(l*l);
}
float iSphere( in vec3 ro, in vec3 rd, in vec4 sph )
{
float t = -1.0;
vec3 ce = ro - sph.xyz;
float b = dot( rd, ce );
float c = dot( ce, ce ) - sph.w*sph.w;
float h = b*b - c;
if( h>0.0 )
{
t = -b - sqrt(h);
}
return t;
}
//===============================================================================================
//===============================================================================================
// scene
//===============================================================================================
//===============================================================================================
// spheres
const vec4 sc0 = vec4( 3.0, 0.5, 0.0, 0.5 );
const vec4 sc1 = vec4( -4.0, 2.0,-5.0, 2.0 );
const vec4 sc2 = vec4( -4.0, 2.0, 5.0, 2.0 );
const vec4 sc3 = vec4(-30.0, 8.0, 0.0, 8.0 );
float intersect( vec3 ro, vec3 rd, out vec3 pos, out vec3 nor, out float occ, out int matid )
{
// raytrace
float tmin = 10000.0;
nor = vec3(0.0);
occ = 1.0;
pos = vec3(0.0);
matid = -1;
// raytrace-plane
float h = (0.01-ro.y)/rd.y;
if( h>0.0 )
{
tmin = h;
nor = vec3(0.0,1.0,0.0);
pos = ro + h*rd;
matid = 0;
occ = occSphere( sc0, pos, nor ) *
occSphere( sc1, pos, nor ) *
occSphere( sc2, pos, nor ) *
occSphere( sc3, pos, nor );
}
// raytrace-sphere
h = iSphere( ro, rd, sc0 );
if( h>0.0 && h<tmin )
{
tmin = h;
pos = ro + h*rd;
nor = normalize(pos-sc0.xyz);
matid = 1;
occ = 0.5 + 0.5*nor.y;
}
h = iSphere( ro, rd, sc1 );
if( h>0.0 && h<tmin )
{
tmin = h;
pos = ro + tmin*rd;
nor = normalize(pos-sc1.xyz);
matid = 2;
occ = 0.5 + 0.5*nor.y;
}
h = iSphere( ro, rd, sc2 );
if( h>0.0 && h<tmin )
{
tmin = h;
pos = ro + tmin*rd;
nor = normalize(pos-sc2.xyz);
matid = 3;
occ = 0.5 + 0.5*nor.y;
}
h = iSphere( ro, rd, sc3 );
if( h>0.0 && h<tmin )
{
tmin = h;
pos = ro + tmin*rd;
nor = normalize(pos-sc3.xyz);
matid = 4;
occ = 0.5 + 0.5*nor.y;
}
return tmin;
}
vec2 texCoords( in vec3 pos, int mid )
{
vec2 matuv;
if( mid==0 )
{
matuv = pos.xz;
}
else if( mid==1 )
{
vec3 q = normalize( pos - sc0.xyz );
matuv = vec2( atan(q.x,q.z), acos(q.y ) )*sc0.w;
}
else if( mid==2 )
{
vec3 q = normalize( pos - sc1.xyz );
matuv = vec2( atan(q.x,q.z), acos(q.y ) )*sc1.w;
}
else if( mid==3 )
{
vec3 q = normalize( pos - sc2.xyz );
matuv = vec2( atan(q.x,q.z), acos(q.y ) )*sc2.w;
}
else if( mid==4 )
{
vec3 q = normalize( pos - sc3.xyz );
matuv = vec2( atan(q.x,q.z), acos(q.y ) )*sc3.w;
}
return 8.0*matuv;
}
void calcCamera( out vec3 ro, out vec3 ta )
{
float an = 0.1*sin(0.1*iTime);
ro = vec3( 5.0*cos(an), 0.5, 5.0*sin(an) );
ta = vec3( 0.0, 1.0, 0.0 );
}
vec3 doLighting( in vec3 pos, in vec3 nor, in float occ, in vec3 rd )
{
float sh = min( min( min( softShadowSphere( pos, vec3(0.57703), sc0 ),
softShadowSphere( pos, vec3(0.57703), sc1 )),
softShadowSphere( pos, vec3(0.57703), sc2 )),
softShadowSphere( pos, vec3(0.57703), sc3 ));
float dif = clamp(dot(nor,vec3(0.57703)),0.0,1.0);
float bac = clamp(0.5+0.5*dot(nor,vec3(-0.707,0.0,-0.707)),0.0,1.0);
vec3 lin = dif*vec3(1.50,1.40,1.30)*sh;
lin += occ*vec3(0.15,0.20,0.30);
lin += bac*vec3(0.10,0.10,0.10)*(0.2+0.8*occ);
return lin;
}
//===============================================================================================
//===============================================================================================
// render
//===============================================================================================
//===============================================================================================
void calcRayForPixel( in vec2 pix, out vec3 resRo, out vec3 resRd )
{
vec2 p = (2.0*pix-iResolution.xy) / iResolution.y;
// camera movement
vec3 ro, ta;
calcCamera( ro, ta );
// camera matrix
vec3 ww = normalize( ta - ro );
vec3 uu = normalize( cross(ww,vec3(0.0,1.0,0.0) ) );
vec3 vv = normalize( cross(uu,ww));
// create view ray
vec3 rd = normalize( p.x*uu + p.y*vv + 2.0*ww );
resRo = ro;
resRd = rd;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 p = (-iResolution.xy + 2.0*fragCoord) / iResolution.y;
float th = (iMouse.z>0.001) ? (2.0*iMouse.x-iResolution.x)/iResolution.y : 0.0;
vec3 ro, rd, ddx_ro, ddx_rd, ddy_ro, ddy_rd;
calcRayForPixel( fragCoord + vec2(0.0,0.0), ro, rd );
calcRayForPixel( fragCoord + vec2(1.0,0.0), ddx_ro, ddx_rd );
calcRayForPixel( fragCoord + vec2(0.0,1.0), ddy_ro, ddy_rd );
// trace
vec3 pos, nor;
float occ;
int mid;
float t = intersect( ro, rd, pos, nor, occ, mid );
vec3 col = vec3(0.9);
if( mid!=-1 )
{
#if 1
// -----------------------------------------------------------------------
// compute ray differentials by intersecting the tangent plane to the
// surface.
// -----------------------------------------------------------------------
// computer ray differentials
vec3 ddx_pos = ddx_ro - ddx_rd*dot(ddx_ro-pos,nor)/dot(ddx_rd,nor);
vec3 ddy_pos = ddy_ro - ddy_rd*dot(ddy_ro-pos,nor)/dot(ddy_rd,nor);
// calc texture sampling footprint
vec2 uv = texCoords( pos, mid );
vec2 ddx_uv = texCoords( ddx_pos, mid ) - uv;
vec2 ddy_uv = texCoords( ddy_pos, mid ) - uv;
#else
// -----------------------------------------------------------------------
// Because we are in the GPU, we do have access to differentials directly
// This wouldn't be the case in a regular raytracer.
// It wouldn't work as well in shaders doing interleaved calculations in
// pixels (such as some of the 3D/stereo shaders here in Shadertoy)
// -----------------------------------------------------------------------
vec2 uvw = texCoords( pos, mid );
// calc texture sampling footprint
vec2 ddx_uvw = dFdx( uvw );
vec2 ddy_uvw = dFdy( uvw );
#endif
// shading
vec3 mate = vec3(0.0);
if( p.x<th ) mate = vec3(1.0)*gridTexture( uv );
else mate = vec3(1.0)*gridTextureGradBox( uv, ddx_uv, ddy_uv );
// lighting
vec3 lin = doLighting( pos, nor, occ, rd );
// combine lighting with material
col = mate * lin;
// fog
col = mix( col, vec3(0.9), 1.0-exp( -0.00001*t*t ) );
}
// gamma correction
col = pow( col, vec3(0.4545) );
col *= smoothstep( 1.0, 2.0, abs(p.x-th)/(2.0/iResolution.y) );
fragColor = vec4( col, 1.0 );
} | mit | [
1401,
1415,
1480,
1498,
1799
] | [
[
1401,
1415,
1480,
1498,
1799
],
[
1829,
1829,
1861,
1880,
2143
],
[
2564,
2564,
2627,
2627,
2850
],
[
2852,
2852,
2910,
2910,
3018
],
[
3020,
3020,
3074,
3074,
3260
],
[
3861,
3861,
3956,
3972,
5070
],
[
5072,
5072,
5112,
5112,
5752
],
[
5755,
5755,
5800,
5800,
5911
],
[
5913,
5913,
5984,
5984,
6541
],
[
6945,
6945,
7014,
7014,
7384
],
[
7386,
7386,
7443,
7443,
9767
]
] | // grid ratio
| float gridTextureGradBox( in vec2 p, in vec2 ddx, in vec2 ddy )
{ |
vec2 w = max(abs(ddx), abs(ddy)) + 0.01;
// analytic (box) filtering
vec2 a = p + 0.5*w;
vec2 b = p - 0.5*w;
vec2 i = (floor(a)+min(fract(a)*N,1.0)-
floor(b)-min(fract(b)*N,1.0))/(N*w);
//pattern
return (1.0-i.x)*(1.0-i.y);
} | // grid ratio
float gridTextureGradBox( in vec2 p, in vec2 ddx, in vec2 ddy )
{ | 2 | 6 |
4dKfDV | iq | 2018-07-03T04:37:50 | // The MIT License
// Copyright © 2018 Inigo Quilez
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#define AA 4 // make this 1 is your machine is too slow
//------------------------------------------------------------------
const vec2 torus = vec2(0.5,0.2);
float map( in vec3 p )
{
return length( vec2(length(p.xz)-torus.x,p.y) )-torus.y;
}
// gradient/derivative of map (common factors removed)
vec3 dmap( in vec3 p )
{
return p*(1.0 - vec3(1,0,1)*torus.x/length(p.xz));
//return p*(dot(p,p)-torus.y*torus.y-torus.x*torus.x*vec3(1.0,-1.0,1.0));
}
vec2 castRay( in vec3 ro, in vec3 rd )
{
// plane
float tmax = (-torus.y-ro.y)/rd.y;
// torus
float t = 1.0;
float m = 2.0;
for( int i=0; i<100; i++ )
{
float precis = 0.0004*t;
float res = map( ro+rd*t );
if( res<precis || t>tmax ) break;
t += res;
}
if( t>tmax ) { t=tmax; m=1.0; }
return vec2( t, m );
}
float calcSoftshadow( in vec3 ro, in vec3 rd )
{
float res = 1.0;
float t = 0.02;
for( int i=0; i<12; i++ )
{
float h = map( ro + rd*t );
res = min( res,18.0*h/t );
t += clamp( h, 0.05, 0.10 );
if( res<0.005 || t>1.0 ) break;
}
return clamp( res, 0.0, 1.0 );
}
vec3 hexagon_pattern( vec2 p )
{
vec2 q = vec2( p.x*2.0*0.5773503, p.y + p.x*0.5773503 );
vec2 pi = floor(q);
vec2 pf = fract(q);
float v = mod(pi.x + pi.y, 3.0);
float ca = step(1.0,v);
float cb = step(2.0,v);
vec2 ma = step(pf.xy,pf.yx);
return vec3( pi + ca - cb*ma, dot( ma, 1.0-pf.yx + ca*(pf.x+pf.y-1.0) + cb*(pf.yx-2.0*pf.xy) ) );
}
vec3 render( in vec3 ro, in vec3 rd )
{
vec3 col = vec3(0.0);
vec2 res = castRay(ro,rd);
vec3 pos = ro + rd*res.x;
vec3 nor = vec3(0.0,1.0,0.0);
float occ = 1.0;
// plane
if( res.y<1.5 )
{
// fake occlusion
occ = smoothstep(0.0,0.42, abs(length(pos.xz)-torus.x) );
// texture
#if 0
vec3 h = hexagon_pattern(pos.xz*4.);
float f = mod(h.x+2.0*h.y,3.0)/2.0 ;
#else
float f = float( (int(floor(2.0*pos.x))+int(floor(2.0*pos.z)))&1);
#endif
col = vec3(0.3 + f*0.1);
}
// torus
else
{
// analytic torus normal
nor = normalize( dmap(pos) );
// fake occlusion
occ = 0.5 + 0.5*nor.y;
// texture
vec2 uv = vec2(atan(pos.z,pos.x),atan(length(pos.xz)-torus.x,pos.y) )*
vec2(12.0*sqrt(3.0), 8.0)/3.14159;
uv.y += iTime;
vec3 h = hexagon_pattern( uv );
col = vec3( mod(h.x+2.0*h.y,3.0)/2.0 );
//col = mix(col,vec3(0.0), 1.0-smoothstep(0.02,0.05,h.z)); // aliased
col = mix(col,vec3(0.0),clamp(1.3*(1.0-smoothstep(0.01*res.x,0.05*res.x,h.z))/res.x,0.0,1.0)); // somehow filtered
}
// lighting
vec3 lig = normalize( vec3(0.4, 0.5, -0.6) );
vec3 hal = normalize( lig-rd );
float amb = clamp( 0.65+0.35*nor.y, 0.0, 1.0 );
float dif = clamp( dot( nor, lig ), 0.0, 1.0 );
float bac = clamp( dot( nor, normalize(vec3(-lig.x,0.0,-lig.z))), 0.0, 1.0 );
dif *= calcSoftshadow( pos, lig );
float spe = pow( clamp( dot( nor, hal ), 0.0, 1.0 ),32.0) *
dif *
(0.04 + 0.96*pow( clamp(1.0+dot(hal,rd),0.0,1.0), 5.0 ));
vec3 lin = vec3(0.0);
lin += 1.63*dif*vec3(1.15,0.90,0.55);
lin += 0.50*amb*vec3(0.30,0.60,1.50)*occ;
lin += 0.30*bac*vec3(0.40,0.30,0.25)*occ;
col = col*lin;
col += 6.00*spe*vec3(1.15,0.90,0.55);
return col;
}
void mainImage( out vec4 fragColor, in vec2 fragCoord )
{
vec2 mo = iMouse.xy/iResolution.xy;
// camera
vec3 ro = vec3( 1.3*cos(0.05*iTime + 6.0*mo.x), 1.1, 1.3*sin(0.05*iTime + 6.0*mo.x) );
vec3 ta = vec3( 0.0, -0.2, 0.0 );
// camera-to-world transformation
vec3 cw = normalize(ta-ro);
vec3 cu = normalize(vec3(-cw.z,0.0,cw.x));
vec3 cv = (cross(cu,cw) );
vec4 tot = vec4(0.0);
#if AA>1
for( int m=0; m<AA; m++ )
for( int n=0; n<AA; n++ )
{
// pixel coordinates
vec2 o = (vec2(float(m),float(n)) / float(AA-1) - 0.5)*1.7; // 1.7 pixels wide
vec2 p = (-iResolution.xy + 2.0*(fragCoord+o))/iResolution.y;
#else
vec2 p = (-iResolution.xy + 2.0*fragCoord)/iResolution.y;
#endif
// ray direction
vec3 rd = normalize( p.x*cu + p.y*cv + 2.0*cw );
// render
vec3 col = render( ro, rd );
// gamma (before reconstruction/filtering)
col = pow( col, vec3(0.4545) );
#if AA>1
// triangular reconstruction filter, kernel 2.0 pixels wide
float w = clamp(1.0 - length(o)/1.0,0.0,1.0);
tot.xyz += w*col;
tot.w += w;
#else
tot.xyz = col;
#endif
#if AA>1
}
tot /= tot.w;
#endif
// grading
tot.xyz = pow(tot.xyz,vec3(0.8,0.9,1.0) );
// vignetting
vec2 q = fragCoord/iResolution.xy;
tot.xyz *= 0.3 + 0.7*pow(16.0*q.x*q.y*(1.0-q.x)*(1.0-q.y),0.25);
fragColor = vec4( tot.xyz, 1.0 );
} | mit | [
1333,
1388,
1412,
1412,
1545
] | [
[
1244,
1244,
1268,
1268,
1331
],
[
1333,
1388,
1412,
1412,
1545
],
[
1547,
1547,
1587,
1600,
1924
],
[
1927,
1927,
1975,
1975,
2234
],
[
2236,
2236,
2269,
2269,
2591
]
] | // gradient/derivative of map (common factors removed)
| vec3 dmap( in vec3 p )
{ |
return p*(1.0 - vec3(1,0,1)*torus.x/length(p.xz));
//return p*(dot(p,p)-torus.y*torus.y-torus.x*torus.x*vec3(1.0,-1.0,1.0));
} | // gradient/derivative of map (common factors removed)
vec3 dmap( in vec3 p )
{ | 1 | 1 |
lldyzM | ollj | 2018-07-20T10:46:29 | //self https://www.shadertoy.com/view/lldyzM
//analytical filter kernel,triangular
//https://www.shadertoy.com/view/llffWs
// Similar to https://www.shadertoy.com/view/XlXBWs,but with a triangular filter kernel,
// which produces less flickering animations that a box filter. Luckily,it's still easily
// http://iquilezles.org/www/articles/morecheckerfiltering/morecheckerfiltering.htm
// checker,2D,box filter: https://www.shadertoy.com/view/XlcSz2
// checker,3D,box filter: https://www.shadertoy.com/view/XlXBWs
// checker,3D,tri filter: https://www.shadertoy.com/view/llffWs
// grid,2D,box filter: https://www.shadertoy.com/view/XtBfzz
// The MIT License
//https://www.shadertoy.com/view/llffWs
// Copyright © 2017 Inigo Quilez
// Permission is hereby granted,free of charge,to any person obtaining a copy of this software and associated documentation files(the "Software"),to dealthe Software without restriction,including without limitation the rights to use,copy,modify,merge,publish,distribute,sublicense,and/or sell copies of the Software,and to permit persons to whom the Software is furnished to do so,subject to the following conditions: The above copyright notice and this permission notice shall be includedall copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER LIABILITY,WHETHERAN ACTION OF CONTRACT,TORT OR OTHERWISE,ARISING FROM,OUT OF ORCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGSTHE SOFTWARE.
/* ---snippety blog summary esplanation
//fwidth(a,b)=abs(dfdx(p))+abs(dfdy(p))
#define maab(a,b)max(abs(a),abs(b))
the m-parameter is a value,returned from maab(),which may be calculated for multiple textures to be mixed,so it is moved out of the function.
//llffWs is tri-filtering AND box filtering,but it does not need the double integral,but other shaders calculate a double integral.
//there is this double-integral blog post this snioppet is all about:
the basic idea is to smoothen a discontinuity with an antiderivative
"cubic filters" are most common in CG,but this isr "tiangle-filter"ed weights,worse than cubic,better than the box filtering above
f(x)is the square-wave base signal that begs to be filtered.
box-filter formula is integralfromToOf(-w/2,w/2,f(x)dx)
tri-filter formula is integralfromToOf(-w,0,f(x)dx*(w+x)/w)+integralfromtoOf(0,w,f(x)dx*(w-x)/w)
these integrals are integralfromToOf(uv-w/2,uv+w/2,...),but shifting the center simplifies this function.
these integrals are done by [integration by parts],which has lots of symmetries that cancel each other out to:
tri-filter formula is(p(-w*.5)-2.*p(0.)+p(w*.5))/w/w
where p(x)is the antidetivative to f(x)(the striangle wave to the square wave.)
where s(x)is the double-integral of f(x)== the antidefivative of p(x)=an infinite smoothstep function.
//still no double-integrals needed!
vec3 sqrAndIntegrals(float x
){x*=.5;float h=fract(x)-.5,s=-sign(h),t=abs(h)*2.-1.)
;return(s,t,x+h*t);}//return vec3(square,tri(integral),smoothsteps(doubleIntegral))
vec2 fTri(vec2 x){vec2 h=fract(x*.5)-.5);return x*.5-h*(abs(h)*2.-1.);}//;return x*.5+h*(1.-2.*abs(h))
float TriFilteredCheckers(vec2 uv,vec2 w//w=maab(dpdx,dpdy)filter kernel
){w+.001
;vec2 i=(fTri(uw+w)-2.*fTri(uw)+ftri(uv-w))/(w*w)//analytic integral,3TapFilter function
;return .5-.5*i.x-i.y//xor-pattern
;}
//still no double-integrals needed!
//anyways,that would be curvature,what use is curvature for surface filtering?
*/
#define scale 5.
// spheres
const vec4 sc0=vec4(2,.5,.8,.5);
const vec4 sc1=vec4(-6,1,-4.,3);
const vec4 sc2=vec4(-16,1,7,4);
const vec4 sc3=vec4(-25,8,0,9);
struct v33{vec3 a;vec3 b;};
//and this ray-transpose function is the strangest of em all to be useful here:
void rayTransp(inout v33 a,inout v33 b){vec3 s=a.b;a.b=b.a;b.a=s;}//swap direction(.b)of [a] with origin(.a)of [b]
v33 sub(v33 a,vec3 b){return v33(a.a-b,a.b-b);}//substract b from all ray components
//component wise ray substraction(this one is a bit odd,differential wise,is basically scaling a rays points)
v33 subc(v33 a,v33 b){return v33(a.a-b.a,a.b-b.b);}//it makes sense in
v33 subc(vec2 a,v33 b){return v33(a.x-b.a,a.x-b.b);}//the context of
v33 subc(v33 a,vec2 b){return v33(a.a-b.x,a.b-b.y);}//v33-differentials for AA
vec2 dt(v33 a,v33 b){return vec2(dot(a.a,b.a),dot(a.b,b.b));}//dual dotprodiuct on v33s
vec2 dt(v33 a,vec3 b){return dt(a,v33(b,b));}
v33 div(v33 a,vec2 b){return v33(a.a/b.x,a.b/b.y);}
v33 mul(v33 a,v33 b){return v33(a.a*b.a,a.b*b.b);}//dual mult
v33 mul(v33 a,vec2 b){return v33(a.a*b.x,a.b*b.y);}
v33 mul(v33 a,float b){return v33(a.a*b,a.b*b);}
float sat(float a){return clamp(a,0.,1.);}
#define dd(a)dot(a,a)
//half-identity-scaling,labeled uN because it scales uv space,usually within a modulo context.
#define u2(a)((a)*2.-1.)
#define u5(a)((a)*.5+.5)
//u3(a)=1.-u2(a)!
//u6(a)=1.-u2(a)!
#define u3(a)(1.-(a)*2.)
#define u6(a)(.5-(a)*.5)
#define maab(a,b)max(abs(a),abs(b))
vec3 maab2(v33 a){return maab(a.a,a.b);}
float suv(vec3 a){return a.x+a.y+a.z;}
float prv(vec3 a){return a.x*a.y*a.z;}
float miv(vec2 a){return min(a.x,a.y);}
float miv(vec4 a){return min(miv(a.xy),miv(a.zw));}
float ss01(float a){return smoothstep(0.,1.,a);}
// ---unfiltered checkerboard ---
#define checker(a)mod(suv(floor(a)),2.)
//analytically triangle-filtered checkerboard: https://www.shadertoy.com/view/MtffWs
#define Fa(a,b)u2(abs(b-.5))
#define Fb(a,b)((a)*.5-((b)-.5)*Fa(a,b))
#define tri(a,b)b(a,fract((a)*.5))
//noe to self,maybe replace iMouse.y by abs(angleBetween(rayDirection,Normal))/quaterRotation
//tri(a,Fa)2xTap for box-filtering,used a lot in CG
float checkerF2(vec3 p,vec3 w){w+=iMouse.y/iResolution.y//filter kernel increase this value over inverse squared distance?
;return u6(prv((tri(p-.5*w,Fa)-tri(p+.5*w,Fa))/w));}//analytical integral(box filter),xor pattern
//tri(a,Fb)3xTap for tri-filtering,is slightly better than checkerF2()
float checkerF3(vec3 p,vec3 w){w+=iMouse.y/iResolution.y//filter kernel increase this value over inverse squared distance?
;return u6(prv((tri(p+w,Fb)-2.*tri(p,Fb)+tri(p-w,Fb))/(w*w)));}// analytical integral(tri filter),xor pattern
//sphere softShadow of(ray,sphere)
float sssp(v33 r,vec4 s){vec3 oc=s.xyz-r.a;float b=dot(oc,r.b),z=1.;if(b>0.){float h=dd(oc)-b*b-s.w*s.w;z=ss01(2.*h/b);}return z;}
//sphere occlusion
float occSphere(vec3 u,vec3 n,vec4 s){vec3 i=s.xyz-u;return 1.-dot(n,normalize(i))*s.w*s.w/dd(i);}
float iSphere(v33 r,vec4 s){vec3 e=r.a-s.xyz;float b=dot(r.b,e),h=b*b-dd(e)+s.w*s.w,t=-1.;if(h>0.)t=-b-sqrt(h);return t;}
float intersect(vec3 ro,vec3 rd,out vec3 pos,out vec3 n,out float occ,out float matid
){
;mat4 sc=mat4(sc0,sc1,sc2,sc3)
;float tmin=10000.
;n=vec3(0)
;occ=1.
;pos=vec3(0)
;float h=(.01-ro.y)/rd.y//plane
;if(h>0.
){tmin=h
;n=vec3(0,1,0)
;pos=ro+h*rd
;matid=0.
;occ=occSphere(pos,n,sc[0])*occSphere(pos,n,sc[1])*occSphere(pos,n,sc[2])*occSphere(pos,n,sc[3])
;}
;for(int i=0;i<4;i++){
;float h=iSphere(v33(ro,rd),sc[i])
;bool b=abs(h-.5*tmin)<tmin*.5//==h>0.&&h<tmin
;if(b){tmin=h;pos=ro+tmin*rd;n=normalize(ro+h*rd-sc[i].xyz);matid=1.;occ=u5(n.y);}}
;return tmin;}
void calcCamera(out vec3 ro,out vec3 ta){float an=.3*sin(.04*iTime);ro=vec3(5.5*cos(an),1.,5.5*sin(an));ta=vec3(0,1,0);}
vec3 doLighting(vec3 pos,vec3 rd,vec3 n,float occ
){ ;v33 rrr=v33(pos,rd)//seems to be a shared light source position
;float sh=miv(vec4(sssp(rrr,sc0),sssp(rrr,sc1),sssp(rrr,sc2),sssp(rrr,sc3)))
,dif=sat(dot(n,vec3(.57703)));float bac=sat(dot(n,vec3(-.707,.0,-.707)))
;vec3 lin=dif*sh*vec3(1.5,1.4,1.3)
;lin+=occ*vec3(.15,.2,.3);lin+=bac*vec3(.1);return lin;}
v33 calcRayForPixel(vec2 pix,vec2 res
){vec2 p=(-res.xy+2.0*pix)/res.y
;vec3 ro,ta
;calcCamera(ro,ta)
;vec3 w=normalize(ta-ro)
;vec3 u=normalize(cross(w,vec3(0,1,0)))
;vec3 rd=normalize(p.x*u+p.y*normalize(cross(u,w))+1.5*w)
;return v33(ro,rd);}
void mainImage(out vec4 fragColor,vec2 fragCoord
){vec2 res=vec2(iResolution.x/3.0,iResolution.y)
;int id=int(floor(fragCoord.x/res.x))
;vec2 px=vec2(fragCoord.x-float(id)*res.x,fragCoord.y)
;v33 r0=calcRayForPixel(px+vec2(0,0),res)
;vec3 pos,nor
;float occ,mid;float t=intersect(r0.a,r0.b,pos,nor,occ,mid)
;vec3 col=vec3(.9)
;if(t<100.
//todo,measure angle between normal and rayDirection,and only do #if 1 for anggles>45deg;
//todo,there is a precision fix for near-orthogonal normals to camera that may be good here.
#if 1
){vec3 uvw=pos*scale//analytic ray-differential is in object-space
;v33 rx=calcRayForPixel(px+vec2(1,0),res);
;v33 ry=calcRayForPixel(px+vec2(0,1),res);
;rayTransp(rx,ry)//swap rx.b with ry.a and the lines below become more symmetric: yes,this swaps the origin of one ray with the direction of another.
;v33 w=mul(ry,dt(sub(rx,pos),nor)/dt(ry,nor))
;w=subc(rx,w)
;w=mul(sub(w,pos),scale)
#else
){vec3 uvw=pos*scale;v33 w=v33(dFdx(uvw),dFdy(uvw))//semi-analogously use dFdx()dFdy()in screenspace has bad borders
#endif
;vec3 m=vec3(0)
;w.a=maab2(w)
;if(id==0)m=vec3(1)*checker(uvw)
;else if(id==1)m=vec3(1)*checkerF2(uvw,w.a)
;else if(id==2)m=vec3(1)*checkerF3(uvw,w.a)
;col=m*doLighting(pos,vec3(.57703),nor,occ)
//;col=mix(col,vec3(.9),1.-exp(-.0001*t*t))// fog
;}
;col=pow(col,vec3(.4545))//gamma
;col*=smoothstep(2.,3.,abs(px.x))//frame border lines
;fragColor=vec4(col,1);}
| mit | [
3872,
3952,
3992,
3992,
4018
] | [
[
3872,
3952,
3992,
3992,
4018
],
[
4018,
4067,
4089,
4089,
4114
],
[
4114,
4262,
4285,
4285,
4314
],
[
4314,
4334,
4357,
4357,
4386
],
[
4386,
4403,
4426,
4426,
4455
],
[
4455,
4482,
4503,
4503,
4543
],
[
4543,
4570,
4592,
4592,
4615
],
[
4616,
4616,
4638,
4638,
4667
],
[
4668,
4668,
4689,
4689,
4718
],
[
4718,
4730,
4752,
4752,
4781
],
[
4782,
4782,
4805,
4805,
4830
],
[
4833,
4833,
4852,
4852,
4875
],
[
5165,
5165,
5183,
5183,
5205
],
[
5206,
5206,
5224,
5224,
5244
],
[
5245,
5245,
5263,
5263,
5283
],
[
5284,
5284,
5302,
5302,
5323
],
[
5324,
5324,
5342,
5342,
5375
],
[
5376,
5376,
5396,
5396,
5424
],
[
5691,
5837,
5868,
5868,
6013
],
[
6013,
6130,
6161,
6161,
6317
],
[
6365,
6400,
6425,
6425,
6530
],
[
6531,
6550,
6588,
6588,
6648
],
[
6650,
6650,
6678,
6678,
6771
],
[
6773,
6773,
6861,
6861,
7360
],
[
7362,
7362,
7403,
7403,
7482
],
[
7484,
7484,
7536,
7536,
7847
],
[
7849,
7849,
7889,
7889,
8100
]
] | //and this ray-transpose function is the strangest of em all to be useful here:
| void rayTransp(inout v33 a,inout v33 b){ | vec3 s=a.b;a.b=b.a;b.a=s;} | //and this ray-transpose function is the strangest of em all to be useful here:
void rayTransp(inout v33 a,inout v33 b){ | 1 | 1 |
lldyzM | ollj | 2018-07-20T10:46:29 | //self https://www.shadertoy.com/view/lldyzM
//analytical filter kernel,triangular
//https://www.shadertoy.com/view/llffWs
// Similar to https://www.shadertoy.com/view/XlXBWs,but with a triangular filter kernel,
// which produces less flickering animations that a box filter. Luckily,it's still easily
// http://iquilezles.org/www/articles/morecheckerfiltering/morecheckerfiltering.htm
// checker,2D,box filter: https://www.shadertoy.com/view/XlcSz2
// checker,3D,box filter: https://www.shadertoy.com/view/XlXBWs
// checker,3D,tri filter: https://www.shadertoy.com/view/llffWs
// grid,2D,box filter: https://www.shadertoy.com/view/XtBfzz
// The MIT License
//https://www.shadertoy.com/view/llffWs
// Copyright © 2017 Inigo Quilez
// Permission is hereby granted,free of charge,to any person obtaining a copy of this software and associated documentation files(the "Software"),to dealthe Software without restriction,including without limitation the rights to use,copy,modify,merge,publish,distribute,sublicense,and/or sell copies of the Software,and to permit persons to whom the Software is furnished to do so,subject to the following conditions: The above copyright notice and this permission notice shall be includedall copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER LIABILITY,WHETHERAN ACTION OF CONTRACT,TORT OR OTHERWISE,ARISING FROM,OUT OF ORCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGSTHE SOFTWARE.
/* ---snippety blog summary esplanation
//fwidth(a,b)=abs(dfdx(p))+abs(dfdy(p))
#define maab(a,b)max(abs(a),abs(b))
the m-parameter is a value,returned from maab(),which may be calculated for multiple textures to be mixed,so it is moved out of the function.
//llffWs is tri-filtering AND box filtering,but it does not need the double integral,but other shaders calculate a double integral.
//there is this double-integral blog post this snioppet is all about:
the basic idea is to smoothen a discontinuity with an antiderivative
"cubic filters" are most common in CG,but this isr "tiangle-filter"ed weights,worse than cubic,better than the box filtering above
f(x)is the square-wave base signal that begs to be filtered.
box-filter formula is integralfromToOf(-w/2,w/2,f(x)dx)
tri-filter formula is integralfromToOf(-w,0,f(x)dx*(w+x)/w)+integralfromtoOf(0,w,f(x)dx*(w-x)/w)
these integrals are integralfromToOf(uv-w/2,uv+w/2,...),but shifting the center simplifies this function.
these integrals are done by [integration by parts],which has lots of symmetries that cancel each other out to:
tri-filter formula is(p(-w*.5)-2.*p(0.)+p(w*.5))/w/w
where p(x)is the antidetivative to f(x)(the striangle wave to the square wave.)
where s(x)is the double-integral of f(x)== the antidefivative of p(x)=an infinite smoothstep function.
//still no double-integrals needed!
vec3 sqrAndIntegrals(float x
){x*=.5;float h=fract(x)-.5,s=-sign(h),t=abs(h)*2.-1.)
;return(s,t,x+h*t);}//return vec3(square,tri(integral),smoothsteps(doubleIntegral))
vec2 fTri(vec2 x){vec2 h=fract(x*.5)-.5);return x*.5-h*(abs(h)*2.-1.);}//;return x*.5+h*(1.-2.*abs(h))
float TriFilteredCheckers(vec2 uv,vec2 w//w=maab(dpdx,dpdy)filter kernel
){w+.001
;vec2 i=(fTri(uw+w)-2.*fTri(uw)+ftri(uv-w))/(w*w)//analytic integral,3TapFilter function
;return .5-.5*i.x-i.y//xor-pattern
;}
//still no double-integrals needed!
//anyways,that would be curvature,what use is curvature for surface filtering?
*/
#define scale 5.
// spheres
const vec4 sc0=vec4(2,.5,.8,.5);
const vec4 sc1=vec4(-6,1,-4.,3);
const vec4 sc2=vec4(-16,1,7,4);
const vec4 sc3=vec4(-25,8,0,9);
struct v33{vec3 a;vec3 b;};
//and this ray-transpose function is the strangest of em all to be useful here:
void rayTransp(inout v33 a,inout v33 b){vec3 s=a.b;a.b=b.a;b.a=s;}//swap direction(.b)of [a] with origin(.a)of [b]
v33 sub(v33 a,vec3 b){return v33(a.a-b,a.b-b);}//substract b from all ray components
//component wise ray substraction(this one is a bit odd,differential wise,is basically scaling a rays points)
v33 subc(v33 a,v33 b){return v33(a.a-b.a,a.b-b.b);}//it makes sense in
v33 subc(vec2 a,v33 b){return v33(a.x-b.a,a.x-b.b);}//the context of
v33 subc(v33 a,vec2 b){return v33(a.a-b.x,a.b-b.y);}//v33-differentials for AA
vec2 dt(v33 a,v33 b){return vec2(dot(a.a,b.a),dot(a.b,b.b));}//dual dotprodiuct on v33s
vec2 dt(v33 a,vec3 b){return dt(a,v33(b,b));}
v33 div(v33 a,vec2 b){return v33(a.a/b.x,a.b/b.y);}
v33 mul(v33 a,v33 b){return v33(a.a*b.a,a.b*b.b);}//dual mult
v33 mul(v33 a,vec2 b){return v33(a.a*b.x,a.b*b.y);}
v33 mul(v33 a,float b){return v33(a.a*b,a.b*b);}
float sat(float a){return clamp(a,0.,1.);}
#define dd(a)dot(a,a)
//half-identity-scaling,labeled uN because it scales uv space,usually within a modulo context.
#define u2(a)((a)*2.-1.)
#define u5(a)((a)*.5+.5)
//u3(a)=1.-u2(a)!
//u6(a)=1.-u2(a)!
#define u3(a)(1.-(a)*2.)
#define u6(a)(.5-(a)*.5)
#define maab(a,b)max(abs(a),abs(b))
vec3 maab2(v33 a){return maab(a.a,a.b);}
float suv(vec3 a){return a.x+a.y+a.z;}
float prv(vec3 a){return a.x*a.y*a.z;}
float miv(vec2 a){return min(a.x,a.y);}
float miv(vec4 a){return min(miv(a.xy),miv(a.zw));}
float ss01(float a){return smoothstep(0.,1.,a);}
// ---unfiltered checkerboard ---
#define checker(a)mod(suv(floor(a)),2.)
//analytically triangle-filtered checkerboard: https://www.shadertoy.com/view/MtffWs
#define Fa(a,b)u2(abs(b-.5))
#define Fb(a,b)((a)*.5-((b)-.5)*Fa(a,b))
#define tri(a,b)b(a,fract((a)*.5))
//noe to self,maybe replace iMouse.y by abs(angleBetween(rayDirection,Normal))/quaterRotation
//tri(a,Fa)2xTap for box-filtering,used a lot in CG
float checkerF2(vec3 p,vec3 w){w+=iMouse.y/iResolution.y//filter kernel increase this value over inverse squared distance?
;return u6(prv((tri(p-.5*w,Fa)-tri(p+.5*w,Fa))/w));}//analytical integral(box filter),xor pattern
//tri(a,Fb)3xTap for tri-filtering,is slightly better than checkerF2()
float checkerF3(vec3 p,vec3 w){w+=iMouse.y/iResolution.y//filter kernel increase this value over inverse squared distance?
;return u6(prv((tri(p+w,Fb)-2.*tri(p,Fb)+tri(p-w,Fb))/(w*w)));}// analytical integral(tri filter),xor pattern
//sphere softShadow of(ray,sphere)
float sssp(v33 r,vec4 s){vec3 oc=s.xyz-r.a;float b=dot(oc,r.b),z=1.;if(b>0.){float h=dd(oc)-b*b-s.w*s.w;z=ss01(2.*h/b);}return z;}
//sphere occlusion
float occSphere(vec3 u,vec3 n,vec4 s){vec3 i=s.xyz-u;return 1.-dot(n,normalize(i))*s.w*s.w/dd(i);}
float iSphere(v33 r,vec4 s){vec3 e=r.a-s.xyz;float b=dot(r.b,e),h=b*b-dd(e)+s.w*s.w,t=-1.;if(h>0.)t=-b-sqrt(h);return t;}
float intersect(vec3 ro,vec3 rd,out vec3 pos,out vec3 n,out float occ,out float matid
){
;mat4 sc=mat4(sc0,sc1,sc2,sc3)
;float tmin=10000.
;n=vec3(0)
;occ=1.
;pos=vec3(0)
;float h=(.01-ro.y)/rd.y//plane
;if(h>0.
){tmin=h
;n=vec3(0,1,0)
;pos=ro+h*rd
;matid=0.
;occ=occSphere(pos,n,sc[0])*occSphere(pos,n,sc[1])*occSphere(pos,n,sc[2])*occSphere(pos,n,sc[3])
;}
;for(int i=0;i<4;i++){
;float h=iSphere(v33(ro,rd),sc[i])
;bool b=abs(h-.5*tmin)<tmin*.5//==h>0.&&h<tmin
;if(b){tmin=h;pos=ro+tmin*rd;n=normalize(ro+h*rd-sc[i].xyz);matid=1.;occ=u5(n.y);}}
;return tmin;}
void calcCamera(out vec3 ro,out vec3 ta){float an=.3*sin(.04*iTime);ro=vec3(5.5*cos(an),1.,5.5*sin(an));ta=vec3(0,1,0);}
vec3 doLighting(vec3 pos,vec3 rd,vec3 n,float occ
){ ;v33 rrr=v33(pos,rd)//seems to be a shared light source position
;float sh=miv(vec4(sssp(rrr,sc0),sssp(rrr,sc1),sssp(rrr,sc2),sssp(rrr,sc3)))
,dif=sat(dot(n,vec3(.57703)));float bac=sat(dot(n,vec3(-.707,.0,-.707)))
;vec3 lin=dif*sh*vec3(1.5,1.4,1.3)
;lin+=occ*vec3(.15,.2,.3);lin+=bac*vec3(.1);return lin;}
v33 calcRayForPixel(vec2 pix,vec2 res
){vec2 p=(-res.xy+2.0*pix)/res.y
;vec3 ro,ta
;calcCamera(ro,ta)
;vec3 w=normalize(ta-ro)
;vec3 u=normalize(cross(w,vec3(0,1,0)))
;vec3 rd=normalize(p.x*u+p.y*normalize(cross(u,w))+1.5*w)
;return v33(ro,rd);}
void mainImage(out vec4 fragColor,vec2 fragCoord
){vec2 res=vec2(iResolution.x/3.0,iResolution.y)
;int id=int(floor(fragCoord.x/res.x))
;vec2 px=vec2(fragCoord.x-float(id)*res.x,fragCoord.y)
;v33 r0=calcRayForPixel(px+vec2(0,0),res)
;vec3 pos,nor
;float occ,mid;float t=intersect(r0.a,r0.b,pos,nor,occ,mid)
;vec3 col=vec3(.9)
;if(t<100.
//todo,measure angle between normal and rayDirection,and only do #if 1 for anggles>45deg;
//todo,there is a precision fix for near-orthogonal normals to camera that may be good here.
#if 1
){vec3 uvw=pos*scale//analytic ray-differential is in object-space
;v33 rx=calcRayForPixel(px+vec2(1,0),res);
;v33 ry=calcRayForPixel(px+vec2(0,1),res);
;rayTransp(rx,ry)//swap rx.b with ry.a and the lines below become more symmetric: yes,this swaps the origin of one ray with the direction of another.
;v33 w=mul(ry,dt(sub(rx,pos),nor)/dt(ry,nor))
;w=subc(rx,w)
;w=mul(sub(w,pos),scale)
#else
){vec3 uvw=pos*scale;v33 w=v33(dFdx(uvw),dFdy(uvw))//semi-analogously use dFdx()dFdy()in screenspace has bad borders
#endif
;vec3 m=vec3(0)
;w.a=maab2(w)
;if(id==0)m=vec3(1)*checker(uvw)
;else if(id==1)m=vec3(1)*checkerF2(uvw,w.a)
;else if(id==2)m=vec3(1)*checkerF3(uvw,w.a)
;col=m*doLighting(pos,vec3(.57703),nor,occ)
//;col=mix(col,vec3(.9),1.-exp(-.0001*t*t))// fog
;}
;col=pow(col,vec3(.4545))//gamma
;col*=smoothstep(2.,3.,abs(px.x))//frame border lines
;fragColor=vec4(col,1);}
| mit | [
4018,
4067,
4089,
4089,
4114
] | [
[
3872,
3952,
3992,
3992,
4018
],
[
4018,
4067,
4089,
4089,
4114
],
[
4114,
4262,
4285,
4285,
4314
],
[
4314,
4334,
4357,
4357,
4386
],
[
4386,
4403,
4426,
4426,
4455
],
[
4455,
4482,
4503,
4503,
4543
],
[
4543,
4570,
4592,
4592,
4615
],
[
4616,
4616,
4638,
4638,
4667
],
[
4668,
4668,
4689,
4689,
4718
],
[
4718,
4730,
4752,
4752,
4781
],
[
4782,
4782,
4805,
4805,
4830
],
[
4833,
4833,
4852,
4852,
4875
],
[
5165,
5165,
5183,
5183,
5205
],
[
5206,
5206,
5224,
5224,
5244
],
[
5245,
5245,
5263,
5263,
5283
],
[
5284,
5284,
5302,
5302,
5323
],
[
5324,
5324,
5342,
5342,
5375
],
[
5376,
5376,
5396,
5396,
5424
],
[
5691,
5837,
5868,
5868,
6013
],
[
6013,
6130,
6161,
6161,
6317
],
[
6365,
6400,
6425,
6425,
6530
],
[
6531,
6550,
6588,
6588,
6648
],
[
6650,
6650,
6678,
6678,
6771
],
[
6773,
6773,
6861,
6861,
7360
],
[
7362,
7362,
7403,
7403,
7482
],
[
7484,
7484,
7536,
7536,
7847
],
[
7849,
7849,
7889,
7889,
8100
]
] | //swap direction(.b)of [a] with origin(.a)of [b]
| v33 sub(v33 a,vec3 b){ | return v33(a.a-b,a.b-b);} | //swap direction(.b)of [a] with origin(.a)of [b]
v33 sub(v33 a,vec3 b){ | 1 | 1 |
lldyzM | ollj | 2018-07-20T10:46:29 | //self https://www.shadertoy.com/view/lldyzM
//analytical filter kernel,triangular
//https://www.shadertoy.com/view/llffWs
// Similar to https://www.shadertoy.com/view/XlXBWs,but with a triangular filter kernel,
// which produces less flickering animations that a box filter. Luckily,it's still easily
// http://iquilezles.org/www/articles/morecheckerfiltering/morecheckerfiltering.htm
// checker,2D,box filter: https://www.shadertoy.com/view/XlcSz2
// checker,3D,box filter: https://www.shadertoy.com/view/XlXBWs
// checker,3D,tri filter: https://www.shadertoy.com/view/llffWs
// grid,2D,box filter: https://www.shadertoy.com/view/XtBfzz
// The MIT License
//https://www.shadertoy.com/view/llffWs
// Copyright © 2017 Inigo Quilez
// Permission is hereby granted,free of charge,to any person obtaining a copy of this software and associated documentation files(the "Software"),to dealthe Software without restriction,including without limitation the rights to use,copy,modify,merge,publish,distribute,sublicense,and/or sell copies of the Software,and to permit persons to whom the Software is furnished to do so,subject to the following conditions: The above copyright notice and this permission notice shall be includedall copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER LIABILITY,WHETHERAN ACTION OF CONTRACT,TORT OR OTHERWISE,ARISING FROM,OUT OF ORCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGSTHE SOFTWARE.
/* ---snippety blog summary esplanation
//fwidth(a,b)=abs(dfdx(p))+abs(dfdy(p))
#define maab(a,b)max(abs(a),abs(b))
the m-parameter is a value,returned from maab(),which may be calculated for multiple textures to be mixed,so it is moved out of the function.
//llffWs is tri-filtering AND box filtering,but it does not need the double integral,but other shaders calculate a double integral.
//there is this double-integral blog post this snioppet is all about:
the basic idea is to smoothen a discontinuity with an antiderivative
"cubic filters" are most common in CG,but this isr "tiangle-filter"ed weights,worse than cubic,better than the box filtering above
f(x)is the square-wave base signal that begs to be filtered.
box-filter formula is integralfromToOf(-w/2,w/2,f(x)dx)
tri-filter formula is integralfromToOf(-w,0,f(x)dx*(w+x)/w)+integralfromtoOf(0,w,f(x)dx*(w-x)/w)
these integrals are integralfromToOf(uv-w/2,uv+w/2,...),but shifting the center simplifies this function.
these integrals are done by [integration by parts],which has lots of symmetries that cancel each other out to:
tri-filter formula is(p(-w*.5)-2.*p(0.)+p(w*.5))/w/w
where p(x)is the antidetivative to f(x)(the striangle wave to the square wave.)
where s(x)is the double-integral of f(x)== the antidefivative of p(x)=an infinite smoothstep function.
//still no double-integrals needed!
vec3 sqrAndIntegrals(float x
){x*=.5;float h=fract(x)-.5,s=-sign(h),t=abs(h)*2.-1.)
;return(s,t,x+h*t);}//return vec3(square,tri(integral),smoothsteps(doubleIntegral))
vec2 fTri(vec2 x){vec2 h=fract(x*.5)-.5);return x*.5-h*(abs(h)*2.-1.);}//;return x*.5+h*(1.-2.*abs(h))
float TriFilteredCheckers(vec2 uv,vec2 w//w=maab(dpdx,dpdy)filter kernel
){w+.001
;vec2 i=(fTri(uw+w)-2.*fTri(uw)+ftri(uv-w))/(w*w)//analytic integral,3TapFilter function
;return .5-.5*i.x-i.y//xor-pattern
;}
//still no double-integrals needed!
//anyways,that would be curvature,what use is curvature for surface filtering?
*/
#define scale 5.
// spheres
const vec4 sc0=vec4(2,.5,.8,.5);
const vec4 sc1=vec4(-6,1,-4.,3);
const vec4 sc2=vec4(-16,1,7,4);
const vec4 sc3=vec4(-25,8,0,9);
struct v33{vec3 a;vec3 b;};
//and this ray-transpose function is the strangest of em all to be useful here:
void rayTransp(inout v33 a,inout v33 b){vec3 s=a.b;a.b=b.a;b.a=s;}//swap direction(.b)of [a] with origin(.a)of [b]
v33 sub(v33 a,vec3 b){return v33(a.a-b,a.b-b);}//substract b from all ray components
//component wise ray substraction(this one is a bit odd,differential wise,is basically scaling a rays points)
v33 subc(v33 a,v33 b){return v33(a.a-b.a,a.b-b.b);}//it makes sense in
v33 subc(vec2 a,v33 b){return v33(a.x-b.a,a.x-b.b);}//the context of
v33 subc(v33 a,vec2 b){return v33(a.a-b.x,a.b-b.y);}//v33-differentials for AA
vec2 dt(v33 a,v33 b){return vec2(dot(a.a,b.a),dot(a.b,b.b));}//dual dotprodiuct on v33s
vec2 dt(v33 a,vec3 b){return dt(a,v33(b,b));}
v33 div(v33 a,vec2 b){return v33(a.a/b.x,a.b/b.y);}
v33 mul(v33 a,v33 b){return v33(a.a*b.a,a.b*b.b);}//dual mult
v33 mul(v33 a,vec2 b){return v33(a.a*b.x,a.b*b.y);}
v33 mul(v33 a,float b){return v33(a.a*b,a.b*b);}
float sat(float a){return clamp(a,0.,1.);}
#define dd(a)dot(a,a)
//half-identity-scaling,labeled uN because it scales uv space,usually within a modulo context.
#define u2(a)((a)*2.-1.)
#define u5(a)((a)*.5+.5)
//u3(a)=1.-u2(a)!
//u6(a)=1.-u2(a)!
#define u3(a)(1.-(a)*2.)
#define u6(a)(.5-(a)*.5)
#define maab(a,b)max(abs(a),abs(b))
vec3 maab2(v33 a){return maab(a.a,a.b);}
float suv(vec3 a){return a.x+a.y+a.z;}
float prv(vec3 a){return a.x*a.y*a.z;}
float miv(vec2 a){return min(a.x,a.y);}
float miv(vec4 a){return min(miv(a.xy),miv(a.zw));}
float ss01(float a){return smoothstep(0.,1.,a);}
// ---unfiltered checkerboard ---
#define checker(a)mod(suv(floor(a)),2.)
//analytically triangle-filtered checkerboard: https://www.shadertoy.com/view/MtffWs
#define Fa(a,b)u2(abs(b-.5))
#define Fb(a,b)((a)*.5-((b)-.5)*Fa(a,b))
#define tri(a,b)b(a,fract((a)*.5))
//noe to self,maybe replace iMouse.y by abs(angleBetween(rayDirection,Normal))/quaterRotation
//tri(a,Fa)2xTap for box-filtering,used a lot in CG
float checkerF2(vec3 p,vec3 w){w+=iMouse.y/iResolution.y//filter kernel increase this value over inverse squared distance?
;return u6(prv((tri(p-.5*w,Fa)-tri(p+.5*w,Fa))/w));}//analytical integral(box filter),xor pattern
//tri(a,Fb)3xTap for tri-filtering,is slightly better than checkerF2()
float checkerF3(vec3 p,vec3 w){w+=iMouse.y/iResolution.y//filter kernel increase this value over inverse squared distance?
;return u6(prv((tri(p+w,Fb)-2.*tri(p,Fb)+tri(p-w,Fb))/(w*w)));}// analytical integral(tri filter),xor pattern
//sphere softShadow of(ray,sphere)
float sssp(v33 r,vec4 s){vec3 oc=s.xyz-r.a;float b=dot(oc,r.b),z=1.;if(b>0.){float h=dd(oc)-b*b-s.w*s.w;z=ss01(2.*h/b);}return z;}
//sphere occlusion
float occSphere(vec3 u,vec3 n,vec4 s){vec3 i=s.xyz-u;return 1.-dot(n,normalize(i))*s.w*s.w/dd(i);}
float iSphere(v33 r,vec4 s){vec3 e=r.a-s.xyz;float b=dot(r.b,e),h=b*b-dd(e)+s.w*s.w,t=-1.;if(h>0.)t=-b-sqrt(h);return t;}
float intersect(vec3 ro,vec3 rd,out vec3 pos,out vec3 n,out float occ,out float matid
){
;mat4 sc=mat4(sc0,sc1,sc2,sc3)
;float tmin=10000.
;n=vec3(0)
;occ=1.
;pos=vec3(0)
;float h=(.01-ro.y)/rd.y//plane
;if(h>0.
){tmin=h
;n=vec3(0,1,0)
;pos=ro+h*rd
;matid=0.
;occ=occSphere(pos,n,sc[0])*occSphere(pos,n,sc[1])*occSphere(pos,n,sc[2])*occSphere(pos,n,sc[3])
;}
;for(int i=0;i<4;i++){
;float h=iSphere(v33(ro,rd),sc[i])
;bool b=abs(h-.5*tmin)<tmin*.5//==h>0.&&h<tmin
;if(b){tmin=h;pos=ro+tmin*rd;n=normalize(ro+h*rd-sc[i].xyz);matid=1.;occ=u5(n.y);}}
;return tmin;}
void calcCamera(out vec3 ro,out vec3 ta){float an=.3*sin(.04*iTime);ro=vec3(5.5*cos(an),1.,5.5*sin(an));ta=vec3(0,1,0);}
vec3 doLighting(vec3 pos,vec3 rd,vec3 n,float occ
){ ;v33 rrr=v33(pos,rd)//seems to be a shared light source position
;float sh=miv(vec4(sssp(rrr,sc0),sssp(rrr,sc1),sssp(rrr,sc2),sssp(rrr,sc3)))
,dif=sat(dot(n,vec3(.57703)));float bac=sat(dot(n,vec3(-.707,.0,-.707)))
;vec3 lin=dif*sh*vec3(1.5,1.4,1.3)
;lin+=occ*vec3(.15,.2,.3);lin+=bac*vec3(.1);return lin;}
v33 calcRayForPixel(vec2 pix,vec2 res
){vec2 p=(-res.xy+2.0*pix)/res.y
;vec3 ro,ta
;calcCamera(ro,ta)
;vec3 w=normalize(ta-ro)
;vec3 u=normalize(cross(w,vec3(0,1,0)))
;vec3 rd=normalize(p.x*u+p.y*normalize(cross(u,w))+1.5*w)
;return v33(ro,rd);}
void mainImage(out vec4 fragColor,vec2 fragCoord
){vec2 res=vec2(iResolution.x/3.0,iResolution.y)
;int id=int(floor(fragCoord.x/res.x))
;vec2 px=vec2(fragCoord.x-float(id)*res.x,fragCoord.y)
;v33 r0=calcRayForPixel(px+vec2(0,0),res)
;vec3 pos,nor
;float occ,mid;float t=intersect(r0.a,r0.b,pos,nor,occ,mid)
;vec3 col=vec3(.9)
;if(t<100.
//todo,measure angle between normal and rayDirection,and only do #if 1 for anggles>45deg;
//todo,there is a precision fix for near-orthogonal normals to camera that may be good here.
#if 1
){vec3 uvw=pos*scale//analytic ray-differential is in object-space
;v33 rx=calcRayForPixel(px+vec2(1,0),res);
;v33 ry=calcRayForPixel(px+vec2(0,1),res);
;rayTransp(rx,ry)//swap rx.b with ry.a and the lines below become more symmetric: yes,this swaps the origin of one ray with the direction of another.
;v33 w=mul(ry,dt(sub(rx,pos),nor)/dt(ry,nor))
;w=subc(rx,w)
;w=mul(sub(w,pos),scale)
#else
){vec3 uvw=pos*scale;v33 w=v33(dFdx(uvw),dFdy(uvw))//semi-analogously use dFdx()dFdy()in screenspace has bad borders
#endif
;vec3 m=vec3(0)
;w.a=maab2(w)
;if(id==0)m=vec3(1)*checker(uvw)
;else if(id==1)m=vec3(1)*checkerF2(uvw,w.a)
;else if(id==2)m=vec3(1)*checkerF3(uvw,w.a)
;col=m*doLighting(pos,vec3(.57703),nor,occ)
//;col=mix(col,vec3(.9),1.-exp(-.0001*t*t))// fog
;}
;col=pow(col,vec3(.4545))//gamma
;col*=smoothstep(2.,3.,abs(px.x))//frame border lines
;fragColor=vec4(col,1);}
| mit | [
4114,
4262,
4285,
4285,
4314
] | [
[
3872,
3952,
3992,
3992,
4018
],
[
4018,
4067,
4089,
4089,
4114
],
[
4114,
4262,
4285,
4285,
4314
],
[
4314,
4334,
4357,
4357,
4386
],
[
4386,
4403,
4426,
4426,
4455
],
[
4455,
4482,
4503,
4503,
4543
],
[
4543,
4570,
4592,
4592,
4615
],
[
4616,
4616,
4638,
4638,
4667
],
[
4668,
4668,
4689,
4689,
4718
],
[
4718,
4730,
4752,
4752,
4781
],
[
4782,
4782,
4805,
4805,
4830
],
[
4833,
4833,
4852,
4852,
4875
],
[
5165,
5165,
5183,
5183,
5205
],
[
5206,
5206,
5224,
5224,
5244
],
[
5245,
5245,
5263,
5263,
5283
],
[
5284,
5284,
5302,
5302,
5323
],
[
5324,
5324,
5342,
5342,
5375
],
[
5376,
5376,
5396,
5396,
5424
],
[
5691,
5837,
5868,
5868,
6013
],
[
6013,
6130,
6161,
6161,
6317
],
[
6365,
6400,
6425,
6425,
6530
],
[
6531,
6550,
6588,
6588,
6648
],
[
6650,
6650,
6678,
6678,
6771
],
[
6773,
6773,
6861,
6861,
7360
],
[
7362,
7362,
7403,
7403,
7482
],
[
7484,
7484,
7536,
7536,
7847
],
[
7849,
7849,
7889,
7889,
8100
]
] | //substract b from all ray components
//component wise ray substraction(this one is a bit odd,differential wise,is basically scaling a rays points)
| v33 subc(v33 a,v33 b){ | return v33(a.a-b.a,a.b-b.b);} | //substract b from all ray components
//component wise ray substraction(this one is a bit odd,differential wise,is basically scaling a rays points)
v33 subc(v33 a,v33 b){ | 1 | 1 |
lldyzM | ollj | 2018-07-20T10:46:29 | //self https://www.shadertoy.com/view/lldyzM
//analytical filter kernel,triangular
//https://www.shadertoy.com/view/llffWs
// Similar to https://www.shadertoy.com/view/XlXBWs,but with a triangular filter kernel,
// which produces less flickering animations that a box filter. Luckily,it's still easily
// http://iquilezles.org/www/articles/morecheckerfiltering/morecheckerfiltering.htm
// checker,2D,box filter: https://www.shadertoy.com/view/XlcSz2
// checker,3D,box filter: https://www.shadertoy.com/view/XlXBWs
// checker,3D,tri filter: https://www.shadertoy.com/view/llffWs
// grid,2D,box filter: https://www.shadertoy.com/view/XtBfzz
// The MIT License
//https://www.shadertoy.com/view/llffWs
// Copyright © 2017 Inigo Quilez
// Permission is hereby granted,free of charge,to any person obtaining a copy of this software and associated documentation files(the "Software"),to dealthe Software without restriction,including without limitation the rights to use,copy,modify,merge,publish,distribute,sublicense,and/or sell copies of the Software,and to permit persons to whom the Software is furnished to do so,subject to the following conditions: The above copyright notice and this permission notice shall be includedall copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS",WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED,INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,DAMAGES OR OTHER LIABILITY,WHETHERAN ACTION OF CONTRACT,TORT OR OTHERWISE,ARISING FROM,OUT OF ORCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGSTHE SOFTWARE.
/* ---snippety blog summary esplanation
//fwidth(a,b)=abs(dfdx(p))+abs(dfdy(p))
#define maab(a,b)max(abs(a),abs(b))
the m-parameter is a value,returned from maab(),which may be calculated for multiple textures to be mixed,so it is moved out of the function.
//llffWs is tri-filtering AND box filtering,but it does not need the double integral,but other shaders calculate a double integral.
//there is this double-integral blog post this snioppet is all about:
the basic idea is to smoothen a discontinuity with an antiderivative
"cubic filters" are most common in CG,but this isr "tiangle-filter"ed weights,worse than cubic,better than the box filtering above
f(x)is the square-wave base signal that begs to be filtered.
box-filter formula is integralfromToOf(-w/2,w/2,f(x)dx)
tri-filter formula is integralfromToOf(-w,0,f(x)dx*(w+x)/w)+integralfromtoOf(0,w,f(x)dx*(w-x)/w)
these integrals are integralfromToOf(uv-w/2,uv+w/2,...),but shifting the center simplifies this function.
these integrals are done by [integration by parts],which has lots of symmetries that cancel each other out to:
tri-filter formula is(p(-w*.5)-2.*p(0.)+p(w*.5))/w/w
where p(x)is the antidetivative to f(x)(the striangle wave to the square wave.)
where s(x)is the double-integral of f(x)== the antidefivative of p(x)=an infinite smoothstep function.
//still no double-integrals needed!
vec3 sqrAndIntegrals(float x
){x*=.5;float h=fract(x)-.5,s=-sign(h),t=abs(h)*2.-1.)
;return(s,t,x+h*t);}//return vec3(square,tri(integral),smoothsteps(doubleIntegral))
vec2 fTri(vec2 x){vec2 h=fract(x*.5)-.5);return x*.5-h*(abs(h)*2.-1.);}//;return x*.5+h*(1.-2.*abs(h))
float TriFilteredCheckers(vec2 uv,vec2 w//w=maab(dpdx,dpdy)filter kernel
){w+.001
;vec2 i=(fTri(uw+w)-2.*fTri(uw)+ftri(uv-w))/(w*w)//analytic integral,3TapFilter function
;return .5-.5*i.x-i.y//xor-pattern
;}
//still no double-integrals needed!
//anyways,that would be curvature,what use is curvature for surface filtering?
*/
#define scale 5.
// spheres
const vec4 sc0=vec4(2,.5,.8,.5);
const vec4 sc1=vec4(-6,1,-4.,3);
const vec4 sc2=vec4(-16,1,7,4);
const vec4 sc3=vec4(-25,8,0,9);
struct v33{vec3 a;vec3 b;};
//and this ray-transpose function is the strangest of em all to be useful here:
void rayTransp(inout v33 a,inout v33 b){vec3 s=a.b;a.b=b.a;b.a=s;}//swap direction(.b)of [a] with origin(.a)of [b]
v33 sub(v33 a,vec3 b){return v33(a.a-b,a.b-b);}//substract b from all ray components
//component wise ray substraction(this one is a bit odd,differential wise,is basically scaling a rays points)
v33 subc(v33 a,v33 b){return v33(a.a-b.a,a.b-b.b);}//it makes sense in
v33 subc(vec2 a,v33 b){return v33(a.x-b.a,a.x-b.b);}//the context of
v33 subc(v33 a,vec2 b){return v33(a.a-b.x,a.b-b.y);}//v33-differentials for AA
vec2 dt(v33 a,v33 b){return vec2(dot(a.a,b.a),dot(a.b,b.b));}//dual dotprodiuct on v33s
vec2 dt(v33 a,vec3 b){return dt(a,v33(b,b));}
v33 div(v33 a,vec2 b){return v33(a.a/b.x,a.b/b.y);}
v33 mul(v33 a,v33 b){return v33(a.a*b.a,a.b*b.b);}//dual mult
v33 mul(v33 a,vec2 b){return v33(a.a*b.x,a.b*b.y);}
v33 mul(v33 a,float b){return v33(a.a*b,a.b*b);}
float sat(float a){return clamp(a,0.,1.);}
#define dd(a)dot(a,a)
//half-identity-scaling,labeled uN because it scales uv space,usually within a modulo context.
#define u2(a)((a)*2.-1.)
#define u5(a)((a)*.5+.5)
//u3(a)=1.-u2(a)!
//u6(a)=1.-u2(a)!
#define u3(a)(1.-(a)*2.)
#define u6(a)(.5-(a)*.5)
#define maab(a,b)max(abs(a),abs(b))
vec3 maab2(v33 a){return maab(a.a,a.b);}
float suv(vec3 a){return a.x+a.y+a.z;}
float prv(vec3 a){return a.x*a.y*a.z;}
float miv(vec2 a){return min(a.x,a.y);}
float miv(vec4 a){return min(miv(a.xy),miv(a.zw));}
float ss01(float a){return smoothstep(0.,1.,a);}
// ---unfiltered checkerboard ---
#define checker(a)mod(suv(floor(a)),2.)
//analytically triangle-filtered checkerboard: https://www.shadertoy.com/view/MtffWs
#define Fa(a,b)u2(abs(b-.5))
#define Fb(a,b)((a)*.5-((b)-.5)*Fa(a,b))
#define tri(a,b)b(a,fract((a)*.5))
//noe to self,maybe replace iMouse.y by abs(angleBetween(rayDirection,Normal))/quaterRotation
//tri(a,Fa)2xTap for box-filtering,used a lot in CG
float checkerF2(vec3 p,vec3 w){w+=iMouse.y/iResolution.y//filter kernel increase this value over inverse squared distance?
;return u6(prv((tri(p-.5*w,Fa)-tri(p+.5*w,Fa))/w));}//analytical integral(box filter),xor pattern
//tri(a,Fb)3xTap for tri-filtering,is slightly better than checkerF2()
float checkerF3(vec3 p,vec3 w){w+=iMouse.y/iResolution.y//filter kernel increase this value over inverse squared distance?
;return u6(prv((tri(p+w,Fb)-2.*tri(p,Fb)+tri(p-w,Fb))/(w*w)));}// analytical integral(tri filter),xor pattern
//sphere softShadow of(ray,sphere)
float sssp(v33 r,vec4 s){vec3 oc=s.xyz-r.a;float b=dot(oc,r.b),z=1.;if(b>0.){float h=dd(oc)-b*b-s.w*s.w;z=ss01(2.*h/b);}return z;}
//sphere occlusion
float occSphere(vec3 u,vec3 n,vec4 s){vec3 i=s.xyz-u;return 1.-dot(n,normalize(i))*s.w*s.w/dd(i);}
float iSphere(v33 r,vec4 s){vec3 e=r.a-s.xyz;float b=dot(r.b,e),h=b*b-dd(e)+s.w*s.w,t=-1.;if(h>0.)t=-b-sqrt(h);return t;}
float intersect(vec3 ro,vec3 rd,out vec3 pos,out vec3 n,out float occ,out float matid
){
;mat4 sc=mat4(sc0,sc1,sc2,sc3)
;float tmin=10000.
;n=vec3(0)
;occ=1.
;pos=vec3(0)
;float h=(.01-ro.y)/rd.y//plane
;if(h>0.
){tmin=h
;n=vec3(0,1,0)
;pos=ro+h*rd
;matid=0.
;occ=occSphere(pos,n,sc[0])*occSphere(pos,n,sc[1])*occSphere(pos,n,sc[2])*occSphere(pos,n,sc[3])
;}
;for(int i=0;i<4;i++){
;float h=iSphere(v33(ro,rd),sc[i])
;bool b=abs(h-.5*tmin)<tmin*.5//==h>0.&&h<tmin
;if(b){tmin=h;pos=ro+tmin*rd;n=normalize(ro+h*rd-sc[i].xyz);matid=1.;occ=u5(n.y);}}
;return tmin;}
void calcCamera(out vec3 ro,out vec3 ta){float an=.3*sin(.04*iTime);ro=vec3(5.5*cos(an),1.,5.5*sin(an));ta=vec3(0,1,0);}
vec3 doLighting(vec3 pos,vec3 rd,vec3 n,float occ
){ ;v33 rrr=v33(pos,rd)//seems to be a shared light source position
;float sh=miv(vec4(sssp(rrr,sc0),sssp(rrr,sc1),sssp(rrr,sc2),sssp(rrr,sc3)))
,dif=sat(dot(n,vec3(.57703)));float bac=sat(dot(n,vec3(-.707,.0,-.707)))
;vec3 lin=dif*sh*vec3(1.5,1.4,1.3)
;lin+=occ*vec3(.15,.2,.3);lin+=bac*vec3(.1);return lin;}
v33 calcRayForPixel(vec2 pix,vec2 res
){vec2 p=(-res.xy+2.0*pix)/res.y
;vec3 ro,ta
;calcCamera(ro,ta)
;vec3 w=normalize(ta-ro)
;vec3 u=normalize(cross(w,vec3(0,1,0)))
;vec3 rd=normalize(p.x*u+p.y*normalize(cross(u,w))+1.5*w)
;return v33(ro,rd);}
void mainImage(out vec4 fragColor,vec2 fragCoord
){vec2 res=vec2(iResolution.x/3.0,iResolution.y)
;int id=int(floor(fragCoord.x/res.x))
;vec2 px=vec2(fragCoord.x-float(id)*res.x,fragCoord.y)
;v33 r0=calcRayForPixel(px+vec2(0,0),res)
;vec3 pos,nor
;float occ,mid;float t=intersect(r0.a,r0.b,pos,nor,occ,mid)
;vec3 col=vec3(.9)
;if(t<100.
//todo,measure angle between normal and rayDirection,and only do #if 1 for anggles>45deg;
//todo,there is a precision fix for near-orthogonal normals to camera that may be good here.
#if 1
){vec3 uvw=pos*scale//analytic ray-differential is in object-space
;v33 rx=calcRayForPixel(px+vec2(1,0),res);
;v33 ry=calcRayForPixel(px+vec2(0,1),res);
;rayTransp(rx,ry)//swap rx.b with ry.a and the lines below become more symmetric: yes,this swaps the origin of one ray with the direction of another.
;v33 w=mul(ry,dt(sub(rx,pos),nor)/dt(ry,nor))
;w=subc(rx,w)
;w=mul(sub(w,pos),scale)
#else
){vec3 uvw=pos*scale;v33 w=v33(dFdx(uvw),dFdy(uvw))//semi-analogously use dFdx()dFdy()in screenspace has bad borders
#endif
;vec3 m=vec3(0)
;w.a=maab2(w)
;if(id==0)m=vec3(1)*checker(uvw)
;else if(id==1)m=vec3(1)*checkerF2(uvw,w.a)
;else if(id==2)m=vec3(1)*checkerF3(uvw,w.a)
;col=m*doLighting(pos,vec3(.57703),nor,occ)
//;col=mix(col,vec3(.9),1.-exp(-.0001*t*t))// fog
;}
;col=pow(col,vec3(.4545))//gamma
;col*=smoothstep(2.,3.,abs(px.x))//frame border lines
;fragColor=vec4(col,1);}
| mit | [
4455,
4482,
4503,
4503,
4543
] | [
[
3872,
3952,
3992,
3992,
4018
],
[
4018,
4067,
4089,
4089,
4114
],
[
4114,
4262,
4285,
4285,
4314
],
[
4314,
4334,
4357,
4357,
4386
],
[
4386,
4403,
4426,
4426,
4455
],
[
4455,
4482,
4503,
4503,
4543
],
[
4543,
4570,
4592,
4592,
4615
],
[
4616,
4616,
4638,
4638,
4667
],
[
4668,
4668,
4689,
4689,
4718
],
[
4718,
4730,
4752,
4752,
4781
],
[
4782,
4782,
4805,
4805,
4830
],
[
4833,
4833,
4852,
4852,
4875
],
[
5165,
5165,
5183,
5183,
5205
],
[
5206,
5206,
5224,
5224,
5244
],
[
5245,
5245,
5263,
5263,
5283
],
[
5284,
5284,
5302,
5302,
5323
],
[
5324,
5324,
5342,
5342,
5375
],
[
5376,
5376,
5396,
5396,
5424
],
[
5691,
5837,
5868,
5868,
6013
],
[
6013,
6130,
6161,
6161,
6317
],
[
6365,
6400,
6425,
6425,
6530
],
[
6531,
6550,
6588,
6588,
6648
],
[
6650,
6650,
6678,
6678,
6771
],
[
6773,
6773,
6861,
6861,
7360
],
[
7362,
7362,
7403,
7403,
7482
],
[
7484,
7484,
7536,
7536,
7847
],
[
7849,
7849,
7889,
7889,
8100
]
] | //v33-differentials for AA
| vec2 dt(v33 a,v33 b){ | return vec2(dot(a.a,b.a),dot(a.b,b.b));} | //v33-differentials for AA
vec2 dt(v33 a,v33 b){ | 1 | 1 |