SlideShare a Scribd company logo
3
Most read
10
Most read
13
Most read
Shaders
A brief introduction to rendering,
shaders and Unity CG shaders
Matias Lavik Dimension10
The good old days
- Send vertex data to the GPU, and specify settings such as colour and fog.
- Many limitations - less low-level control
- Some APIs had “high level” concepts, such as sprites
PlayStation 1 “PSYQ” SDK
OpenGL (fixed function pipeline)
Programmable shading pipeline
- More control through the use of shaders
- Vertex shader: modify vertex positions
- Fragment shader: modify output colour
- Newer features: Tesselation shaders and geometry shaders
- Allows you to add screen-space effects by first rendering scene to texture
OpenGL 2.0 shading pipeline
Some terminology
Vertex
- Wikipedia: “a point where two or more curves, lines, or edges meet”
- Usually: A point (and its position, normal, texCoord, etc.) in a triangle
● Position
● Normal
● Texture coordinate
● Tangent / Bitangent
Vertex buffer
- Buffered vertex data on the GPU
- Vertex data is created on the CPU and then uploaded to the video device
Vertex layout
- Order of the vertex attributes/components (position, normal, texcoord)
- Each attribute can have its own buffer (slow) or be on the same buffer
- One buffer per attribute: (VVVV) (NNNN) (CCCC)
- Blocks in a batch: (VVVVNNNNCCCC)
- Interleaved: (VNCVNCVNCVNC) (“stride” = byte offset between attributes)
Uniforms / shader constants
- OpenGL: “Uniform” ≈ DirectX: “Shader constant”
- Per-material data sent to shaders
- Vertex data is per vertex - uniforms are per material
- Examples: material properties (colour, smoothness, specular
reflectiveness), light sources, cross-section plane
- In Unity, these are called “properties”, and you can set their value using
Material::SetFloat(...) / Material::SetInt(...), etc.
Rendering
Create vertex data (array of vertices)
Create vertex buffer (send vertices to GPU)
Bind vertex buffer and index buffer, and draw
From Ming3D: https://github.com/mlavik1/Ming3D
Problems
- Many rendering APIs: OpenGL, DirectX, Vulkan, GNM (PS4), Metal
- Each rendering API has its own shader language
- GLSL (OpenGL), HLSL (DirectX)
- Need to support several rendering APIs and shader languages, and in
some cases several versions of them
Solution: Make your own shader language and convert it to GLSL, HLSL, etc..
Unity has their own shader language (based on Nvidia’s Cg)
Unity shader example
Shaders in Unity
Name of shader (and path)
Properties (textures and uniforms / shader constants)
Contains a texture with name “MainTex”
Shader pass (Unity uses different passes for shadow
casting, depth, etc)
Vertex shader
Fragment shader
Various features
- Math functions
- sin(x), cos(x), tan(x)
- Standard library functions
- lerp(a, b, t)
- smoothstep(a, b, t)
- clamp(x, a, b)
- length(v)
- tex2D(texture, texCoord)
- http://developer.download.nvidia.com/CgTutorial/cg_tutorial_appendix_e.html
- Built-in shader variables
- _Time: Time since level load (t/20, t, t*2, t*3)
- https://docs.unity3d.com/Manual/SL-ShaderPrograms.html
TeleportCursor.shader
(from VirtuaView)
Shader semantic
- MSDN: “A semantic is a string attached to a shader input or output that
conveys information about the intended use of a parameter”
- Unity needs to know which attributes in the vertex layout are position,
normal, etc. (so it can buffer your mesh correctly)
- Some rendering APIs require semantics on all input/output data
- Vertex input/output: POSITION, TEXCOORD0, TEXCOORD1, NORMAL,
COLOR, TANGENT
- Fragment shader output: SV_Target
- Multiple render targets: SV_Target0, SV_Target1,..
Shader properties
- Syntax: _PropertyName(“visual name”, type) = value
- Types:
- “int”
- “Vector”
- “Color”
- “2D” (texture)
Including
- You can split shader into several files, by putting common function in a
.cginc-file
- Unity’s standard shader functions are in:
- UnityStandardCore.cginc
- UnityStandardCoreForward.cginc
- UnityStandardShadow.cginc
- UnityStandardMeta.cginc
Unity shader includes location:
Program FilesUnityEditorDataCGIncludes
Multicompiler shader program variants
- If you want to enable/disable a set of features in a shader, without passing a
boolean uniform and checking its value, you can use multicompile program
variants
1. Add this after CGPROGRAM: #pragma multi_compile __ YOUR_DEFINE
2. Use #if YOU_DEFINE_HERE to conditionally enable/disable feature
3. Enable feature with: material.EnableKeyword("YOUR_DEFINE");
4. Disable feature with: material.DisableKeyword("YOUR_DEFINE");
This will create two versions of the shader: One where the the “YOUR_DEFINE”
preprocessor definition is defined, and one where it is not.
The #if-check is done at compile time (or when shader is converted)
Use shader_feature for multicompile definitions that will only be set in the material
AmbientOcclusion.shader AmbientOcclusion.cginc
AmbientOcclusion.cs
Example from my addition to Unity’s SSAO postprocessing effect
Debugging
- Unity has RenderDoc integrations
- RenderDoc allows you to capture a frame, see all render API calls,
visualise input/output if each shader pass, visualise textures, inspect
material properties (uniforms / shader constants) and much more.
- See: https://docs.unity3d.com/Manual/RenderDocIntegration.html
- Alternatively use the Visual Studio shader debugger, which allows you to
add breakpoints, step through code and more:
https://docs.unity3d.com/Manual/SL-DebuggingD3D11ShadersWithVS.ht
ml
1. Download RenderDoc: https://renderdoc.org/builds
2. Include #pragma enable_d3d11_debug_symbols in your shader’s
CGPROGRAM block, if you want to see property names and more.
3. Right-click on “Game” tab and load RenderDoc
4. While in-game, capture a frame

More Related Content

PDF
An introduction to Realistic Ocean Rendering through FFT - Fabio Suriano - Co...
PDF
Best Practices for Shader Graph
PDF
Optimizing the graphics pipeline with compute
PPSX
Oit And Indirect Illumination Using Dx11 Linked Lists
PPSX
Dx11 performancereloaded
PPT
Light prepass
PPTX
Siggraph 2016 - Vulkan and nvidia : the essentials
PDF
Forward+ (EUROGRAPHICS 2012)
An introduction to Realistic Ocean Rendering through FFT - Fabio Suriano - Co...
Best Practices for Shader Graph
Optimizing the graphics pipeline with compute
Oit And Indirect Illumination Using Dx11 Linked Lists
Dx11 performancereloaded
Light prepass
Siggraph 2016 - Vulkan and nvidia : the essentials
Forward+ (EUROGRAPHICS 2012)

What's hot (20)

PPTX
Shader Programming With Unity
PDF
「原神」におけるコンソールプラットフォーム開発
PDF
Optimizing HDRP with NVIDIA Nsight Graphics – Unite Copenhagen 2019
PDF
Rendering AAA-Quality Characters of Project A1
PPTX
Decima Engine: Visibility in Horizon Zero Dawn
PPT
Frostbite Rendering Architecture and Real-time Procedural Shading & Texturing...
PPTX
Physically Based Sky, Atmosphere and Cloud Rendering in Frostbite
PPTX
Five Rendering Ideas from Battlefield 3 & Need For Speed: The Run
PPTX
Anti-Aliasing Methods in CryENGINE 3
PPTX
4K Checkerboard in Battlefield 1 and Mass Effect Andromeda
PPTX
Rendering Technologies from Crysis 3 (GDC 2013)
PPTX
A Certain Slant of Light - Past, Present and Future Challenges of Global Illu...
PPT
Secrets of CryENGINE 3 Graphics Technology
PDF
【Unite Tokyo 2018】『崩壊3rd』開発者が語るアニメ風レンダリングの極意
PPT
Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)
PPT
Crysis Next-Gen Effects (GDC 2008)
PPTX
Hable John Uncharted2 Hdr Lighting
PPTX
Moving Frostbite to Physically Based Rendering
PPTX
The Rendering Technology of Killzone 2
PPTX
FrameGraph: Extensible Rendering Architecture in Frostbite
Shader Programming With Unity
「原神」におけるコンソールプラットフォーム開発
Optimizing HDRP with NVIDIA Nsight Graphics – Unite Copenhagen 2019
Rendering AAA-Quality Characters of Project A1
Decima Engine: Visibility in Horizon Zero Dawn
Frostbite Rendering Architecture and Real-time Procedural Shading & Texturing...
Physically Based Sky, Atmosphere and Cloud Rendering in Frostbite
Five Rendering Ideas from Battlefield 3 & Need For Speed: The Run
Anti-Aliasing Methods in CryENGINE 3
4K Checkerboard in Battlefield 1 and Mass Effect Andromeda
Rendering Technologies from Crysis 3 (GDC 2013)
A Certain Slant of Light - Past, Present and Future Challenges of Global Illu...
Secrets of CryENGINE 3 Graphics Technology
【Unite Tokyo 2018】『崩壊3rd』開発者が語るアニメ風レンダリングの極意
Terrain Rendering in Frostbite using Procedural Shader Splatting (Siggraph 2007)
Crysis Next-Gen Effects (GDC 2008)
Hable John Uncharted2 Hdr Lighting
Moving Frostbite to Physically Based Rendering
The Rendering Technology of Killzone 2
FrameGraph: Extensible Rendering Architecture in Frostbite
Ad

