# Transformation in OpenGL

## Orthographic projection (正交投影)

\begin{aligned} M_{ortho} &= \begin{bmatrix} \frac{2}{r - l} & 0 & 0 & 0\\ 0 & \frac{2}{t - b} & 0 & 0\\ 0 & 0 & \color{red}{-\frac{2}{f - n}} & 0\\ 0 & 0 & 0 & 1 \end{bmatrix}\begin{bmatrix} 1 & 0 & 0 & -\frac{r + l}{2}\\ 0 & 1 & 0 & -\frac{t + b}{2}\\ 0 & 0 & 1 & -\frac{n + f}{2}\\ 0 & 0 & 0 & 1 \end{bmatrix}\\ &= \begin{bmatrix} \frac{2}{r - l} & 0 & 0 & -\frac{r + l}{r - l}\\ 0 & \frac{2}{t - b} & 0 & -\frac{t + b}{t - b}\\ 0 & 0 & -\frac{2}{f - n} & -\frac{f + n}{f - n}\\ 0 & 0 & 0 & 1 \end{bmatrix} \end{aligned}

## Perspective projection (透视投影)

$$y’ = \color{red}{\left|\frac{n}{z}\right|}y$$

$$x’ = \color{red}{\left|\frac{n}{z}\right|}x$$

$$\begin{bmatrix} x\\y\\z\\1 \end{bmatrix} \Rightarrow \begin{bmatrix} \color{red}{-nx/z}\\\color{red}{-ny/z}\\\text{unknown}\\1 \end{bmatrix} = ^ {\times \color{red}{-z}}\begin{bmatrix} nx\\ny\\\text{still unknown}\\\color{red}{-z} \end{bmatrix}$$

$$M_{persp \rightarrow ortho} \begin{bmatrix} x\\y\\z\\1 \end{bmatrix}=\begin{bmatrix} nx\\ny\\\text{unknown}\\z \end{bmatrix}$$

$$M_{persp \rightarrow ortho}=\begin{bmatrix} n & 0 & 0 & 0\\ 0 & n & 0 & 0\\ ? & ? & ? & ?\\ 0 & 0 & \color{red}{-1} & 0 \end{bmatrix}$$

$$\begin{bmatrix} x\\y\\-n\\1 \end{bmatrix} \Rightarrow \begin{bmatrix} x\\y\\-n\\1 \end{bmatrix} = ^ {\times (z=n)}\begin{bmatrix} nx\\ny\\-n^2\\n \end{bmatrix}$$

$$\begin{bmatrix} 0 & 0 & A & B \end{bmatrix}\begin{bmatrix} x\\y\\-n\\1 \end{bmatrix}=-n^2$$

$$-An + B = -n ^ 2$$

$$\begin{bmatrix} 0\\0\\-f\\1 \end{bmatrix} \Rightarrow \begin{bmatrix} 0\\0\\-f\\1 \end{bmatrix} = \begin{bmatrix} 0\\0\\-f^2\\f \end{bmatrix}$$

$$\begin{bmatrix} 0 & 0 & A & B \end{bmatrix}\begin{bmatrix} 0\\0\\-f\\1 \end{bmatrix}=-f^2$$

$$-Af + B = -f ^ 2$$

$$\begin{cases} -An + B = -n ^ 2\\ -Af + B = -f ^ 2 \end{cases}$$

$$A = n + f, B = nf$$

$$M_{persp \rightarrow ortho}=\begin{bmatrix} n & 0 & 0 & 0\\ 0 & n & 0 & 0\\ 0 & 0 & n + f & nf\\ 0 & 0 & -1 & 0 \end{bmatrix}$$

$$M_{persp} = M_{ortho}M_{persp \rightarrow ortho} = \begin{bmatrix} \frac{2n}{r - l} & 0 & \frac{r + l}{r - l} & 0\\ 0 & \frac{2n}{t - b} & \frac{t + b}{t - b} & 0\\ 0 & 0 & -\frac{f + n}{f - n} & -\frac{2nf}{f - n}\\ 0 & 0 & -1 & 0 \end{bmatrix}$$

• aspect ratio 宽高比
• field-of-view fov 垂直可视角度

$$\tan \frac{fovY}{2} = \frac{t}{\left|n\right|}$$ $$aspect = \frac{r}{t}$$

$$M_{persp} = \begin{bmatrix} \frac{1}{\tan(\text{fov} / 2)\cdot \text{aspect}} & 0 & 0 & 0\\ 0 & \frac{1}{\tan(\text{fov} / 2)} & 0 & 0 \\ 0 & 0 & - \frac{f + n}{f - n} & -\frac{2fn}{f - n}\\ 0 & 0 & -1 & 0 \end{bmatrix}$$

## 法线变换矩阵 (The Normal Transformation Matrix)

$$\boldsymbol{N’} \cdot \boldsymbol{T’} = (G \boldsymbol{N}) \cdot (M \boldsymbol{T}) = (G\boldsymbol{N})^T(M \boldsymbol{T}) = \boldsymbol N ^ T G^T M \boldsymbol T = \boldsymbol N \cdot \boldsymbol T = 0$$

$$G^TM = I \Rightarrow G = (M^{-1})^T$$

# ,