I’m writing a shader to split an image horizontally into two pieces and offset the upper half by _Offset.
I set the tilling and offset of the texture to (2, 2, -0.5, -0.5), so I could scale the image down by 0.5 and center it in the middle of the plane. I set the wrap mode of this texture to Clamp and cropped it a little bit.
The result looks like this, a strange horizontal line appears in the middle of the plane.

And this is what I expected.

Here is the shader I am using, the upper fragment is the correct one, but it samples two times and might have some extra performance cost when I want to have more slices.
Shader "Unlit/SimpleShader"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_Offset ("Offset", Range(-1, 1)) = 0.5
[Toggle(_USE_CORRECT_FRAGMENT_SHADER)] _UseCorrect ("Use Correct Shader", float) = 0
}
HLSLINCLUDE
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"
#pragma multi_compile _ _USE_CORRECT_FRAGMENT_SHADER
sampler2D _MainTex;
float4 _MainTex_ST;
float _Offset;
float _UseCorrect;
struct Attributes
{
float4 positionOS : POSITION;
float2 uv : TEXCOORD0;
};
struct Varyings
{
float4 positionCS : SV_POSITION;
float2 texcoord : TEXCOORD0;
};
Varyings vert(Attributes input)
{
Varyings output = (Varyings)0;
VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS.xyz);
output.positionCS = vertexInput.positionCS;
output.texcoord = input.uv * _MainTex_ST.xy + _MainTex_ST.zw;
return output;
}
#if _USE_CORRECT_FRAGMENT_SHADER
float4 frag(Varyings input) : SV_Target
{
float2 uvOffset = input.texcoord;
float4 mainTex = tex2D(_MainTex, uvOffset);
if (input.texcoord.y >= 0.5)
{
uvOffset.x += _Offset;
mainTex = tex2D(_MainTex, uvOffset);
}
return mainTex;
}
#else
float4 frag(Varyings input) : SV_Target
{
float2 uvOffset = input.texcoord;
if (input.texcoord.y >= 0.5)
{
uvOffset.x += _Offset;
}
float4 mainTex = tex2D(_MainTex, uvOffset);
return mainTex;
}
#endif
ENDHLSL
SubShader
{
Tags{ "Queue" = "Transparent" }
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
ZWrite Off
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
ENDHLSL
}
}
}
Is it a bug related to branches in unity?
How should I fix it if I only want to make one sample?
I am using Unity 2020.3.2f1, DX11, Universal Render Pipeline. Haven’t tested on other platforms yet.
Thanks in advance.