Skip to content

Instantly share code, notes, and snippets.

@hman278
Created May 26, 2024 08:12
Show Gist options
  • Save hman278/1051405fed47d863c2c41d92355dcb8f to your computer and use it in GitHub Desktop.
Save hman278/1051405fed47d863c2c41d92355dcb8f to your computer and use it in GitHub Desktop.
Shader function for Unity to randomize texture tiling using hashing
// Credit: https://www.shadertoy.com/view/lt2GDd
half4 hash4(float2 p)
{
return frac(sin(float4(1.0 + dot(p, float2(37.0, 17.0)),
2.0 + dot(p, float2(11.0, 47.0)),
3.0 + dot(p, float2(41.0, 29.0)),
4.0 + dot(p, float2(23.0, 31.0)))) * 103.0);
}
half4 HashedTextureNoTile(
Texture2D<float4> mixedTexture
, SamplerState mixedTextureSampler
, in half2 sampledUVs
, half tilingOffset
)
{
half2 iuv = floor(sampledUVs);
half2 fuv = frac(sampledUVs);
half4 ofa = hash4(iuv + float2(0.0, 0.0));
half4 ofb = hash4(iuv + float2(1.0, 0.0));
half4 ofc = hash4(iuv + float2(0.0, 1.0));
half4 ofd = hash4(iuv + float2(1.0, 1.0));
half2 duvdx = ddx(sampledUVs);
half2 duvdy = ddy(sampledUVs);
// transform per-tile uvs
ofa.zw = sign(ofa.zw - 0.5);
ofb.zw = sign(ofb.zw - 0.5);
ofc.zw = sign(ofc.zw - 0.5);
ofd.zw = sign(ofd.zw - 0.5);
// uv's, and derivarives (for correct mipmapping)
half2 uva = sampledUVs * ofa.zw + ofa.xy; half2 ddxa = duvdx * ofa.zw; half2 ddya = duvdy * ofa.zw;
half2 uvb = sampledUVs * ofb.zw + ofb.xy; half2 ddxb = duvdx * ofb.zw; half2 ddyb = duvdy * ofb.zw;
half2 uvc = sampledUVs * ofc.zw + ofc.xy; half2 ddxc = duvdx * ofc.zw; half2 ddyc = duvdy * ofc.zw;
half2 uvd = sampledUVs * ofd.zw + ofd.xy; half2 ddxd = duvdx * ofd.zw; half2 ddyd = duvdy * ofd.zw;
// fetch and blend
half2 b = smoothstep(0.25, 0.75, fuv);
return lerp(lerp(mixedTexture.SampleGrad(mixedTextureSampler, uva + tilingOffset, ddxa, ddya),
mixedTexture.SampleGrad(mixedTextureSampler, uvb + tilingOffset, ddxb, ddyb ), b.x ),
lerp(mixedTexture.SampleGrad(mixedTextureSampler, uvc + tilingOffset, ddxc, ddyc ),
mixedTexture.SampleGrad(mixedTextureSampler, uvd + tilingOffset, ddxd, ddyd ), b.x), b.y );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment