Quantcast
Channel: Community | MonoGame - Latest topics
Viewing all articles
Browse latest Browse all 6821

Why is my displacement effect not working? (based on code from deferred engine)

$
0
0

@GeonBit wrote:

Hi all,

I tried to copy some shader code from the awesome deferred engine here:

To add displacement to my own custom effects, but for some reason it doesn't work and I just can't figure out why..
Here's my vertex shader:

VertexShaderOutput VertexShaderMain(VertexShaderInput input)
{
// Initialize Output  
VertexShaderOutput output;

// Transform Position  
float4 worldPosition = mul(input.Position, World);
float4 viewPosition = mul(worldPosition, View);
float4 fragPosition = mul(viewPosition, Projection);
output.Position = fragPosition;
output.FragPosition = fragPosition;

// Pass Depth  
output.Depth.x = output.Position.z;
output.Depth.y = output.Position.w;
output.Depth.z = viewPosition.z;

// Build TBN Matrix (Tangent, Bitangent, Normals)
float3x3 TBN;
TBN[0] = normalize(mul(input.Tangent, (float3x3)WorldViewIT));
TBN[1] = normalize(mul(input.BiTangent, (float3x3)WorldViewIT));
TBN[2] = normalize(mul(input.Normal, (float3x3)WorldViewIT));
output.TBN = TBN;

// Pass UV  
output.UV = TextureOffset + input.UV * TexturesTiling;

// Return Output  
return output;
}

and here's the part that do displacement in the pixel shader:

	// get pixel height from depth map
	float pixelHeight = tex2D(NormalSampler, UV).a;

	// get tangent pos and tangent camera
	float3 tangentPos = mul(input.FragPosition.xyz, input.TBN);
	float3 tangentCamera = mul(CameraPosition, input.TBN);

	// calculate view direction
	float3 viewDir = normalize(tangentPos - tangentCamera);

	// calculate new UV
	float2 p = viewDir.xy / viewDir.z * pixelHeight * 0.01f;
	UV = UV - p;

Which should do the same as the code from the deferred engine. However, the result I'm getting looks like this:

Where the distort line "moves" along the surface as I change the camera angle / position.

BTW before I tried this code I had the much more primitive displacement code:

float2 offset = EyeTangent.xy * (pixelHeight * 0.04f * DisplacementScale - 0.01f) + DisplacementBias;
return uv + offset;

Which was sort-of working but looks pretty ugly and basic.

@kosmonautgames hope you see this :slight_smile:

Posts: 7

Participants: 2

Read full topic


Viewing all articles
Browse latest Browse all 6821

Trending Articles