Hello! I found this python function on Internet to project 3d point to 2d screen. It works when Y rotation angle less then pi/2. I want to add camera movement and rotation around other axes. Thing I dont understand what do last 3 lines do? What is factor and why it is calculated by dividing by fov + z? And how projecting works?

def project(vertex, fov, rotation_angle):
    (x, y, z) = vertex
    cos_angle = math.cos(rotation_angle)
    sin_angle = math.sin(rotation_angle)
    x_rotated = x * cos_angle - z * sin_angle
    z_rotated = x * sin_angle + z * cos_angle
    factor = fov / (fov + z_rotated)
    x_proj = int((x_rotated * factor + 1) * width / 2)
    y_proj = int((-y * factor + 1) * height / 2)
    return (x_proj, y_proj)
  • pelya@lemmy.world
    link
    fedilink
    English
    arrow-up
    0
    ·
    edit-2
    9 days ago

    If you want to understand how 3D projection works, it’s better to solve a few trigonometric equations by hand on a piece of paper, then copy these equations to your Python code.

    If you just want to quickly make your own 3D renderer, simply use OpenGL API and the corresponding projection matrix. It will run the same exact formulas inside the driver, just in a 4x4 matrix form, and you can simply experiment with modifying each element of your projection matrix to make your 3D scene rotate the way you want, without bothering to understand the math.

    Simply copying some formula from the net will most probably fail.