Thursday, August 29, 2019

shaders - Rotate mesh to normal


I have some instanced geometry (basic tube meshes) laid out in a grid, and I have a noise texture (normal map) that I want to use to rotate my instances with. So head pixel in my texture is a normal and I want to rotate each instance with the corresponding normal in a shader. How can I achieve that in a shader only? Unless I am mistaking, there should only be a rotation around the X and Z axes.



Answer



You can get a rotation matrix from a a direction (\$\vec d\$) and an up vector (\$\vec u\$) (direction is the normal here).


First you need to get 2 perpendicular vectors, one pointing to the right (\$\vec r\$) and one pointing up (\$\vec t\$) when looking in the direction of the normal vector.


enter image description here



You can get \$\vec r\$ by getting the cross product of \$\vec d\$ and \$\vec u\$:


$$\vec r = \vec d \times \vec u$$


Then you can get \$\vec t\$ by doing the same to \$\vec r\$ and \$\vec d\$:


$$\vec t = \vec r \times \vec d$$


The rotation matrix can be defined by these three vectors in the following way:


$$\begin{bmatrix} \vec r_x & \vec r_y & \vec r_z & 0 \\ \vec t_x & \vec t_y & \vec t_z & 0 \\ \vec d_x & \vec d_y & \vec d_z & 0 \\ 0 & 0 & 0 & 1 \end{bmatrix}$$


Use it as a model matrix


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...