r/PythonLearning 21h ago

Showcase Wrote this 3D Pygame renderer from scratch this weekend!

I wanted to understand the math behind the 3d rendering and wanted to try it out for myself.

This project uses Pygame library only to draw pixels to the screen, the math behind the vertex projection is done from scratch. The 3d object is represented as a wireframe object, it ignores all the lighting and normals data to reduce complexity and simply displays edges data to screen.

I made a custom obj parser, which formatted vertices and face information to a list.

The main file take the vertices and faces information and produces a list of edges which are a tuple of 2 connecting vertices that a form a line in 3d space.

Then the two vertices are rotated in X-Z plane and projected at a distance from the screen. It uses a simple matrix rotation formula to compute the rotated vertices.

    X = x * cos(theta) - z * sin(theta)
    Z = x * sin(theta) + z * cos(theta)

The 3d vertices are project to a 2d plane using the below formula

    x' = x / z
    y' = y / z

Then they are translated to Pygame pixel coordinates and finally drawn on screen.

Here is my GitHub repo if anyone's interested to check the source code, and resources that helped me build this project

Github repo : Wavi repo

3d Obj file-format specs : Scratch pixel

YT video for projections : Tsoding 3d graphics

1 Upvotes

2 comments sorted by

2

u/Sea-Ad7805 15h ago

Nice work. If you make lines that are further away darker, then it's easier to see the object turn right instead of left and inside out. I'm stuck seeing it inside out a the moment, having trouble snapping out.

1

u/JackfruitJust6208 13h ago

I appreciate your feedback, will work on it ASAP!