float SobelEdgeDetection(float2 uv, sampler2D tex)
// Sobel filter kernels for horizontal and vertical edge detection
float3 Gx[3] = { float3(-1, 0, 1), float3(-2, 0, 2), float3(-1, 0, 1) };
float3 Gy[3] = { float3(1, 2, 1), float3(0, 0, 0), float3(-1, -2, -1) };
float texelSize = 1.0 / 512.0; // Adjust based on your texture size
float2(-texelSize, texelSize), // Top-left
float2(0.0, texelSize), // Top
float2(texelSize, texelSize), // Top-right
float2(-texelSize, 0.0), // Left
float2(texelSize, 0.0), // Right
float2(-texelSize, -texelSize), // Bottom-left
float2(0.0, -texelSize), // Bottom
float2(texelSize, -texelSize) // Bottom-right
// Sample the texture at each offset and apply Sobel filters
for (int i = 0; i < 8; i++)
sample[i] = tex2D(tex, uv + texOffset[i]).rgb;
// Calculate the Sobel response for X and Y directions
float3 edgeX = Gx[0] * sample[0] + Gx[1] * sample[1] + Gx[2] * sample[2] +
Gx[0] * sample[3] + Gx[2] * sample[4] +
Gx[0] * sample[5] + Gx[1] * sample[6] + Gx[2] * sample[7];
float3 edgeY = Gy[0] * sample[0] + Gy[1] * sample[1] + Gy[2] * sample[2] +
Gy[0] * sample[3] + Gy[2] * sample[4] +
Gy[0] * sample[5] + Gy[1] * sample[6] + Gy[2] * sample[7];
// Calculate the magnitude of the gradient
float edgeMagnitude = length(edgeX) + length(edgeY);
return saturate(edgeMagnitude); // Clamp the result between 0 and 1