SlideShare a Scribd company logo
1 of 22
Download to read offline
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

What's hot

Best Practices for Shader Graph
Best Practices for Shader GraphBest Practices for Shader Graph
Best Practices for Shader GraphUnity Technologies
 
A Bit More Deferred Cry Engine3
A Bit More Deferred   Cry Engine3A Bit More Deferred   Cry Engine3
A Bit More Deferred Cry Engine3guest11b095
 
스크린 스페이스 데칼에 대해 자세히 알아보자(워햄머 40,000: 스페이스 마린)
스크린 스페이스 데칼에 대해 자세히 알아보자(워햄머 40,000: 스페이스 마린)스크린 스페이스 데칼에 대해 자세히 알아보자(워햄머 40,000: 스페이스 마린)
스크린 스페이스 데칼에 대해 자세히 알아보자(워햄머 40,000: 스페이스 마린)포프 김
 
NVIDIA OpenGL in 2016
NVIDIA OpenGL in 2016NVIDIA OpenGL in 2016
NVIDIA OpenGL in 2016Mark Kilgard
 
Screen Space Decals in Warhammer 40,000: Space Marine
Screen Space Decals in Warhammer 40,000: Space MarineScreen Space Decals in Warhammer 40,000: Space Marine
Screen Space Decals in Warhammer 40,000: Space MarinePope Kim
 
Moving Frostbite to Physically Based Rendering
Moving Frostbite to Physically Based RenderingMoving Frostbite to Physically Based Rendering
Moving Frostbite to Physically Based RenderingElectronic Arts / DICE
 
Brdf기반 사전정의 스킨 셰이더
Brdf기반 사전정의 스킨 셰이더Brdf기반 사전정의 스킨 셰이더
Brdf기반 사전정의 스킨 셰이더동석 김
 
Filmic Tonemapping for Real-time Rendering - Siggraph 2010 Color Course
Filmic Tonemapping for Real-time Rendering - Siggraph 2010 Color CourseFilmic Tonemapping for Real-time Rendering - Siggraph 2010 Color Course
Filmic Tonemapping for Real-time Rendering - Siggraph 2010 Color Coursehpduiker
 
NVIDIA's OpenGL Functionality
NVIDIA's OpenGL FunctionalityNVIDIA's OpenGL Functionality
NVIDIA's OpenGL FunctionalityMark Kilgard
 
Lighting Shading by John Hable
Lighting Shading by John HableLighting Shading by John Hable
Lighting Shading by John HableNaughty Dog
 
Colin Barre-Brisebois - GDC 2011 - Approximating Translucency for a Fast, Che...
Colin Barre-Brisebois - GDC 2011 - Approximating Translucency for a Fast, Che...Colin Barre-Brisebois - GDC 2011 - Approximating Translucency for a Fast, Che...
Colin Barre-Brisebois - GDC 2011 - Approximating Translucency for a Fast, Che...Colin Barré-Brisebois
 
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술Ki Hyunwoo
 
Abalanche - Unity Shader Graph #1: Shader & PBR Materials
Abalanche - Unity Shader Graph #1: Shader & PBR MaterialsAbalanche - Unity Shader Graph #1: Shader & PBR Materials
Abalanche - Unity Shader Graph #1: Shader & PBR MaterialsPhuong Hoang Vu
 
Oit And Indirect Illumination Using Dx11 Linked Lists
Oit And Indirect Illumination Using Dx11 Linked ListsOit And Indirect Illumination Using Dx11 Linked Lists
Oit And Indirect Illumination Using Dx11 Linked ListsHolger Gruen
 
High Dynamic Range color grading and display in Frostbite
High Dynamic Range color grading and display in FrostbiteHigh Dynamic Range color grading and display in Frostbite
High Dynamic Range color grading and display in FrostbiteElectronic Arts / DICE
 
Star Ocean 4 - Flexible Shader Managment and Post-processing
Star Ocean 4 - Flexible Shader Managment and Post-processingStar Ocean 4 - Flexible Shader Managment and Post-processing
Star Ocean 4 - Flexible Shader Managment and Post-processingumsl snfrzb
 
아티스트에게 사랑받는 3DS Max 우버쉐이더
아티스트에게 사랑받는 3DS Max 우버쉐이더아티스트에게 사랑받는 3DS Max 우버쉐이더
아티스트에게 사랑받는 3DS Max 우버쉐이더포프 김
 
OpenGL 3.2 and More
OpenGL 3.2 and MoreOpenGL 3.2 and More
OpenGL 3.2 and MoreMark Kilgard
 

What's hot (20)

Best Practices for Shader Graph
Best Practices for Shader GraphBest Practices for Shader Graph
Best Practices for Shader Graph
 
A Bit More Deferred Cry Engine3
A Bit More Deferred   Cry Engine3A Bit More Deferred   Cry Engine3
A Bit More Deferred Cry Engine3
 
스크린 스페이스 데칼에 대해 자세히 알아보자(워햄머 40,000: 스페이스 마린)
스크린 스페이스 데칼에 대해 자세히 알아보자(워햄머 40,000: 스페이스 마린)스크린 스페이스 데칼에 대해 자세히 알아보자(워햄머 40,000: 스페이스 마린)
스크린 스페이스 데칼에 대해 자세히 알아보자(워햄머 40,000: 스페이스 마린)
 
NVIDIA OpenGL in 2016
NVIDIA OpenGL in 2016NVIDIA OpenGL in 2016
NVIDIA OpenGL in 2016
 
Screen Space Decals in Warhammer 40,000: Space Marine
Screen Space Decals in Warhammer 40,000: Space MarineScreen Space Decals in Warhammer 40,000: Space Marine
Screen Space Decals in Warhammer 40,000: Space Marine
 
Moving Frostbite to Physically Based Rendering
Moving Frostbite to Physically Based RenderingMoving Frostbite to Physically Based Rendering
Moving Frostbite to Physically Based Rendering
 
Brdf기반 사전정의 스킨 셰이더
Brdf기반 사전정의 스킨 셰이더Brdf기반 사전정의 스킨 셰이더
Brdf기반 사전정의 스킨 셰이더
 
Filmic Tonemapping for Real-time Rendering - Siggraph 2010 Color Course
Filmic Tonemapping for Real-time Rendering - Siggraph 2010 Color CourseFilmic Tonemapping for Real-time Rendering - Siggraph 2010 Color Course
Filmic Tonemapping for Real-time Rendering - Siggraph 2010 Color Course
 
NVIDIA's OpenGL Functionality
NVIDIA's OpenGL FunctionalityNVIDIA's OpenGL Functionality
NVIDIA's OpenGL Functionality
 
Lighting Shading by John Hable
Lighting Shading by John HableLighting Shading by John Hable
Lighting Shading by John Hable
 
Colin Barre-Brisebois - GDC 2011 - Approximating Translucency for a Fast, Che...
Colin Barre-Brisebois - GDC 2011 - Approximating Translucency for a Fast, Che...Colin Barre-Brisebois - GDC 2011 - Approximating Translucency for a Fast, Che...
Colin Barre-Brisebois - GDC 2011 - Approximating Translucency for a Fast, Che...
 
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술
NDC2016 프로젝트 A1의 AAA급 캐릭터 렌더링 기술
 
Abalanche - Unity Shader Graph #1: Shader & PBR Materials
Abalanche - Unity Shader Graph #1: Shader & PBR MaterialsAbalanche - Unity Shader Graph #1: Shader & PBR Materials
Abalanche - Unity Shader Graph #1: Shader & PBR Materials
 
Oit And Indirect Illumination Using Dx11 Linked Lists
Oit And Indirect Illumination Using Dx11 Linked ListsOit And Indirect Illumination Using Dx11 Linked Lists
Oit And Indirect Illumination Using Dx11 Linked Lists
 
Motion blur
Motion blurMotion blur
Motion blur
 
High Dynamic Range color grading and display in Frostbite
High Dynamic Range color grading and display in FrostbiteHigh Dynamic Range color grading and display in Frostbite
High Dynamic Range color grading and display in Frostbite
 
Star Ocean 4 - Flexible Shader Managment and Post-processing
Star Ocean 4 - Flexible Shader Managment and Post-processingStar Ocean 4 - Flexible Shader Managment and Post-processing
Star Ocean 4 - Flexible Shader Managment and Post-processing
 
아티스트에게 사랑받는 3DS Max 우버쉐이더
아티스트에게 사랑받는 3DS Max 우버쉐이더아티스트에게 사랑받는 3DS Max 우버쉐이더
아티스트에게 사랑받는 3DS Max 우버쉐이더
 
High dynamic range
High dynamic rangeHigh dynamic range
High dynamic range
 
OpenGL 3.2 and More
OpenGL 3.2 and MoreOpenGL 3.2 and More
OpenGL 3.2 and More
 

Similar to Shaders in Unity

Hardware Shaders
Hardware ShadersHardware Shaders
Hardware Shadersgueste52f1b
 
Optimizing unity games (Google IO 2014)
Optimizing unity games (Google IO 2014)Optimizing unity games (Google IO 2014)
Optimizing unity games (Google IO 2014)Alexander Dolbilov
 
Advanced Graphics Workshop - GFX2011
Advanced Graphics Workshop - GFX2011Advanced Graphics Workshop - GFX2011
Advanced Graphics Workshop - GFX2011Prabindh Sundareson
 
3 boyd direct3_d12 (1)
3 boyd direct3_d12 (1)3 boyd direct3_d12 (1)
3 boyd direct3_d12 (1)mistercteam
 
JIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdf
JIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdfJIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdf
JIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdfSamiraKids
 
Clean architecture for shaders unite2019
Clean architecture for shaders unite2019Clean architecture for shaders unite2019
Clean architecture for shaders unite2019Abhilash Majumder
 
OpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI PlatformsOpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI PlatformsPrabindh Sundareson
 
Minko - Targeting Flash/Stage3D with C++ and GLSL
Minko - Targeting Flash/Stage3D with C++ and GLSLMinko - Targeting Flash/Stage3D with C++ and GLSL
Minko - Targeting Flash/Stage3D with C++ and GLSLMinko3D
 
Gdc 14 bringing unreal engine 4 to open_gl
Gdc 14 bringing unreal engine 4 to open_glGdc 14 bringing unreal engine 4 to open_gl
Gdc 14 bringing unreal engine 4 to open_glchangehee lee
 
BitSquid Tech: Benefits of a data-driven renderer
BitSquid Tech: Benefits of a data-driven rendererBitSquid Tech: Benefits of a data-driven renderer
BitSquid Tech: Benefits of a data-driven renderertobias_persson
 
02 direct3 d_pipeline
02 direct3 d_pipeline02 direct3 d_pipeline
02 direct3 d_pipelineGirish Ghate
 
Graphics software
Graphics softwareGraphics software
Graphics softwareMohd Arif
 
Unity advanced computer graphics week 02
Unity advanced computer graphics week 02Unity advanced computer graphics week 02
Unity advanced computer graphics week 02Tri Thanh
 
[03 1][gpu용 개발자 도구 - parallel nsight 및 axe] miller axe
[03 1][gpu용 개발자 도구 - parallel nsight 및 axe] miller axe[03 1][gpu용 개발자 도구 - parallel nsight 및 axe] miller axe
[03 1][gpu용 개발자 도구 - parallel nsight 및 axe] miller axelaparuma
 
Minko stage3d 20130222
Minko stage3d 20130222Minko stage3d 20130222
Minko stage3d 20130222Minko3D
 
The next generation of GPU APIs for Game Engines
The next generation of GPU APIs for Game EnginesThe next generation of GPU APIs for Game Engines
The next generation of GPU APIs for Game EnginesPooya Eimandar
 

Similar to Shaders in Unity (20)

Hardware Shaders
Hardware ShadersHardware Shaders
Hardware Shaders
 
NvFX GTC 2013
NvFX GTC 2013NvFX GTC 2013
NvFX GTC 2013
 
Optimizing unity games (Google IO 2014)
Optimizing unity games (Google IO 2014)Optimizing unity games (Google IO 2014)
Optimizing unity games (Google IO 2014)
 
Advanced Graphics Workshop - GFX2011
Advanced Graphics Workshop - GFX2011Advanced Graphics Workshop - GFX2011
Advanced Graphics Workshop - GFX2011
 
3 boyd direct3_d12 (1)
3 boyd direct3_d12 (1)3 boyd direct3_d12 (1)
3 boyd direct3_d12 (1)
 
JIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdf
JIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdfJIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdf
JIT Spraying Never Dies - Bypass CFG By Leveraging WARP Shader JIT Spraying.pdf
 
Chapter-3.pdf
Chapter-3.pdfChapter-3.pdf
Chapter-3.pdf
 
Clean architecture for shaders unite2019
Clean architecture for shaders unite2019Clean architecture for shaders unite2019
Clean architecture for shaders unite2019
 
Android native gl
Android native glAndroid native gl
Android native gl
 
OpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI PlatformsOpenGL ES based UI Development on TI Platforms
OpenGL ES based UI Development on TI Platforms
 
Minko - Targeting Flash/Stage3D with C++ and GLSL
Minko - Targeting Flash/Stage3D with C++ and GLSLMinko - Targeting Flash/Stage3D with C++ and GLSL
Minko - Targeting Flash/Stage3D with C++ and GLSL
 
Gdc 14 bringing unreal engine 4 to open_gl
Gdc 14 bringing unreal engine 4 to open_glGdc 14 bringing unreal engine 4 to open_gl
Gdc 14 bringing unreal engine 4 to open_gl
 
What is OpenGL ?
What is OpenGL ?What is OpenGL ?
What is OpenGL ?
 
BitSquid Tech: Benefits of a data-driven renderer
BitSquid Tech: Benefits of a data-driven rendererBitSquid Tech: Benefits of a data-driven renderer
BitSquid Tech: Benefits of a data-driven renderer
 
02 direct3 d_pipeline
02 direct3 d_pipeline02 direct3 d_pipeline
02 direct3 d_pipeline
 
Graphics software
Graphics softwareGraphics software
Graphics software
 
Unity advanced computer graphics week 02
Unity advanced computer graphics week 02Unity advanced computer graphics week 02
Unity advanced computer graphics week 02
 
[03 1][gpu용 개발자 도구 - parallel nsight 및 axe] miller axe
[03 1][gpu용 개발자 도구 - parallel nsight 및 axe] miller axe[03 1][gpu용 개발자 도구 - parallel nsight 및 axe] miller axe
[03 1][gpu용 개발자 도구 - parallel nsight 및 axe] miller axe
 
Minko stage3d 20130222
Minko stage3d 20130222Minko stage3d 20130222
Minko stage3d 20130222
 
The next generation of GPU APIs for Game Engines
The next generation of GPU APIs for Game EnginesThe next generation of GPU APIs for Game Engines
The next generation of GPU APIs for Game Engines
 

Recently uploaded

Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1DianaGray10
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum ComputingGDSC PJATK
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintMahmoud Rabie
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.francesco barbera
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServiceRenan Moreira de Oliveira
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...Aggregage
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 

Recently uploaded (20)

Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1Secure your environment with UiPath and CyberArk technologies - Session 1
Secure your environment with UiPath and CyberArk technologies - Session 1
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum Computing
 
Empowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership BlueprintEmpowering Africa's Next Generation: The AI Leadership Blueprint
Empowering Africa's Next Generation: The AI Leadership Blueprint
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
 
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
The Data Metaverse: Unpacking the Roles, Use Cases, and Tech Trends in Data a...
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 

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