Last active
September 27, 2024 09:29
-
-
Save olecksamdr/5b3b89d737d7760e092f7f6dc7e18e88 to your computer and use it in GitHub Desktop.
GLSL Ray Marching Template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://youtu.be/khblXafu7iA?si=jo4m_TubKhM_ct7u | |
float sdSphere(vec3 p, float r) { | |
// signed distance to a sphere of radius 1 located at the origin | |
return length(p) - r; | |
} | |
float sdBox(vec3 p, vec3 a) { | |
vec3 q = abs(p) - a; | |
return length(max(q, 0.)) + min(max(q.x, max(q.y, q.z)), .0); | |
} | |
float smin(float a, float b, float k) { | |
float h = max(k - abs(a - b), .0) / k; | |
return min(a, b) - h * h * h * k * (1. / 6.); | |
} | |
mat2 rotate2D(float angle) { | |
float s = sin(angle); | |
float c = cos(angle); | |
return mat2(c, -s, s, c); | |
} | |
float map(vec3 p) { | |
vec3 spherePos = vec3(sin(iTime) * 3., 0, 0); | |
float sphere = sdSphere(p - spherePos, 1.); | |
//copy | |
vec3 q = p; | |
// upward movement | |
q.y -= iTime * .4; | |
// space repetition | |
q = fract(q) - .5; | |
// rotate around z axis | |
// q.xy *= rotate2D(iTime); | |
float box = sdBox(q, vec3(.1)); | |
float ground = p.y + .75; | |
return smin(ground, smin(box, sphere, 2.), 1.); | |
} | |
void mainImage( out vec4 fragColor, in vec2 fragCoord ) | |
{ | |
// Normalized pixel coordinates (from -1 to 1) | |
vec2 uv = (2. * fragCoord - iResolution.xy) / iResolution.y; | |
vec2 mouse = (2. * iMouse.xy - iResolution.xy) / iResolution.y; | |
// INITIALIZATION | |
// ray origin - camera current position | |
vec3 ro = vec3(0, 0, -3); | |
// ray direction | |
vec3 rd = normalize(vec3(uv, 1)); | |
vec3 color = vec3(0); | |
// traveled - total distance traveled from the camera origin | |
float t = 0.; | |
// Vertical camera rotation | |
ro.yz *= rotate2D(-mouse.y); | |
rd.yz *= rotate2D(-mouse.y); | |
// Horizontal camera rotation | |
ro.xz *= rotate2D(-mouse.x); | |
rd.xz *= rotate2D(-mouse.x); | |
//ro.yz *= rotate2D(-iTime * .1); | |
//rd.yz *= rotate2D(-iTime * .1); | |
//ro.xz *= rotate2D(-iTime * .1); | |
//rd.xz *= rotate2D(-iTime * .1); | |
// RAYMARCHING | |
for (int i = 0; i < 80; i++) { | |
// point along the ray | |
vec3 p = ro + rd * t; | |
// distance - current distance to the scene | |
float d = map(p); | |
// march the ray | |
t += d; | |
// if distance is to close or to far | |
if (d < 0.001 || d > 100.) break; | |
} | |
// Output to screen | |
// color based on a distance | |
color = vec3(t * .2); | |
fragColor = vec4(color, 1.); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment