Normal mapping and tangent space

Hi,

I am working on a custom terrain that is displacement mapped in the vertex shader. The normals are calculated in the fragment shader using central differencing.

Now, from the looks of it I have to calculate the tangents as well to get correct lighting. Is there a way around this (it’s a pretty expensive calculation…)? E.g. convert the light vector instead (I don’t have to add normals).

Please be patient, all this shader stuff is pretty new to me…

Thanks!

check unity default shader sources, there is a fast tangent estimation there.
Actually, why not use the default unity normal mapped shader anyways.

Depends on the mesh you’re displacing, but if it’s a uniform grid with uniform grid UVs then the tangents will be the same at every vertex, so you can effectively hard-code them and then gram-schmidt orthogonalise them to the normals.

I think something along the lines of…

float3 tangent = float3(0,1,0); // This will vary depending on the UV alignment. But one of these should be 1 and the rest 0.
tangent = tangent - dot(tangent, normal) * normal; // Orthogonalise the tangent to the normal you've calculated.
float3 binormal = cross(normal, tangent); // Calculate the binormal to be orthogonal to the normal and tangent.
float3x3 rotation = float3x3(tangent, binormal, normal); // Here's your OS->TS matrix.

Great, thanks for the tips, I’ll try them out.

@Aubergine: It’s not a simple displacement mapping, but rather an implementation of geo clipmaps, so I can’t use the default shader. But you’re right, the default shader sources are always a good place to look for hints.

You mean you dont use the default terrain but a custom lod mesh instead?
Why dont you calculate the tangents from script and pass to shader then?