How I can get the distance in a glm perspective projection that will represent 1 pixel in my screen?

Viewed 163

I have the following glm perspective projection

world.cameraProjection = glm::perspective(glm::radians(45.0f), app.aspectRatio, 0.0f, 100.0f);
world.cameraProjection = glm::scale(world.cameraProjection, world.scale);
world.cameraView = glm::translate(world.cameraProjection, world.camera);

And I will like to guess the value I will have to use to draw a line that has pixel perfect width.

I know the width of my screen, and I'm trying now to translate the percentage of the viewport that represents 1 pixel into a distance for the glm cameraView. So even if the zoom changes the line I'm drawing will appear always the same size in the screen.

Is there a function in glm to do this?

1 Answers

When using Perspective projection, the x- and y-distance that represents one pixel depends on the depth (z-distance).

A projected size in normalized device space can be transformed to a size in view space with:

aspect = width / height
tanFov = tan(fov_y / 2.0) * 2.0;

dist_x = ndc_dist_x * z_eye * tanFov * aspect;
dist_y = ndc_dist_y * z_eye * tanFov;

What you want is that:

height * (ndc_dist_y + 1) / 2 == 1

So if you know the z-distance of an object, the formula is:

dist = z_eye * (2.0 / height - 1.0) * tan(fov_y / 2.0) * 2.0

where fov_y is the field of view in radiant, height is the height of the field of view in pixels, and z_eye is the absolute distance from the object to the camera.


Consider using parallel projection (Orthographic projection), where the size of the projection does not depend on the distance from the camera.

Related