Home Game Development opengl – Manual calc of perspective projection and getting point on the screen

opengl – Manual calc of perspective projection and getting point on the screen

0
opengl – Manual calc of perspective projection and getting point on the screen

[ad_1]

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);
glLoadIdentity();
gluPerspective(fov, aspectRatio, zNear, zFar);

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

gray platform render

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);
glLoadIdentity();
glOrtho(0, 960, 480, 0, 1, -1);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

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:

projection matrix formula

Result of my code:

result 2

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

[ad_2]