Similar to Shaders in Unity (20)

PPTX
Cg shaders with Unity3D
PPT
Gpu presentation
PDF
[UniteKorea2013] The Unity Rendering Pipeline
PPTX
Shaders and the black magic
PDF
Clean architecture for shaders unite2019
PDF
Minko stage3d workshop_20130525
PDF
Game Programming 12 - Shaders
PDF
【Unite 2017 Tokyo】シェーダープログラミング入門!カスタムシェーダー、作るで!
PPT
Hardware Shaders
PDF
Shaders - Claudia Doppioslash - Unity With the Best
PDF
Unity advanced computer graphics week 02
PPTX
Shaders & Standard Shader In Unity
PPTX
Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks
PDF
Shaders in Unity by Zoel
PDF
Shader editor
PPT
Programmable Piplelines
PPTX
Working with Shader with Unity
PPTX
Pixel shaders
PDF
iOS Visual F/X Using GLSL
PDF
Hpg2011 papers kazakov
Cg shaders with Unity3D
Gpu presentation
[UniteKorea2013] The Unity Rendering Pipeline
Shaders and the black magic
Clean architecture for shaders unite2019
Minko stage3d workshop_20130525
Game Programming 12 - Shaders
【Unite 2017 Tokyo】シェーダープログラミング入門!カスタムシェーダー、作るで!
Hardware Shaders
Shaders - Claudia Doppioslash - Unity With the Best
Unity advanced computer graphics week 02
Shaders & Standard Shader In Unity
Beginning direct3d gameprogramming09_shaderprogramming_20160505_jintaeks
Shaders in Unity by Zoel
Shader editor
Programmable Piplelines
Working with Shader with Unity
Pixel shaders
iOS Visual F/X Using GLSL
Hpg2011 papers kazakov
Ad

Recently uploaded (20)

PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
PPTX
Big Data Technologies - Introduction.pptx
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Modernizing your data center with Dell and AMD
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Cloud computing and distributed systems.
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Understanding_Digital_Forensics_Presentation.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Chapter 3 Spatial Domain Image Processing.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
The AUB Centre for AI in Media Proposal.docx
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
Big Data Technologies - Introduction.pptx
Agricultural_Statistics_at_a_Glance_2022_0.pdf
NewMind AI Monthly Chronicles - July 2025
Modernizing your data center with Dell and AMD
Unlocking AI with Model Context Protocol (MCP)
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Cloud computing and distributed systems.
Advanced methodologies resolving dimensionality complications for autism neur...
Digital-Transformation-Roadmap-for-Companies.pptx

