【OpenGL】透视投影矩阵推导

项目场景:

  • 系统:ubuntu
  • glad + glfw + opengl3.3
    复习games101MVP变换,在使用OpenGL检验推导透视投影矩阵时,发现得出结果的Z坐标与把不符合目标预期。可以看到下面代码,四个矩形从前到后的顺序应该是RGB然后才到粉色,可是实际是反过来的。
    验证正常推导情况

问题描述

为什么缩放Z轴需要为负数(红圈的地方,已经加入负号,最终效果正确)。
透视投影推导过程


原因分析:

为什么会这样呢?在纸上反复计算了半天后,刷手机看机了罗斯大佬的视频
探秘三维透视投影 - 齐次坐标的妙用,才发现原来OpenGL转NDC时,默认是近平面映射到-1,远平面映射到1,我大呼白费力气,原来一开始就错了,难怪算半天没发现问题,原来不是算错了。
后来查看OpenGL wiki glDepthRangeglDepthFuncglClearDepth

Parameters

nearVal
Specifies the mapping of the near clipping plane to window coordinates. The initial value is 0.


farVal
Specifies the mapping of the far clipping plane to window coordinates. The initial value is 1.


Description
After clipping and division by w, depth coordinates range from −1 to 1, corresponding to the near and far clipping planes. glDepthRange specifies a linear mapping of the normalized depth coordinates in this range to window depth coordinates. Regardless of the actual depth buffer implementation, window coordinate depth values are treated as though they range from 0 through 1 (like color components). Thus, the values accepted by glDepthRange are both clamped to this range before they are accepted.

The setting of (0,1) maps the near plane to 0 and the far plane to 1. With this mapping, the depth buffer range is fully utilized.

这里意思是
Z轴变换过程
压缩的空间可以自定义,默认(0,1),OpenGL深度测试默认比小,每个像素深度值默认为1。
这也就是为什么默认值OpenGL要在透视投影变换中把Z轴翻转。
如果不想翻转,只需设置

glDepthFunc(GL_GREATER);    // 设置为比大
glClearDepth(0.0f);         // 设置默认深度值为0

修改后效果:
深度测试比大
参考代码:OpenGL_Learn

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值