Skip to content

Instantly share code, notes, and snippets.

@kraj0t
Last active March 30, 2025 22:57
Show Gist options
  • Save kraj0t/c5a3c79c8b35904a83d0d99104dbb7c0 to your computer and use it in GitHub Desktop.
Save kraj0t/c5a3c79c8b35904a83d0d99104dbb7c0 to your computer and use it in GitHub Desktop.
Shader notes, tips and tricks

Reconstruct faceted normal from position

normalWS = normalize(cross(ddy(IN.positionWS), ddx(IN.positionWS)));

_ScreenParams vs _ScreenSize

Unity documentation is wrong when it explains _ScreenParams, and _ScreenSize is not documented. _ScreenParams contains the actual screen size, while _ScreenSize contains the size of the camera’s target texture. This is important because the camera's texture (the buffer) can vary with Render Scale. Also, note that the .z and .w components are calculated differently.

How to override clamp & filtering settings in textures

In GlobalSamplers.hlsl 6 different samplers are defined. You can use those instead of SAMPLER(sampler_MyTex) if you want to hardcode how the sampling must work.

This is useful in case your shader must use certain sampling mode, or if the shader's texture properties are hidden from the user.

For example, if your shader must always work with trilinear filtering, such as for reflection cubemaps, you could use sampler_TrilinearClamp.

Also, as stated in GlobalSamplers.hlsl, there is a limit to how many active samplers a shader can have.

Check if a texture property has not been defined

If a map is undefined in the material, then it will use the built-in texture. Since those textures are at most 4x4, we can check the size of the texture in the shader and avoid having another boolean that the artist needs to set:

if (_MyTexture_TexelSize.z > 4)

Different matcap techniques

Implementation here, as explained by Ben Golus here

Links of interest

  • Gists by Ben Golus here
  • 3 Matcap implementation techniques by Ben Golus here. Select among them with unity_OrthoParams.w

Use ObjectFactory in editor where possible

Internally, Unity uses ObjectFactory (most of the time, at least). You can use it to react to components being added in the editor.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment