Perspective Divide

Simple image for expalan Perspective Divide:

In our goal, we need to find out the P' of x and y which are projected from 3D world. The Z is the key.

Find P' x

Find P' y

Feel bad for my handwriting :(

But Based on forumlar we know, the Z with X and Y relationship)

If in the left hand coordinte, the bigger Z and the X' and Y' will become smaller

If in the right hand coordinte, the smaller Z, the X and Y will become smaller.

Define 3D vector

typedef struct {
  float x;
  float y;
  float z;
} vec3_t;

Define the camera.

vec3_t camera_position = { .x = 0, .y = 0, .z = -5 };

create an 3D cube as 9 x 9 x 9 cube by using 3D vector.

vec3_t cube_points[9 * 9 * 9];

for(float x = -1; x <= 1; x += 0.25) {
    for(float y = -1; y <= 1; y += 0.25) {
      for(float z = -1; z <= 1; z += 0.25) {
        vec3_t point = { .x = x, .y = y, .z = z}; // c99 format

        cube_points[point_count++] = point;        
      }
    }
}

projection function:

vec2_t project(vec3_t point) {

  vec2_t projected_point = {
    .x = (fov * point.x) / point.z,
    .y = (fov * point.y) / point.z
  };
  return projected_point;
}


for(int i = 0; i < (9 * 9 * 9); i++) {
    vec3_t point = cube_points[i];
    // adjust each point Z to smaller distance with our screen, in our coordinte, the X and Y will become smaller.
     point.z -= camera_position.z; 

    // Project the current point
    vec2_t projected_point = project(point);
    // Save the projected 2D vector in the array
    projected_points[i] = projected_point;
}

Result:

Prove that the Z can effect the X and y. We adjust the Z value on each game loop.

camera_position.z += 0.001;

Resources: pikuma course

Date: 2023-12-27 Wed 00:00

Author: Terry Fung

Created: 2024-11-10 Sun 14:09

Emacs 29.4 (Org mode 9.6.15)

Validate