Shaders in Unity

  • 1. Shaders A brief introduction to rendering, shaders and Unity CG shaders Matias Lavik Dimension10
  • 2. The good old days - Send vertex data to the GPU, and specify settings such as colour and fog. - Many limitations - less low-level control - Some APIs had “high level” concepts, such as sprites PlayStation 1 “PSYQ” SDK OpenGL (fixed function pipeline)
  • 3. Programmable shading pipeline - More control through the use of shaders - Vertex shader: modify vertex positions - Fragment shader: modify output colour - Newer features: Tesselation shaders and geometry shaders - Allows you to add screen-space effects by first rendering scene to texture OpenGL 2.0 shading pipeline
  • 5. Vertex - Wikipedia: “a point where two or more curves, lines, or edges meet” - Usually: A point (and its position, normal, texCoord, etc.) in a triangle ● Position ● Normal ● Texture coordinate ● Tangent / Bitangent
  • 6. Vertex buffer - Buffered vertex data on the GPU - Vertex data is created on the CPU and then uploaded to the video device Vertex layout - Order of the vertex attributes/components (position, normal, texcoord) - Each attribute can have its own buffer (slow) or be on the same buffer - One buffer per attribute: (VVVV) (NNNN) (CCCC) - Blocks in a batch: (VVVVNNNNCCCC) - Interleaved: (VNCVNCVNCVNC) (“stride” = byte offset between attributes)
  • 7. Uniforms / shader constants - OpenGL: “Uniform” ≈ DirectX: “Shader constant” - Per-material data sent to shaders - Vertex data is per vertex - uniforms are per material - Examples: material properties (colour, smoothness, specular reflectiveness), light sources, cross-section plane - In Unity, these are called “properties”, and you can set their value using Material::SetFloat(...) / Material::SetInt(...), etc.
  • 8. Rendering Create vertex data (array of vertices) Create vertex buffer (send vertices to GPU) Bind vertex buffer and index buffer, and draw From Ming3D: https://github.com/mlavik1/Ming3D
  • 9. Problems - Many rendering APIs: OpenGL, DirectX, Vulkan, GNM (PS4), Metal - Each rendering API has its own shader language - GLSL (OpenGL), HLSL (DirectX) - Need to support several rendering APIs and shader languages, and in some cases several versions of them Solution: Make your own shader language and convert it to GLSL, HLSL, etc.. Unity has their own shader language (based on Nvidia’s Cg)
  • 12. Name of shader (and path) Properties (textures and uniforms / shader constants) Contains a texture with name “MainTex”
  • 13. Shader pass (Unity uses different passes for shadow casting, depth, etc) Vertex shader Fragment shader
  • 14. Various features - Math functions - sin(x), cos(x), tan(x) - Standard library functions - lerp(a, b, t) - smoothstep(a, b, t) - clamp(x, a, b) - length(v) - tex2D(texture, texCoord) - http://developer.download.nvidia.com/CgTutorial/cg_tutorial_appendix_e.html - Built-in shader variables - _Time: Time since level load (t/20, t, t*2, t*3) - https://docs.unity3d.com/Manual/SL-ShaderPrograms.html
  • 16. Shader semantic - MSDN: “A semantic is a string attached to a shader input or output that conveys information about the intended use of a parameter” - Unity needs to know which attributes in the vertex layout are position, normal, etc. (so it can buffer your mesh correctly) - Some rendering APIs require semantics on all input/output data - Vertex input/output: POSITION, TEXCOORD0, TEXCOORD1, NORMAL, COLOR, TANGENT - Fragment shader output: SV_Target - Multiple render targets: SV_Target0, SV_Target1,..
  • 17. Shader properties - Syntax: _PropertyName(“visual name”, type) = value - Types: - “int” - “Vector” - “Color” - “2D” (texture)
  • 18. Including - You can split shader into several files, by putting common function in a .cginc-file - Unity’s standard shader functions are in: - UnityStandardCore.cginc - UnityStandardCoreForward.cginc - UnityStandardShadow.cginc - UnityStandardMeta.cginc Unity shader includes location: Program FilesUnityEditorDataCGIncludes
  • 19. Multicompiler shader program variants - If you want to enable/disable a set of features in a shader, without passing a boolean uniform and checking its value, you can use multicompile program variants 1. Add this after CGPROGRAM: #pragma multi_compile __ YOUR_DEFINE 2. Use #if YOU_DEFINE_HERE to conditionally enable/disable feature 3. Enable feature with: material.EnableKeyword("YOUR_DEFINE"); 4. Disable feature with: material.DisableKeyword("YOUR_DEFINE"); This will create two versions of the shader: One where the the “YOUR_DEFINE” preprocessor definition is defined, and one where it is not. The #if-check is done at compile time (or when shader is converted) Use shader_feature for multicompile definitions that will only be set in the material
  • 20. AmbientOcclusion.shader AmbientOcclusion.cginc AmbientOcclusion.cs Example from my addition to Unity’s SSAO postprocessing effect
  • 21. Debugging - Unity has RenderDoc integrations - RenderDoc allows you to capture a frame, see all render API calls, visualise input/output if each shader pass, visualise textures, inspect material properties (uniforms / shader constants) and much more. - See: https://docs.unity3d.com/Manual/RenderDocIntegration.html - Alternatively use the Visual Studio shader debugger, which allows you to add breakpoints, step through code and more: https://docs.unity3d.com/Manual/SL-DebuggingD3D11ShadersWithVS.ht ml
  • 22. 1. Download RenderDoc: https://renderdoc.org/builds 2. Include #pragma enable_d3d11_debug_symbols in your shader’s CGPROGRAM block, if you want to see property names and more. 3. Right-click on “Game” tab and load RenderDoc 4. While in-game, capture a frame