# Tutorial: MatCaps in Unreal Engine 4

To generate matcap UV coordinates, we use the following formula:

$\begin{pmatrix} u \\ v \end{pmatrix} = \begin{pmatrix} \frac{\vec{R_x}}{\frac{3}{4} \sqrt{\vec{R_x}^{2} + \vec{R_y}^{2} + (\vec{R_z} + 1)^2}} + \frac{1}{2} \\ \frac{\vec{R_y}}{\frac{3}{4} \sqrt{\vec{R_x}^{2} + \vec{R_y}^{2} + (\vec{R_z} + 1)^2}} + \frac{1}{2} \end{pmatrix}$

where:

• $\vec{R} = \vec{C} - 2 \times (\vec{N} \cdot \vec{C}) \times \vec{N}$
• $\vec{C}$ is a unit vector pointing from the current pixel to the camera (in view-space)
• $\vec{N}$ is a unit vector of the vertex normal or pixel normal (in view-space)

In this tutorial, I demonstrate a step-by-step approach to implementing the formulae laid-out above:

To create a more realistic matcap material, we can split the diffuse and specular reflectance components into two dedicated textures (rather than having a single texture attempting to simulate both). Diffuse reflectance does not vary according to viewing angle, making spherical projection a more approperiate option for portraying it. Specular reflectance on the other hand is viewing angle dependant and ideally suited to using the original matcap projection method. Spherical projection is easily accomplished using the following formula:

$\begin{pmatrix} u \\ v \end{pmatrix} = \begin{pmatrix} \frac{1}{2} + \frac{{\rm atan2} \left(\vec{D}_z, \vec{D}_x \right)}{2\pi} \\ \frac{1}{2} - \frac{\arcsin \left(\vec{D}_y \right)}{\pi} \end{pmatrix}$

where:

• $\vec{D}$ is a unit vector pointing from the sphere’s centre to the current pixel

For a sphere, $\vec{D}$ is no different to a surface normal. This makes things very straightforward to implement!

A more resource friendly approach would be to project the same texture onto both hemispheres, essentially cutting the texture size in half. This will create a symmetry between hemispheres, which should not be too noticeable when combined with the specular texture. In order to implement this approach, we multiply u by 2: $2u$

In order to combine the diffuse and specular reflectance textures, we simply add them together ― just like nature does in real-life!

${\rm output} = {\rm diffuse} + {\rm specular}$