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$:


r=d×u


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


t=r×d


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


[rxryrz0txtytz0dxdydz00001]


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...