Question about nearZ, farZ, and camera position relationship in perspective projection

The Partridge Family were neither partridges nor a family. Discuss.
Post Reply
WilsonHuang
Posts: 44
Joined: February 13th, 2019, 3:23 am

Question about nearZ, farZ, and camera position relationship in perspective projection

Post by WilsonHuang » October 27th, 2021, 3:40 pm

I have 600x600 plane square. My goal is render it on screen in 1:1 ratio.
Here is my perspective projection and camera code

Code: Select all

//Perspective
gfx.SetProjection(DirectX::XMMatrixPerspectiveLH(1.0f, 1.0f / Graphics::AspectRatio, 1.0f, 1000.0f));

//camera
//every parameter is 0.0f except range
const auto position = 
        DX::XMVector3Transform(
        DX::XMVectorSet(0.0f, 0.0f, -range, 0.0f),
        DX::XMMatrixRotationRollPitchYaw(aroundX, -aroundY, 0.0f));

    return
        DX::XMMatrixLookAtLH(position, DX::XMVectorZero(),
            DX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f)) *
        DX::XMMatrixRotationRollPitchYaw(pitch, -yaw, roll);
When I set nearZ = 1.0f, the camera position.z (range) need to set 800.0f (ScreenWidth) to fill the height (see nearZ_1.png)
However, when I set nearZ = 0.5f, the range need to set 400.0f (half of ScreenWidth) to fill the height. (see nearZ_05.png)
Why? I can't figure out the relationship between nearZ and the screen width
Also the square disappears when I set range = 1000.0f. Why? 1000.0f is not greater than the farZ.
Attachments
nearZ_05.png
(130.57 KiB) Not downloaded yet
nearZ_1.png
(130.51 KiB) Not downloaded yet

albinopapa
Posts: 4373
Joined: February 28th, 2013, 3:23 am
Location: Oklahoma, United States

Re: Question about nearZ, farZ, and camera position relationship in perspective projection

Post by albinopapa » October 30th, 2021, 10:49 pm

Just a guess here, but I'll try my best.

When you create a projection matrix, it defines the entire area the camera can see. Setting the near Z to 1.f would/should be where the "screen" is. By lowering the near Z, you move the near clip plane or closest viewable plane closer to the camera and increasing the range from nearZ to farZ.

As an experiment, you could create a slider that changes the nearZ and farZ values by 0.01f per step.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com

Post Reply