Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.

Unity Shader System Introduction

A brief introduction to unity shader programming.

  • Identifiez-vous pour voir les commentaires

Unity Shader System Introduction

  1. 1. Unity Shader System李 得 雨 (Dustin Lee)Unity Technologies KoreaProduct Evangelist
  2. 2. Session IntroductionPart 1 : Unity Shader StructurePart 2 : Unity Rendering PipelinePart 3 : Unity Shader ProgrammingSession Introduction
  3. 3. Unity Shader Structure
  4. 4. Unity Multi Platform ArchitectureUnity Shader StructureCPU GPUUser Script(C#, UnityScript )Virtual MachineUnity EngineUser Shader Script(ShaderLab)Script ParserNative Shader
  5. 5. Shader Script ( Shader Lab )Unity Shader Structure• Abstract shader script layer for multiplatform system• Multi-Device• Supports old mobile hardwares. ( DX 7/8 )• Support modern mobile hardwares ( DX9, Shader Model 2 )• Support PC and Console hardwares (Shader Model 3 )• Supports Extreme PC hardware ( DX11, Shader Model 5 )• Multi-Library• OpenGL , OpenGL E/S , DirectX• Multi-Language• GLSL , Cg, HLSL
  6. 6. Shader Lab SyntaxUnity Shader StructureSimple Custom Shader ExampleShader "Custom/Simple" {Properties{_MainTex ("Base (RGB)", 2D) = "white" {}}SubShader{Tags { "Queue"="Geometry+1" }Pass{SetTexture [_MainTex] { combine texture }}}FallBack "Diffuse"}
  7. 7. Shader Lab Syntax ( Shader )Unity Shader Structure• Defines shader name• “/” seperates drop down levelShader "Custom/Simple"
  8. 8. Shader Lab Syntax ( Properties )Unity Shader Structure• Define list of parameters for artist.• Float textbox• Float Range Slides• Vector4 textboxes• Color Picker• 2D Texture ( POT )• 2D Texture ( NPOT )• Cube Texture
  9. 9. Shader Lab Syntax ( SubShader )Unity Shader Structure• An unity shader is designed to supportmulti devices with each subshadercode• Top-down priority order• If all subshaders fail, unity runsfallback shaderSubShader{// First Priority Shader Code( Designed for high-level PC )}SubShader{// Second Priority Shader Code( Designed for mid-level PC )}SubShader{// Third Priority Shader Code( Designed for low-level PC )}// Alternative Shader CodeFallback “VertexLit”
  10. 10. Unity Rendering PipelineUnity Shader StructureGame ObjectGeometryHigh QualitySubShaderLow QualitySubShaderApplyUnity Shader
  11. 11. SubShader Format ( Tag )Unity Shader StructureTagPassSubShader• SubShader Tag Keyword• how and when shader runs?• When is very important!• Background = 1000• Geometry = 2000• AlphaTest = 2450• Transparent = 3000• Overlay = 4000
  12. 12. Unity Rendering PipelineUnity Shader StructureSubShaderTags { "Queue"="Geometry+1" }Unity renders this game object after rendering ofall other opaque game objects.
  13. 13. SubShader Format ( Pass )Unity Shader Structure• SubShader Pass Keyword• Performs rendering of the geometry• Subshader can have multiple passes.• Pass consists of three divisions• Pass Tag• Render State• Shader CodePassRender StateShader Code SnippetCullingDepthTestAlphaTestBlendingPass Tag
  14. 14. Unity Rendering PipelineUnity Shader StructureGame ObjectFor the actual rendering operation,unity engine provides three rendering methods.
  15. 15. Unity Rendering Pipeline
  16. 16. Unity Rendering PipelineUnity Rendering Pipeline• Vertex Lit• Forward• Deferred Lighting
  17. 17. Vertex Lit PipelineUnity Rendering Pipeline• Designed for old hardware.• DirectX 7 / 8 compatible• Final pixel is calculated by interpolation between vertices.• Pros• Simple and Fast• No overhead in CPU side• Useful to lightmapping in mobile• Cons• Cookie, Lightprobe, Shadow are not available.• Number of light has limit.• Can’t express per-pixel expression. ex) normal mapping
  18. 18. Vertex Lit Pipeline PassUnity Rendering Pipeline• There are 3 options for vertex lit pipeline• 1 pass is chosen by unity setting or hardware detection.• Vertex Pass• Just simple vertex lit mode.• No lightmap support.• VertexLM Pass• For old smartphone.• Encodes lightmap by Double LDR .• VertexLMRGBM Pass• For modern smartphone.• Encodes lightmap by RGBM.
  19. 19. Forward PipelineUnity Rendering PipelineVertex Lit Forward
  20. 20. Forward PipelineUnity Rendering Pipeline• Common rendering pipeline• DirectX 9• Per-pixel calculation• Pros• Lightprobe, cookie, shadow are available.• Can render object by independent lighting model.• Cons• Lighting computation increases linearly by number of lights• Only directional light support shadow.• Unity supports additional shader keyword-> fullforwardshadows
  21. 21. Light Setting in Forward PipelineUnity Rendering Pipeline• Render Mode Setting in Light component• Important Light• The largest intensity directional light• Uses in per-pixel calculation• Pixel Light Count• Not Important Light• Next 4 lights use for per-vertex calculation.• Rest lights are approximated by SH (Spherical Harmonics)
  22. 22. Forward Pipeline PassUnity Rendering Pipeline• Rendering is performed by 2 passes• ForwardBase• A ( Most important light )• D~H• ForwardAdd• B, C, D ( Important lights )
  23. 23. Forward Pipeline PassUnity Rendering PipelineForwardBaseForwardAdd_WorldSpaceLightPos0unity_4LightPosX0/Y0/Z0unity_LightColor[4]_WorldSpaceLightPos0• 4 Per Pixel Count = 4 Draw Calls per object1 ForwardBase ( A, D, E, F, G, H ) + 3 ForwardAdd ( B, C, D )
  24. 24. Deferred Lighting PipelineUnity Rendering Pipeline• Modern rendering pipeline• Pros• No number of light limit.• Useful to complex scene rendering at once.• Cons• Mobile doesn’t support this currently.• Supports only Blinn-Phong lighting model.• Does’t support transparent object.-> Only forward supports transparent objects.
  25. 25. Deferred Lighting Pipeline PassUnity Rendering PipelineIn Unity, three rendering passes happen in deferred lighting pipeline.PrePassBase PrePassLighting PrePassFinalRenderTexture Main _CameraNormalsTexture_CameraDepthTexture_LightBufferG Buffer
  26. 26. Shader Programming
  27. 27. Unity Shader ProgramingUnity Shader Programming• Fixed Function Program• Vertex / Fragment Program• Surface Shader Program
  28. 28. Fixed Function ProgramUnity Shader Programming• Matches vertex lit rendering pipeline• Shader model 1.x• Provides special keywords for rendering operation.Pass {Material {Diffuse [_Color]Ambient [_Color]Shininess [_Shininess]Specular [_SpecColor]Emission [_Emission]}Lighting OnSeparateSpecular OnSetTexture [_MainTex] {combine previous * texture}SetTexture [_BlendTex] {combine previous lerp (texture) texture}}
  29. 29. Vertex / Fragment ProgramUnity Shader Programming• Common shader programming• Unity provides keywords for coding snippet area-> CGPROGRAM , GLSLPROGRAMPass {CGPROGRAM#pragma vertex vert#pragma fragment fragfloat4 vert(float4 inVert : POSITION) : SV_POSITION{float4 outVert = mul (UNITY_MATRIX_MVP, inVert);return outVert;}half4 frag(float4 i) : COLOR{return half4(1.0, 0.0, 0.0, 1.0);}ENDCG}Native Code
  30. 30. Cg vs GLSLUnity Shader ProgrammingGLSL CodeCg CodeCGPROGRAM#pragma vertex vert#pragma fragment frag#include "UnityCG.cginc"struct v2f {float4 pos : SV_POSITION;float3 color : COLOR0;};v2f vert (appdata_base v) {v2f o;o.pos = mul (UNITY_MATRIX_MVP,v.vertex);o.color = v.normal * 0.5 + 0.5;return o;}half4 frag (v2f i) : COLOR {return half4 (i.color, 1);}ENDCGGLSLPROGRAMvarying vec4 position;#ifdef VERTEXvoid main(){position = gl_Normal * 0.5 + vec4(0.5, 0.5, 0.5, 0.0);gl_Position = gl_ModelViewProjectionMatrix* gl_Vertex;}#endif#ifdef FRAGMENTvoid main(){gl_FragColor = position;}#endifENDGLSLResult
  31. 31. HLSL to GLSL Shader ParserUnity Shader Programming• If you use Cg, unity converts to all platform shader codes automatically.Cg/HLSLCode SnippetHLSLShader CodeFullHLSL CodeCovertedGLSL CodeOptimized GLSLShader CodeFinal GLSLShader CodeFull Shader Code PreprocessorProcessingHLSL to GLSL Converter1st Optimizationhttps://github.com/aras-p/glsl-optimizer2nd Optimizationhttps://github.com/aras-p/hlsl2glslfork
  32. 32. Problem in Vertex/Fragment ProgramUnity Shader Programming• What happens if we try to program rendering code?• Lightmapping Setting• Type of Light ( Directional, Point, Spot )• Unity provides various predefined processor. but this make complex.#ifdef LIGHTMAP_OFFfloat3 shlight = ShadeSH9 (float4(worldN,1.0));o.vlight = shlight;#ifdef VERTEXLIGHT_ONfloat3 worldPos = mul(_Object2World, v.vertex).xyz;o.vlight += Shade4PointLights (unity_4LightPosX0, unity_4LightPosY0, unity_4LightPosZ0,unity_LightColor[0].rgb, unity_LightColor[1].rgb, unity_LightColor[2].rgb,unity_LightColor[3].rgb, unity_4LightAtten0, worldPos, worldN );#endif // VERTEXLIGHT_ON#endif // LIGHTMAP_OFFRequires 132 lines of code for general multi-platform diffuse shader
  33. 33. Surface Shader ProgramUnity Shader Programming• Simplified version of vertex/fragment program by unity way.• Automatically converts vertex/fragment code for various situations.CGPROGRAM#pragma surface surf Lambertsampler2D _MainTex;struct Input {float2 uv_MainTex;};void surf (Input IN, inout SurfaceOutput o) {half4 c = tex2D (_MainTex, IN.uv_MainTex);o.Albedo = c.rgb;o.Alpha = c.a;}ENDCG#ifdef LIGHTMAP_OFFfloat3 shlight = ShadeSH9 (float4(worldN,1.0));o.vlight = shlight;#ifdef VERTEXLIGHT_ONfloat3 worldPos = mul(_Object2World, v.vertex).xyz;o.vlight += Shade4PointLights (unity_4LightPosX0, unity_4LightPosY0,unity_4LightPosZ0,unity_LightColor[0].rgb, unity_LightColor[1].rgb,unity_LightColor[2].rgb,unity_LightColor[3].rgb, unity_4LightAtten0, worldPos,worldN );#endif // VERTEXLIGHT_ON#endif // LIGHTMAP_OFF132 lines of code12 lines of code
  34. 34. Surface Shader ProgramUnity Shader ProgrammingYourSurface ShaderProgramVertex/FragmentProgram
  35. 35. Surface Shader Program StructureUnity Shader Programming• Shader Programming = Surface Code + Light CodeSet Function forSurface SettingUnity Lighting ModelOrCustom Lighting Model#pragma surface surf LambertSurface Program
  36. 36. Surface Shader Program 1st StepUnity Shader Programming• Set proper value to each member of structure.• Similar with graphical shader programming interfacestruct SurfaceOutput{fixed3 Albedo;fixed3 Normal;fixed3 Emission;half Specular;fixed Gloss;fixed Alpha;};
  37. 37. Surface Shader Program 2nd StepUnity Shader ProgrammingLambert BlinnPhong RampUnity PredefinedLighting Mode( Lighting.cginc )CustomLighting Modelhalf4 LightingRamp (SurfaceOutput s, half3lightDir, half atten) {half NdotL = dot (s.Normal, lightDir);half diff = NdotL * 0.5 + 0.5;half3 ramp = tex2D (_Ramp,float2(diff)).rgb;half4 c;c.rgb = s.Albedo * _LightColor0.rgb *ramp * (atten * 2);c.a = s.Alpha;return c;}_Ramp Texture
  38. 38. Surface Shader Program FinalUnity Shader Programming#pragma debug• Unity generates vertex / fragment shader program code
  39. 39. LightMode TagUnity Shader ProgrammingSurface generates shader code for each lightmode automatically.ForwardBaseForwardAddPass {Tags { “LightMode"=“ForwardBase" }…• ForwardBase• Most important light• Not important light• ForwardAdd• Other Important lights
  40. 40. LightMode HackUnity Shader Programming• No Lightmap• No ForwardAdd LightMode defined4 important lights passes into ForwardBase passConditionDemo1 Directional + 4 Important Point Lights
  41. 41. ComparisonUnity Shader ProgrammingCommon Shader5 DrawcallsForwardBase Only Shader1 Drawcall
  42. 42. Shader KeywordsUnity Shader ProgrammingUnity classifies shaders based on keywords for multi-platforms and multi-environmentsPredefined Keywords• DIRECTIONAL , POINT , SPOT• LIGHTMAP_(ON/OFF), DIRLIGHTMAP_(ON/OFF), VERTLIGHT_(ON/OFF)• SHADOW_(ON/OFF), POINT_COOKIE, DIRECTIONAL_COOKIE …
  43. 43. User Defined KeywordUnity Shader ProgrammingCGPROGRAM#pragma multi_compile MAKE_REDMAKE_NOT_RED…..void surf (Input IN, inout SurfaceOutput o) {#ifdef MAKE_REDhalf4 c = half4(1,0,0,1);#elsehalf4 c = half4(0,1,0,1);#endifo.Albedo = c.rgb;o.Alpha = c.a;}ENDCGShader.EnableKeyword(“MAKE_RED”);#pragma multi_compileDemo
  44. 44. Thank you!Email : dustin@unity3d.comFacebook : MrDustinLee

×