设模型变换矩阵为$\bold M$,视图变换矩阵为$\bold V$,投影变换矩阵为$\bold P$,Local坐标为$\bold v_0$,裁剪坐标为$\bold v_{clip}$,NDC坐标为$\bold v_{ndc}$,那么有如下的MVP变换:
$$ \begin{aligned} &\bold v_{clip}=\bold{PVM}\times \bold v_{0}&&(1)\\ &\bold v_{ndc}= \bold v_{clip}/ \bold v_{clip}.w&&(2) \end{aligned} $$
相当于MVP的逆变换,得到的是$\bold v_{world}$,容易知道:
$$ \bold v_{world}=(\bold {PV})^{-1}\times \bold v_{clip} $$
由(2)式可知:
$$ \bold v_{clip}=\bold v_{ndc}\times \bold v_{clip}.w $$
我们的目标是:已知$\bold v_{ndc}$和变换矩阵,求出$\bold v_{world}$。
容易知道:
$$ \begin{aligned} \bold v_{world}&=(\bold {PV})^{-1}\times \bold v_{clip}\\ &=(\bold {PV})^{-1}\times \bold v_{ndc}\times \bold v_{clip}.w \end{aligned} $$
如何计算$\bold v_{clip}.w$?可以这样想,因为$\bold v_{world}.w=1$,因此可以对两边同时取$w$分量:
$$ \begin{aligned} \bold v_{clip}.w&=\frac{\bold v_{world}.w}{((\bold {PV})^{-1}\times \bold v_{ndc}).w}\\ &=\frac{1}{((\bold {PV})^{-1}\times \bold v_{ndc}).w} \end{aligned} $$
所以:
$$ \bold v_{world}=\frac{(\bold {PV})^{-1}\times \bold v_{ndc}}{((\bold {PV})^{-1}\times \bold v_{ndc}).w} $$
所以,我们不需要$\bold v_{clip}.w$也是可以得到世界坐标的。
glsl代码如下:
float depth = texture(depthTex, texcoord);
vec4 ndcPos = vec4(2 * texcoord, 2 * depth - 1, 1.0f);
vec4 worldPos = InverseVP * ndcPos;
worldPos /= worldPos.w
在后处理阶段常常需要用到世界坐标,但是实际上这个阶段上我们常常是通过采样存储世界坐标的贴图来获得世界坐标的。这样子很占用显存。而深度重建就可以不需要坐标贴图,通过重建获得世界坐标,而性能损耗也很小,确减少了很多的显存占用。所以推荐使用深度重建来获得世界坐标。