Write a Shadertoy example showing superquadrics as SDF
- User
Write a Shadertoy example showing superquadrics as SDF
Assistant
Shadertoy is a popular online platform for creating and sharing shaders, particularly those written in the GLSL (OpenGL Shading Language). SDF (Signed Distance Functions) are commonly used in shaders to describe the shape of objects in a procedural manner, which is very useful for ray marching and other rendering techniques.
Superquadrics are a family of geometric shapes that can range from spheres to cubes and other interesting shapes, depending on their parameters. They are defined by two exponents, usually denoted as (e_1) and (e_2), which control the shape's roundness in the xy-plane and the z-direction, respectively.
Below is a simple example of a Shadertoy shader that uses an SDF for a superquadric. This example is designed to be pasted into a new shader on Shadertoy. It includes a basic setup for rendering the superquadric using ray marching.
glsl#ifdef GL_ES precision mediump float; #endif uniform vec2 iResolution; // Viewport resolution (in pixels) uniform float iTime; // Shader playback time (in seconds) // Signed distance function for a superquadric float superquadricSDF(vec3 p, float e1, float e2) { float r = length(p.xy) / length(p.z); float s = length(p.yz) / length(p.x); return pow(pow(r, e1) + pow(s, e2), 1.0 / (e1 + e2)); } // Ray marching setup vec3 rayDirection(vec2 fragCoord, vec2 iResolution, float iTime) { vec2 uv = fragCoord / iResolution.xy; uv = uv * 2.0 - 1.0; uv.x *= iResolution.x / iResolution.y; vec3 ro = vec3(0.0, 0.0, -3.0); // Camera position vec3 rd = normalize(vec3(uv, 1.0)); return rd; } // Ray marching function float rayMarch(vec3 ro, vec3 rd) { const int maxSteps = 64; const float minDistance = 0.01; float t = 0.0; for (int i = 0; i < maxSteps; i++) { vec3 pos = ro + t * rd; float d = superquadricSDF(pos, 2.0, 2.0); // Adjust e1 and e2 to change shape if (d < minDistance || t > 10.0) break; t += d; } return t; } void mainImage(out vec4 fragColor, in vec2 fragCoord) { vec2 uv = fragCoord / iResolution.xy; vec3 rd = rayDirection(fragCoord, iResolution, iTime); vec3 ro = vec3(0.0, 0.0, -3.0); float t = rayMarch(ro, rd); vec3 pos = ro + t * rd; vec3 color = vec3(0.0); if (t < 10.0) { color = vec3(1.0, 0.0, 0.0); // Red color for the superquadric surface } else { color = vec3(0.2, 0.3, 0.5); // Background color } fragColor = vec4(color, 1.0); } void main() { mainImage(gl_FragColor, gl_FragCoord.xy); }- User
The image appears black, is there a mistake?
Assistant
Apologies for the oversight. The provided code snippet had a few issues that would prevent it from rendering the superquadric correctly. Here's an updated version of the shader code that should work on Shadertoy:
glsl
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.