Three.js Black Hole Gravitational Lensing (Ray-Traced Shader)
Real-time ray-traced Schwarzschild black hole in Three.js, with bent light paths, a photon ring, a Doppler-beamed accretion disk and a lensed starfield, all computed per pixel in a fragment shader.
Key topics: three.js black hole, gravitational lensing, ray marching, schwarzschild, accretion disk, glsl shader, general relativity
Game Over
What this code does
- Geodesic Integration: each pixel's ray is stepped with a = −1.5 h² r̂ / r⁴, which reproduces light bending in Schwarzschild spacetime.
- Event Horizon: rays that fall inside r_s are captured and stay black; rays near 1.5 r_s orbit and form the bright photon ring.
- Accretion Disk: whenever a ray crosses the equatorial plane between the inner and outer radius, disk emission is accumulated front to back.
- Lensed Disk Image: the far side of the disk appears bent over and under the hole, which is why the disk seems to wrap the shadow.
- Doppler Beaming: gas orbiting toward the camera is brightened by (1 + β·cosθ)³, giving the asymmetric glow.
- Controls: lensing strength, disk radii, brightness, beaming, ray steps and auto orbit (drag to orbit, scroll to zoom).
Related Demos
Continue Learning
JavaScript Implementation
// Fullscreen quad that ray-traces bent light around a black hole (r_s = 1)
const renderer = new THREE.WebGLRenderer()
renderer.setSize(width, height)
document.querySelector('#app').appendChild(renderer.domElement)
const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(55, width / height, 0.1, 100)
camera.position.set(0, 2, 22)
camera.lookAt(0, 0, 0)
const uniforms = {
uCamPos: { value: camera.position },
uCamWorld: { value: camera.matrixWorld },
uInvProj: { value: camera.projectionMatrixInverse }
}
const material = new THREE.ShaderMaterial({
uniforms,
vertexShader: 'varying vec2 vUv; void main () { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }',
fragmentShader: `
uniform vec3 uCamPos; uniform mat4 uCamWorld; uniform mat4 uInvProj; varying vec2 vUv;
void main () {
vec4 v = uInvProj * vec4(vUv * 2.0 - 1.0, 1.0, 1.0);
vec3 vel = normalize((uCamWorld * vec4(v.xyz / v.w, 0.0)).xyz);
vec3 pos = uCamPos;
float h2 = dot(cross(pos, vel), cross(pos, vel));
vec3 col = vec3(0.0);
for (int i = 0; i < 250; i++) {
float r = length(pos);
if (r < 1.0 || r > 80.0) break;
vec3 prev = pos;
float dt = clamp(0.06 * r, 0.02, 1.2);
vel += -1.5 * h2 * pos / pow(r, 5.0) * dt;
pos += vel * dt;
if (prev.y * pos.y < 0.0) {
float hr = length(mix(prev, pos, prev.y / (prev.y - pos.y)).xz);
if (hr > 3.0 && hr < 11.0) { col = mix(vec3(1.0, 0.9, 0.7), vec3(0.6, 0.1, 0.0), (hr - 3.0) / 8.0); break; }
}
}
gl_FragColor = vec4(col, 1.0);
}`
})
const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material)
quad.frustumCulled = false
scene.add(quad)
camera.updateMatrixWorld()
renderer.render(scene, camera)