Simulating the Curvature of Spacetime in Python

by danman18 in Design > Digital Graphics

76 Views, 2 Favorites, 0 Comments

Simulating the Curvature of Spacetime in Python

Screenshot 2025-11-13 131255.png

This is how to visualize the curvature of spacetime in Python.

Supplies

To make this you need:


Python

A Code Editor

Ursina

Installing Ursina

Install Ursina with pip by typing:


'pip install ursina' or 'pip3 install ursina'

Finding a Formula

After you have installed the requirements you have to find a formula the one I used was:


y=−S⋅(G⋅M/r+ϵ​)


in this formula


y is depth of the point

S is the scale factor

G is the gravitational constant

M is the mass

r is the distance from the center of the mass (I put it as r_vertex instead)

ϵ (epsilon) is to prevent division by zero and it is a very (very) small value

Curve Plane

This is the code I used to curve the plane. It curves the plane by updating the position of individual vertices.

# plane params
size = 40 # size of plane
res = 100 # resolution of curvature

# curve plane
vertices = []
uvs = []
ys=[]
for x in range(res):
for z in range(res):
nx = (x / (res-1)) * 2 - 1
nz = (z / (res-1)) * 2 - 1

# Distance from plane center, scaled to plane size
r_vertex = math.sqrt((nx*size/2)**2 + (nz*size/2)**2)

# Depth at this vertex (more negative at center, shallower at edges)
y = (-S * (G * M) / (r_vertex + epsilon))
ys.append(y)

vertices.append(Vec3(nx*size/2, y, nz*size/2))
uvs.append((x/(res-1), z/(res-1)))

# tringles :)
triangles = []
for x in range(res-1):
for z in range(res-1):
i = x*res + z
triangles += [
i, i+1, i+res,
i+1, i+res+1, i+res
]

# plane entity
plane = Entity(
model=Mesh(vertices=vertices, triangles=triangles, uvs=uvs, mode='triangle'),
texture=gridTex,
texture_scale=(10,10),
double_sided=True
)

Put It Together

Put together the formula and the curvature code along with other ursina stuff and you're done!!!

Downloads

Controls (if You're Using My Code)

I added some controls to move around the scene in my code.

Drag left or right to rotate around the mass

Up arrow to move closer to the mass

and Down arrow to move away


V changes the plane from the grid texture to a white texture and vice versa (helpful if you zoom out and the grid is no longer useful)

Done :)

Screenshot 2025-11-13 131255.png

Now you're done :D Try changing the mass and radius and really just play around with it. You can get some really interesting results by tweaking the values. Here's a challenge for you: make a black hole🕳️.

If there are any bugs please tell me in the comments. Thx for reading :D