# Manual calc of perspective projection and getting point on the screen

I'm need to draw the red rect on the first vertex of gray platform.

To begin with, I draw a gray platform with a perspective projection and set it using gluPerspective:

float fov = 69;
float aspectRatio = 960.0f / 480.0f;
float zNear = 0.1;
float zFar = 1000.0;

glMatrixMode(GL_PROJECTION);
gluPerspective(fov, aspectRatio, zNear, zFar);

glMatrixMode(GL_MODELVIEW);
gluLookAt(
0.0f, 0.0f, 5.0f,
0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f
);


Then, I will install an orthographic projection on the whole screen. The rendering starts from the upper-left corner of the window. My task is to draw a red square at the point where the first vertex of the gray platform begins to be drawn:

glMatrixMode(GL_PROJECTION);
glOrtho(0, 960, 480, 0, 1, -1);

glMatrixMode(GL_MODELVIEW);

drawRedRect(Project(glm::vec3(-1.0f, -1.0f, -1.0f), fov, aspectRatio, zNear, zFar));


Code for Project function:

float fov = tan(fovy / 2.0F);
glm::mat4x4 identity = glm::mat4x4(
1.0f, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
glm::mat4x4 projectionMatrix = glm::mat4x4(
fov / aspectRatio, 0.0f, 0.0f, 0.0f,
0.0f, fov, 0.0f, 0.0f,
0.0f, 0.0f, (zFar + zNear) / (zNear - zFar), (2.0f * zFar * zNear) / (zNear - zFar),
0.0f, 0.0f, -1.0f, 0.0f
);

glm::mat4x4 lookAt = glm::lookAt(
glm::vec3(0.0f, 0.0f, 5.0f),
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f)
);

glm::vec4 platformVector4 = glm::vec4(platformVector.x, platformVector.y, platformVector.z, 1.0f);
platformVector4 = projectionMatrix * lookAt * platformVector4;
//platformVector4 /= platformVector4.w;

float halfWidth = 960.0f / 2.0f;
float halfHeight = 480.0f / 2.0f;

glm::vec2 screenProjectedVector = glm::vec2(
halfWidth + (platformVector4.x * 960.0f) * 0.5f,
halfHeight - (platformVector4.y * 480.0f) * 0.5f
);

return screenProjectedVector;


I also tried to use float fov = tan(glm::radians(fovy / 2.0F));, but it didn't get successful result.

According to the formula used by gluPerspective, I calculated the fov and the perspective projection matrix:

Result of my code:

But I need the square to be on the first vertex, and it's unclear where.

• You can cast a ray from the vertex point to the eye. Then based on the distance between camera and eye scale the dot. No need for orthographic projections. Nov 30, 2023 at 13:13