浏览代码

Update files to match unity 2017.3

/stochastic_alpha_test
Sebastien Lagarde 7 年前
当前提交
7ef41ebc
共有 76 个文件被更改,包括 5084 次插入9 次删除
  1. 9
      ScriptableRenderPipeline/LightweightPipeline/Editor.meta
  2. 12
      ScriptableRenderPipeline/LightweightPipeline/Editor/LegacyShadersToLightweightPipelineUpgrader.cs.meta
  3. 12
      ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightAssetInspector.cs.meta
  4. 12
      ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightPipelineUpgraders.cs.meta
  5. 53
      ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightShaderHelper.cs
  6. 12
      ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightShaderHelper.cs.meta
  7. 9
      ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI.meta
  8. 12
      ScriptableRenderPipeline/LightweightPipeline/Editor/StandardToLightweightMaterialUpgrader.cs.meta
  9. 12
      ScriptableRenderPipeline/LightweightPipeline/Editor/UpgradeCommon.cs.meta
  10. 77
      ScriptableRenderPipeline/LightweightPipeline/Editor/LegacyShadersToLightweightPipelineUpgrader.cs
  11. 164
      ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightAssetInspector.cs
  12. 147
      ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightPipelineUpgraders.cs
  13. 12
      ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightUnlitGUI.cs.meta
  14. 437
      ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightStandardGUI.cs
  15. 253
      ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightStandardSimpleLightingGUI.cs
  16. 67
      ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightUnlitGUI.cs
  17. 12
      ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightStandardSimpleLightingGUI.cs.meta
  18. 13
      ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightStandardGUI.cs.meta
  19. 32
      ScriptableRenderPipeline/LightweightPipeline/Editor/StandardToLightweightMaterialUpgrader.cs
  20. 35
      ScriptableRenderPipeline/LightweightPipeline/Editor/UpgradeCommon.cs
  21. 24
      ScriptableRenderPipeline/LightweightPipeline/LightweightConstantBuffer.cs
  22. 13
      ScriptableRenderPipeline/LightweightPipeline/LightweightConstantBuffer.cs.meta
  23. 984
      ScriptableRenderPipeline/LightweightPipeline/LightweightPipeline.cs
  24. 12
      ScriptableRenderPipeline/LightweightPipeline/LightweightPipeline.cs.meta
  25. 37
      ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.asset
  26. 9
      ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.asset.meta
  27. 227
      ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.cs
  28. 12
      ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.cs.meta
  29. 136
      ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineUtils.cs
  30. 13
      ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineUtils.cs.meta
  31. 9
      ScriptableRenderPipeline/LightweightPipeline/Materials.meta
  32. 79
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultETC1.mat
  33. 10
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultETC1.mat.meta
  34. 76
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultLine.mat
  35. 10
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultLine.mat.meta
  36. 10
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultParticle.mat.meta
  37. 87
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultSprite.mat
  38. 9
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultSprite.mat.meta
  39. 86
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultUI.mat
  40. 10
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultUI.mat.meta
  41. 10
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-StandardShader.mat.meta
  42. 77
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultParticle.mat
  43. 94
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-StandardShader.mat
  44. 9
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-StandardSimpleLighting.mat.meta
  45. 79
      ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-StandardSimpleLighting.mat
  46. 9
      ScriptableRenderPipeline/LightweightPipeline/Shaders.meta
  47. 46
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightBlit.shader
  48. 10
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightBlit.shader.meta
  49. 46
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightCopyDepth.shader
  50. 10
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightCopyDepth.shader.meta
  51. 185
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightCore.cginc
  52. 9
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightCore.cginc.meta
  53. 320
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightLighting.cginc
  54. 9
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightLighting.cginc.meta
  55. 226
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPassLit.cginc
  56. 9
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPassLit.cginc.meta
  57. 20
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPassShadow.cginc
  58. 9
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPassShadow.cginc.meta
  59. 93
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightShadows.cginc
  60. 9
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightShadows.cginc.meta
  61. 142
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightStandard.shader
  62. 10
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightStandard.shader.meta
  63. 172
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightStandardSimpleLighting.shader
  64. 9
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightStandardSimpleLighting.shader.meta
  65. 88
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightUnlit.shader
  66. 9
      ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightUnlit.shader.meta
  67. 10
      ScriptableRenderPipeline/LightweightPipeline/Textures.meta
  68. 3
      ScriptableRenderPipeline/LightweightPipeline/Textures/LightweightLightAttenuation.png
  69. 117
      ScriptableRenderPipeline/LightweightPipeline/Textures/LightweightLightAttenuation.png.meta
  70. 9
      ScriptableRenderPipeline/Core/ShadowIncludes.inl.meta

9
ScriptableRenderPipeline/LightweightPipeline/Editor.meta


fileFormatVersion: 2
guid: 316ed34724625cb47b31136769381b57
folderAsset: yes
timeCreated: 1484576996
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

12
ScriptableRenderPipeline/LightweightPipeline/Editor/LegacyShadersToLightweightPipelineUpgrader.cs.meta


fileFormatVersion: 2
guid: 6d97da3faef6c8a46bc29fcc467932b4
timeCreated: 1489573636
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

12
ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightAssetInspector.cs.meta


fileFormatVersion: 2
guid: 81f58d95eba277541b76ad69cb7e3cc7
timeCreated: 1488386204
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

12
ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightPipelineUpgraders.cs.meta


fileFormatVersion: 2
guid: 50feba52dc59c9943b45f22d41904a77
timeCreated: 1490024332
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

53
ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightShaderHelper.cs


using UnityEngine;
using UnityEngine.Rendering;
namespace UnityEditor.Experimental.Rendering.LightweightPipeline
{
public static class LightweightShaderHelper
{
public static void SetMaterialBlendMode(Material material)
{
UpgradeBlendMode mode = (UpgradeBlendMode) material.GetFloat("_Mode");
switch (mode)
{
case UpgradeBlendMode.Opaque:
material.SetOverrideTag("RenderType", "");
material.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
SetKeyword(material, "_ALPHATEST_ON", false);
SetKeyword(material, "_ALPHABLEND_ON", false);
material.renderQueue = -1;
break;
case UpgradeBlendMode.Cutout:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
SetKeyword(material, "_ALPHATEST_ON", true);
SetKeyword(material, "_ALPHABLEND_ON", false);
material.renderQueue = (int) RenderQueue.AlphaTest;
break;
case UpgradeBlendMode.Alpha:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
SetKeyword(material, "_ALPHATEST_ON", false);
SetKeyword(material, "_ALPHABLEND_ON", true);
material.renderQueue = (int) RenderQueue.Transparent;
break;
}
}
public static void SetKeyword(Material material, string keyword, bool enable)
{
if (enable)
material.EnableKeyword(keyword);
else
material.DisableKeyword(keyword);
}
}
}

12
ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightShaderHelper.cs.meta


fileFormatVersion: 2
guid: 673aad8cdc228cf499f7974fb673fa10
timeCreated: 1496821330
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

9
ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI.meta


fileFormatVersion: 2
guid: c8b417f54d2314549995022591d5454f
folderAsset: yes
timeCreated: 1496821940
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

12
ScriptableRenderPipeline/LightweightPipeline/Editor/StandardToLightweightMaterialUpgrader.cs.meta


fileFormatVersion: 2
guid: aec5479bdc442cb4d96b1de3f5e5c818
timeCreated: 1484641774
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

12
ScriptableRenderPipeline/LightweightPipeline/Editor/UpgradeCommon.cs.meta


fileFormatVersion: 2
guid: 8fe5351dffe46e648adb2abd7a167ce7
timeCreated: 1490691870
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

77
ScriptableRenderPipeline/LightweightPipeline/Editor/LegacyShadersToLightweightPipelineUpgrader.cs


using System.Collections.Generic;
namespace UnityEditor.Experimental.Rendering.LightweightPipeline
{
public class LegacyShadersToLightweightPipelineUpgrader
{
//[MenuItem("RenderPipeline/Lightweight Pipeline/Material Upgraders/Upgrade Legacy Materials to LightweightPipeline - Project", false, 3)]
//public static void UpgradeMaterialsToLDProject()
//{
// List<MaterialUpgrader> materialUpgraders = new List<MaterialUpgrader>();
// GetUpgraders(ref materialUpgraders);
// MaterialUpgrader.UpgradeProjectFolder(materialUpgraders, "Upgrade to LD Materials");
//}
//[MenuItem("RenderPipeline/Lightweight Pipeline/Material Upgraders/Upgrade Legacy Materials to LightweightPipeline - Selection", false, 4)]
//public static void UpgradeMaterialsToLDSelection()
//{
// List<MaterialUpgrader> materialUpgraders = new List<MaterialUpgrader>();
// GetUpgraders(ref materialUpgraders);
// MaterialUpgrader.UpgradeSelection(materialUpgraders, "Upgrade to Lightweight Materials");
//}
private static void GetUpgraders(ref List<MaterialUpgrader> materialUpgraders)
{
/////////////////////////////////////
// Legacy Shaders upgraders /
/////////////////////////////////////
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Diffuse", SupportedUpgradeParams.diffuseOpaque));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Specular", SupportedUpgradeParams.specularOpaque));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Bumped Specular", SupportedUpgradeParams.specularOpaque));
// TODO: option to use environment map as texture or use reflection probe
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Reflective/Bumped Diffuse", SupportedUpgradeParams.diffuseCubemap));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Reflective/Bumped Specular", SupportedUpgradeParams.specularOpaque));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Reflective/Diffuse", SupportedUpgradeParams.diffuseCubemap));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Reflective/Specular", SupportedUpgradeParams.specularOpaque));
// Self-Illum upgrader
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Self-Illumin/Diffuse", SupportedUpgradeParams.diffuseOpaque));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Self-Illumin/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Self-Illumin/Specular", SupportedUpgradeParams.specularOpaque));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Self-Illumin/Bumped Specular", SupportedUpgradeParams.specularOpaque));
// Alpha Blended
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Transparent/Diffuse", SupportedUpgradeParams.diffuseAlpha));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Transparent/Specular", SupportedUpgradeParams.specularAlpha));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Transparent/Bumped Diffuse", SupportedUpgradeParams.diffuseAlpha));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Transparent/Bumped Specular", SupportedUpgradeParams.specularAlpha));
// Cutout
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Transparent/Cutout/Diffuse", SupportedUpgradeParams.diffuseAlphaCutout));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Transparent/Cutout/Specular", SupportedUpgradeParams.specularAlphaCutout));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Transparent/Cutout/Bumped Diffuse", SupportedUpgradeParams.diffuseAlphaCutout));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Legacy Shaders/Transparent/Cutout/Bumped Specular", SupportedUpgradeParams.specularAlphaCutout));
/////////////////////////////////////
// Reflective Shader Upgraders /
/////////////////////////////////////
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Reflective/Diffuse Transperant", SupportedUpgradeParams.diffuseCubemapAlpha));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Reflective/Diffuse Reflection Spec", SupportedUpgradeParams.specularCubemap));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Reflective/Diffuse Reflection Spec Transp", SupportedUpgradeParams.specularCubemapAlpha));
/////////////////////////////////////
// Mobile Upgraders /
/////////////////////////////////////
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Mobile/Diffuse", SupportedUpgradeParams.diffuseOpaque));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Mobile/Bumped Specular", SupportedUpgradeParams.specularOpaque));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Mobile/Bumped Specular(1 Directional Light)", SupportedUpgradeParams.specularOpaque));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Mobile/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Mobile/Unlit (Supports Lightmap)", SupportedUpgradeParams.diffuseOpaque));
materialUpgraders.Add(new LegacyBlinnPhongUpgrader("Mobile/VertexLit", SupportedUpgradeParams.specularOpaque));
}
}
}

164
ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightAssetInspector.cs


using UnityEditor;
namespace UnityEngine.Experimental.Rendering.LightweightPipeline
{
[CustomEditor(typeof(LightweightPipelineAsset))]
public class LightweightAssetInspector : Editor
{
internal class Styles
{
public static GUIContent renderingLabel = new GUIContent("Rendering");
public static GUIContent shadowLabel = new GUIContent("Shadows");
public static GUIContent defaults = new GUIContent("Defaults");
public static GUIContent renderScaleLabel = new GUIContent("Render Scale", "Allows game to render at a resolution different than native resolution. UI is always rendered at native resolution.");
public static GUIContent maxAdditionalPixelLightsLabel = new GUIContent("Max Additional Pixel Lights",
"Controls the additional per-pixel lights that run in fragment light loop.");
public static GUIContent enableVertexLightLabel = new GUIContent("Enable Vertex Light",
"If enabled, shades additional lights exceeding maxAdditionalPixelLights per-vertex up to the maximum of 8 lights.");
public static GUIContent enableSoftParticles = new GUIContent("Enable Soft Particles", "By enabled this the pipeline will generate depth texture necessary for SoftParticles");
public static GUIContent shadowType = new GUIContent("Shadow Type",
"Single directional shadow supported. SOFT_SHADOWS applies shadow filtering.");
public static GUIContent shadowNearPlaneOffset = new GUIContent("Shadow Near Plane Offset",
"Offset shadow near plane to account for large triangles being distorted by pancaking");
public static GUIContent shadowDistante = new GUIContent("Shadow Distance", "Max shadow drawing distance");
public static GUIContent shadowAtlasResolution = new GUIContent("Shadow Map Resolution",
"Resolution of shadow map texture. If cascades are enabled all cascades will be packed into this texture resolution.");
public static GUIContent shadowCascades = new GUIContent("Shadow Cascades",
"Number of cascades for directional shadows");
public static GUIContent shadowCascadeSplit = new GUIContent("Shadow Cascade Split",
"Percentages to split shadow volume");
public static GUIContent defaultDiffuseMaterial = new GUIContent("Default Diffuse Material",
"Material to use when creating 3D objects");
public static GUIContent defaultParticleMaterial = new GUIContent("Default Particle Material",
"Material to use when creating Particle Systems");
public static GUIContent defaultLineMaterial = new GUIContent("Default Line Material",
"Material to use when creating Line Renderers");
public static GUIContent defaultSpriteMaterial = new GUIContent("Default Sprite Material",
"Material to use when creating Sprites");
public static GUIContent defaultUIMaterial = new GUIContent("Default UI Material", "Material to use when creating UI Text");
public static GUIContent defaultShader = new GUIContent("Default Shader",
"Shader to use when creating materials");
public static GUIContent msaaContent = new GUIContent("Anti Aliasing (MSAA)", "Controls the global anti aliasing quality. When set to disabled, MSAA will not be performed even if the camera allows it.");
public static GUIContent attenuationTextureLabel = new GUIContent("Attenuation Texture", "Light attenuation falloff texture");
}
private int kMaxSupportedAdditionalPixelLights = 8;
private SerializedProperty m_RenderScale;
private SerializedProperty m_MaxAdditionalPixelLights;
private SerializedProperty m_SupportsVertexLightProp;
private SerializedProperty m_SupportSoftParticlesProp;
private SerializedProperty m_ShadowTypeProp;
private SerializedProperty m_ShadowNearPlaneOffsetProp;
private SerializedProperty m_ShadowDistanceProp;
private SerializedProperty m_ShadowAtlasResolutionProp;
private SerializedProperty m_ShadowCascadesProp;
private SerializedProperty m_ShadowCascade2SplitProp;
private SerializedProperty m_ShadowCascade4SplitProp;
private SerializedProperty m_DefaultDiffuseMaterial;
private SerializedProperty m_DefaultParticleMaterial;
private SerializedProperty m_DefaultLineMaterial;
private SerializedProperty m_DefaultSpriteMaterial;
private SerializedProperty m_DefaultUIMaterial;
private SerializedProperty m_DefaultShader;
private SerializedProperty m_MSAA;
private SerializedProperty m_AttenuationTexture;
void OnEnable()
{
m_RenderScale = serializedObject.FindProperty("m_RenderScale");
m_MaxAdditionalPixelLights = serializedObject.FindProperty("m_MaxAdditionalPixelLights");
m_SupportsVertexLightProp = serializedObject.FindProperty("m_SupportsVertexLight");
m_SupportSoftParticlesProp = serializedObject.FindProperty("m_SupportSoftParticles");
m_ShadowTypeProp = serializedObject.FindProperty("m_ShadowType");
m_ShadowNearPlaneOffsetProp = serializedObject.FindProperty("m_ShadowNearPlaneOffset");
m_ShadowDistanceProp = serializedObject.FindProperty("m_ShadowDistance");
m_ShadowAtlasResolutionProp = serializedObject.FindProperty("m_ShadowAtlasResolution");
m_ShadowCascadesProp = serializedObject.FindProperty("m_ShadowCascades");
m_ShadowCascade2SplitProp = serializedObject.FindProperty("m_Cascade2Split");
m_ShadowCascade4SplitProp = serializedObject.FindProperty("m_Cascade4Split");
m_DefaultDiffuseMaterial = serializedObject.FindProperty("m_DefaultDiffuseMaterial");
m_DefaultParticleMaterial = serializedObject.FindProperty("m_DefaultParticleMaterial");
m_DefaultLineMaterial = serializedObject.FindProperty("m_DefaultLineMaterial");
m_DefaultSpriteMaterial = serializedObject.FindProperty("m_DefaultSpriteMaterial");
m_DefaultUIMaterial = serializedObject.FindProperty("m_DefaultUIMaterial");
m_DefaultShader = serializedObject.FindProperty("m_DefaultShader");
m_MSAA = serializedObject.FindProperty("m_MSAA");
m_AttenuationTexture = serializedObject.FindProperty("m_AttenuationTexture");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.Space();
EditorGUILayout.LabelField(Styles.renderingLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(Styles.renderScaleLabel);
m_RenderScale.floatValue = EditorGUILayout.Slider(m_RenderScale.floatValue, 0.1f, 1.0f);
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
EditorGUILayout.LabelField(Styles.maxAdditionalPixelLightsLabel);
m_MaxAdditionalPixelLights.intValue = EditorGUILayout.IntSlider(m_MaxAdditionalPixelLights.intValue, 0, kMaxSupportedAdditionalPixelLights);
EditorGUILayout.EndHorizontal();
EditorGUILayout.PropertyField(m_SupportsVertexLightProp, Styles.enableVertexLightLabel);
EditorGUILayout.PropertyField(m_SupportSoftParticlesProp, Styles.enableSoftParticles);
EditorGUILayout.PropertyField(m_MSAA, Styles.msaaContent);
EditorGUILayout.PropertyField(m_AttenuationTexture, Styles.attenuationTextureLabel);
EditorGUI.indentLevel--;
EditorGUILayout.Space();
EditorGUILayout.Space();
EditorGUILayout.LabelField(Styles.shadowLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_ShadowTypeProp, Styles.shadowType);
EditorGUILayout.PropertyField(m_ShadowAtlasResolutionProp, Styles.shadowAtlasResolution);
EditorGUILayout.PropertyField(m_ShadowNearPlaneOffsetProp, Styles.shadowNearPlaneOffset);
EditorGUILayout.PropertyField(m_ShadowDistanceProp, Styles.shadowDistante);
EditorGUILayout.PropertyField(m_ShadowCascadesProp, Styles.shadowCascades);
ShadowCascades cascades = (ShadowCascades)m_ShadowCascadesProp.intValue;
if (cascades == ShadowCascades.FOUR_CASCADES)
{
EditorGUILayout.PropertyField(m_ShadowCascade4SplitProp, Styles.shadowCascadeSplit);
}
else if (cascades == ShadowCascades.TWO_CASCADES)
{
EditorGUILayout.PropertyField(m_ShadowCascade2SplitProp, Styles.shadowCascadeSplit);
}
EditorGUI.indentLevel--;
EditorGUILayout.Space();
EditorGUILayout.LabelField(Styles.defaults, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_DefaultDiffuseMaterial, Styles.defaultDiffuseMaterial);
EditorGUILayout.PropertyField(m_DefaultParticleMaterial, Styles.defaultParticleMaterial);
EditorGUILayout.PropertyField(m_DefaultLineMaterial, Styles.defaultLineMaterial);
EditorGUILayout.PropertyField(m_DefaultSpriteMaterial, Styles.defaultSpriteMaterial);
EditorGUILayout.PropertyField(m_DefaultUIMaterial, Styles.defaultUIMaterial);
EditorGUILayout.PropertyField(m_DefaultShader, Styles.defaultShader);
EditorGUI.indentLevel--;
serializedObject.ApplyModifiedProperties();
}
}
}

147
ScriptableRenderPipeline/LightweightPipeline/Editor/LightweightPipelineUpgraders.cs


using UnityEngine;
using UnityEngine.Experimental.Rendering.LightweightPipeline;
namespace UnityEditor.Experimental.Rendering.LightweightPipeline
{
public static class SupportedUpgradeParams
{
static public UpgradeParams diffuseOpaque = new UpgradeParams()
{
blendMode = UpgradeBlendMode.Opaque,
specularSource = SpecularSource.NoSpecular,
glosinessSource = GlossinessSource.BaseAlpha,
};
static public UpgradeParams specularOpaque = new UpgradeParams()
{
blendMode = UpgradeBlendMode.Opaque,
specularSource = SpecularSource.SpecularTextureAndColor,
glosinessSource = GlossinessSource.BaseAlpha,
};
static public UpgradeParams diffuseAlpha = new UpgradeParams()
{
blendMode = UpgradeBlendMode.Alpha,
specularSource = SpecularSource.NoSpecular,
glosinessSource = GlossinessSource.SpecularAlpha,
};
static public UpgradeParams specularAlpha = new UpgradeParams()
{
blendMode = UpgradeBlendMode.Alpha,
specularSource = SpecularSource.SpecularTextureAndColor,
glosinessSource = GlossinessSource.SpecularAlpha,
};
static public UpgradeParams diffuseAlphaCutout = new UpgradeParams()
{
blendMode = UpgradeBlendMode.Cutout,
specularSource = SpecularSource.NoSpecular,
glosinessSource = GlossinessSource.SpecularAlpha,
};
static public UpgradeParams specularAlphaCutout = new UpgradeParams()
{
blendMode = UpgradeBlendMode.Cutout,
specularSource = SpecularSource.SpecularTextureAndColor,
glosinessSource = GlossinessSource.SpecularAlpha,
};
static public UpgradeParams diffuseCubemap = new UpgradeParams()
{
blendMode = UpgradeBlendMode.Opaque,
specularSource = SpecularSource.NoSpecular,
glosinessSource = GlossinessSource.BaseAlpha,
};
static public UpgradeParams specularCubemap = new UpgradeParams()
{
blendMode = UpgradeBlendMode.Opaque,
specularSource = SpecularSource.SpecularTextureAndColor,
glosinessSource = GlossinessSource.BaseAlpha,
};
static public UpgradeParams diffuseCubemapAlpha = new UpgradeParams()
{
blendMode = UpgradeBlendMode.Alpha,
specularSource = SpecularSource.NoSpecular,
glosinessSource = GlossinessSource.BaseAlpha,
};
static public UpgradeParams specularCubemapAlpha = new UpgradeParams()
{
blendMode = UpgradeBlendMode.Alpha,
specularSource = SpecularSource.SpecularTextureAndColor,
glosinessSource = GlossinessSource.BaseAlpha,
};
}
public class LegacyBlinnPhongUpgrader : MaterialUpgrader
{
public LegacyBlinnPhongUpgrader(string oldShaderName, UpgradeParams upgradeParams)
{
RenameShader(oldShaderName, LightweightPipelineAsset.m_SimpleLightShaderPath, UpdateMaterialKeywords);
SetFloat("_Mode", (float)upgradeParams.blendMode);
SetFloat("_SpecSource", (float)upgradeParams.specularSource);
SetFloat("_GlossinessSource", (float)upgradeParams.glosinessSource);
if (oldShaderName.Contains("Legacy Shaders/Self-Illumin"))
{
RenameTexture("_MainTex", "_EmissionMap");
RemoveTexture("_MainTex");
SetColor("_EmissionColor", Color.white);
}
}
public static void UpdateMaterialKeywords(Material material)
{
material.shaderKeywords = null;
LightweightShaderHelper.SetMaterialBlendMode(material);
UpdateMaterialSpecularSource(material);
LightweightShaderHelper.SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap"));
// A material's GI flag internally keeps track of whether emission is enabled at all, it's enabled but has no effect
// or is enabled and may be modified at runtime. This state depends on the values of the current flag and emissive color.
// The fixup routine makes sure that the material is in the correct state if/when changes are made to the mode or color.
MaterialEditor.FixupEmissiveFlag(material);
bool shouldEmissionBeEnabled = (material.globalIlluminationFlags & MaterialGlobalIlluminationFlags.EmissiveIsBlack) == 0;
LightweightShaderHelper.SetKeyword(material, "_EMISSION", shouldEmissionBeEnabled);
}
private static void UpdateMaterialSpecularSource(Material material)
{
SpecularSource specSource = (SpecularSource)material.GetFloat("_SpecSource");
if (specSource == SpecularSource.NoSpecular)
{
LightweightShaderHelper.SetKeyword(material, "_SPECGLOSSMAP", false);
LightweightShaderHelper.SetKeyword(material, "_SPECULAR_COLOR", false);
LightweightShaderHelper.SetKeyword(material, "_GLOSSINESS_FROM_BASE_ALPHA", false);
}
else
{
GlossinessSource glossSource = (GlossinessSource)material.GetFloat("_GlossinessSource");
bool hasGlossMap = material.GetTexture("_SpecGlossMap");
LightweightShaderHelper.SetKeyword(material, "_SPECGLOSSMAP", hasGlossMap);
LightweightShaderHelper.SetKeyword(material, "_SPECULAR_COLOR", !hasGlossMap);
LightweightShaderHelper.SetKeyword(material, "_GLOSSINESS_FROM_BASE_ALPHA", glossSource == GlossinessSource.BaseAlpha);
}
}
}
public class StandardUpgrader : MaterialUpgrader
{
public StandardUpgrader(string oldShaderName)
{
RenameShader(oldShaderName, LightweightPipelineAsset.m_StandardShaderPath);
}
}
public class TerrainUpgrader : MaterialUpgrader
{
public TerrainUpgrader(string oldShaderName)
{
RenameShader(oldShaderName, LightweightPipelineAsset.m_StandardShaderPath);
SetFloat("_Shininess", 1.0f);
}
}
}

12
ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightUnlitGUI.cs.meta


fileFormatVersion: 2
guid: 3be3f3707c329b043b5816855ee127fd
timeCreated: 1487767801
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

437
ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightStandardGUI.cs


using System;
using UnityEditor.Experimental.Rendering.LightweightPipeline;
using UnityEngine;
namespace UnityEditor
{
internal class LightweightStandardGUI : ShaderGUI
{
public enum WorkflowMode : int
{
Specular = 0,
Metallic
}
public enum BlendMode : int
{
Opaque,
Cutout,
Fade, // Old school alpha-blending mode, fresnel does not affect amount of transparency
Transparent // Physically plausible transparency mode, implemented as alpha pre-multiply
}
public enum SmoothnessMapChannel : int
{
SpecularMetallicAlpha,
AlbedoAlpha,
}
private static class Styles
{
public static GUIContent uvSetLabel = new GUIContent("UV Set");
public static GUIContent albedoText = new GUIContent("Albedo", "Albedo (RGB) and Transparency (A)");
public static GUIContent alphaCutoffText = new GUIContent("Alpha Cutoff", "Threshold for alpha cutoff");
public static GUIContent specularMapText = new GUIContent("Specular", "Specular (RGB) and Smoothness (A)");
public static GUIContent metallicMapText = new GUIContent("Metallic", "Metallic (R) and Smoothness (A)");
public static GUIContent smoothnessText = new GUIContent("Smoothness", "Smoothness value");
public static GUIContent smoothnessScaleText = new GUIContent("Smoothness", "Smoothness scale factor");
public static GUIContent smoothnessMapChannelText = new GUIContent("Source", "Smoothness texture and channel");
public static GUIContent highlightsText = new GUIContent("Specular Highlights", "Specular Highlights");
public static GUIContent reflectionsText = new GUIContent("Reflections", "Glossy Reflections");
public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map");
public static GUIContent heightMapText = new GUIContent("Height Map", "Height Map (G)");
public static GUIContent occlusionText = new GUIContent("Occlusion", "Occlusion (G)");
public static GUIContent emissionText = new GUIContent("Color", "Emission (RGB)");
public static GUIContent detailMaskText = new GUIContent("Detail Mask", "Mask for Secondary Maps (A)");
public static GUIContent detailAlbedoText = new GUIContent("Detail Albedo x2", "Albedo (RGB) multiplied by 2");
public static GUIContent detailNormalMapText = new GUIContent("Normal Map", "Normal Map");
public static string primaryMapsText = "Main Maps";
public static string secondaryMapsText = "Secondary Maps";
public static string forwardText = "Forward Rendering Options";
public static string workflowModeText = "Workflow Mode";
public static string renderingMode = "Rendering Mode";
public static string advancedText = "Advanced Options";
public static readonly string[] workflowNames = Enum.GetNames(typeof(WorkflowMode));
public static readonly string[] blendNames = Enum.GetNames(typeof(BlendMode));
public static readonly string[] metallicSmoothnessChannelNames = {"Metallic Alpha", "Albedo Alpha"};
public static readonly string[] specularSmoothnessChannelNames = {"Specular Alpha", "Albedo Alpha"};
}
#pragma warning disable 0414
private MaterialProperty workflowMode = null;
private MaterialProperty blendMode = null;
private MaterialProperty albedoColor = null;
private MaterialProperty albedoMap = null;
private MaterialProperty alphaCutoff = null;
private MaterialProperty smoothness = null;
private MaterialProperty smoothnessScale = null;
private MaterialProperty smoothnessMapChannel = null;
private MaterialProperty metallic = null;
private MaterialProperty specColor = null;
private MaterialProperty metallicGlossMap = null;
private MaterialProperty specGlossMap = null;
private MaterialProperty highlights = null;
private MaterialProperty reflections = null;
private MaterialProperty bumpScale = null;
private MaterialProperty bumpMap = null;
private MaterialProperty occlusionStrength = null;
private MaterialProperty occlusionMap = null;
private MaterialProperty heigtMapScale = null;
private MaterialProperty heightMap = null;
private MaterialProperty emissionColorForRendering = null;
private MaterialProperty emissionMap = null;
private MaterialProperty detailMask = null;
private MaterialProperty detailAlbedoMap = null;
private MaterialProperty detailNormalMapScale = null;
private MaterialProperty detailNormalMap = null;
private MaterialProperty uvSetSecondary = null;
private MaterialEditor m_MaterialEditor;
private const float kMaxfp16 = 65536f; // Clamp to a value that fits into fp16.
private ColorPickerHDRConfig m_ColorPickerHDRConfig = new ColorPickerHDRConfig(0f, kMaxfp16, 1 / kMaxfp16, 3f);
private bool m_FirstTimeApply = true;
#pragma warning restore 0414
public void FindProperties(MaterialProperty[] props)
{
workflowMode = FindProperty("_WorkflowMode", props);
blendMode = FindProperty("_Mode", props);
albedoColor = FindProperty("_Color", props);
albedoMap = FindProperty("_MainTex", props);
alphaCutoff = FindProperty("_Cutoff", props);
smoothness = FindProperty("_Glossiness", props);
smoothnessScale = FindProperty("_GlossMapScale", props, false);
smoothnessMapChannel = FindProperty("_SmoothnessTextureChannel", props, false);
metallic = FindProperty("_Metallic", props);
specColor = FindProperty("_SpecColor", props);
metallicGlossMap = FindProperty("_MetallicGlossMap", props);
specGlossMap = FindProperty("_SpecGlossMap", props);
highlights = FindProperty("_SpecularHighlights", props);
reflections = FindProperty("_GlossyReflections", props);
bumpScale = FindProperty("_BumpScale", props);
bumpMap = FindProperty("_BumpMap", props);
heigtMapScale = FindProperty("_Parallax", props);
heightMap = FindProperty("_ParallaxMap", props);
occlusionStrength = FindProperty("_OcclusionStrength", props);
occlusionMap = FindProperty("_OcclusionMap", props);
emissionColorForRendering = FindProperty("_EmissionColor", props);
emissionMap = FindProperty("_EmissionMap", props);
detailMask = FindProperty("_DetailMask", props);
detailAlbedoMap = FindProperty("_DetailAlbedoMap", props);
detailNormalMapScale = FindProperty("_DetailNormalMapScale", props);
detailNormalMap = FindProperty("_DetailNormalMap", props);
uvSetSecondary = FindProperty("_UVSec", props);
}
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] props)
{
FindProperties(props); // MaterialProperties can be animated so we do not cache them but fetch them every event to ensure animated values are updated correctly
m_MaterialEditor = materialEditor;
Material material = materialEditor.target as Material;
// Make sure that needed setup (ie keywords/renderqueue) are set up if we're switching some existing
// material to a lightweight shader.
if (m_FirstTimeApply)
{
MaterialChanged(material);
m_FirstTimeApply = false;
}
ShaderPropertiesGUI(material);
}
public void ShaderPropertiesGUI(Material material)
{
// Use default labelWidth
EditorGUIUtility.labelWidth = 0f;
// Detect any changes to the material
EditorGUI.BeginChangeCheck();
{
DoPopup(Styles.workflowModeText, workflowMode, Styles.workflowNames);
DoPopup(Styles.renderingMode, blendMode, Styles.blendNames);
// Primary properties
GUILayout.Label(Styles.primaryMapsText, EditorStyles.boldLabel);
DoAlbedoArea(material);
DoMetallicSpecularArea();
DoNormalArea();
m_MaterialEditor.TexturePropertySingleLine(Styles.occlusionText, occlusionMap, occlusionMap.textureValue != null ? occlusionStrength : null);
DoEmissionArea(material);
EditorGUI.BeginChangeCheck();
m_MaterialEditor.TextureScaleOffsetProperty(albedoMap);
if (EditorGUI.EndChangeCheck())
emissionMap.textureScaleAndOffset = albedoMap.textureScaleAndOffset; // Apply the main texture scale and offset to the emission texture as well, for Enlighten's sake
EditorGUILayout.Space();
m_MaterialEditor.ShaderProperty(highlights, Styles.highlightsText);
m_MaterialEditor.ShaderProperty(reflections, Styles.reflectionsText);
}
if (EditorGUI.EndChangeCheck())
{
foreach (var obj in blendMode.targets)
MaterialChanged((Material)obj);
}
EditorGUILayout.Space();
// NB renderqueue editor is not shown on purpose: we want to override it based on blend mode
GUILayout.Label(Styles.advancedText, EditorStyles.boldLabel);
m_MaterialEditor.EnableInstancingField();
m_MaterialEditor.DoubleSidedGIField();
}
public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
{
// _Emission property is lost after assigning Standard shader to the material
// thus transfer it before assigning the new shader
if (material.HasProperty("_Emission"))
{
material.SetColor("_EmissionColor", material.GetColor("_Emission"));
}
base.AssignNewShaderToMaterial(material, oldShader, newShader);
if (oldShader == null || !oldShader.name.Contains("Legacy Shaders/"))
{
SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode"));
return;
}
BlendMode blendMode = BlendMode.Opaque;
if (oldShader.name.Contains("/Transparent/Cutout/"))
{
blendMode = BlendMode.Cutout;
}
else if (oldShader.name.Contains("/Transparent/"))
{
// NOTE: legacy shaders did not provide physically based transparency
// therefore Fade mode
blendMode = BlendMode.Fade;
}
material.SetFloat("_Mode", (float)blendMode);
if (oldShader.name.Equals("Standard (Specular setup)"))
{
material.SetFloat("_WorkflowMode", (float) WorkflowMode.Specular);
Texture texture = material.GetTexture("_SpecGlossMap");
if (texture != null)
material.SetTexture("_MetallicSpecGlossMap", texture);
}
else
{
material.SetFloat("_WorkflowMode", (float) WorkflowMode.Metallic);
Texture texture = material.GetTexture("_MetallicGlossMap");
if (texture != null)
material.SetTexture("_MetallicSpecGlossMap", texture);
}
MaterialChanged(material);
}
private void DoPopup(string label, MaterialProperty property, string[] options)
{
EditorGUI.showMixedValue = property.hasMixedValue;
var mode = property.floatValue;
EditorGUI.BeginChangeCheck();
mode = EditorGUILayout.Popup(label, (int) mode, options);
if (EditorGUI.EndChangeCheck())
{
m_MaterialEditor.RegisterPropertyChangeUndo(label);
property.floatValue = (float)mode;
}
EditorGUI.showMixedValue = false;
}
void DoNormalArea()
{
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMap);
}
void DoAlbedoArea(Material material)
{
m_MaterialEditor.TexturePropertySingleLine(Styles.albedoText, albedoMap, albedoColor);
if (((BlendMode)material.GetFloat("_Mode") == BlendMode.Cutout))
{
m_MaterialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoffText.text, MaterialEditor.kMiniTextureFieldLabelIndentLevel + 1);
}
}
void DoEmissionArea(Material material)
{
// Emission for GI?
if (m_MaterialEditor.EmissionEnabledProperty())
{
bool hadEmissionTexture = emissionMap.textureValue != null;
// Texture and HDR color controls
m_MaterialEditor.TexturePropertyWithHDRColor(Styles.emissionText, emissionMap, emissionColorForRendering, m_ColorPickerHDRConfig, false);
// If texture was assigned and color was black set color to white
float brightness = emissionColorForRendering.colorValue.maxColorComponent;
if (emissionMap.textureValue != null && !hadEmissionTexture && brightness <= 0f)
emissionColorForRendering.colorValue = Color.white;
// LW does not support RealtimeEmissive. We set it to bake emissive and handle the emissive is black right.
material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.BakedEmissive;
if (brightness <= 0f)
material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.EmissiveIsBlack;
}
}
void DoMetallicSpecularArea()
{
string[] metallicSpecSmoothnessChannelName;
bool hasGlossMap = false;
if ((WorkflowMode) workflowMode.floatValue == WorkflowMode.Metallic)
{
hasGlossMap = metallicGlossMap.textureValue != null;
metallicSpecSmoothnessChannelName = Styles.metallicSmoothnessChannelNames;
m_MaterialEditor.TexturePropertySingleLine(Styles.metallicMapText, metallicGlossMap,
hasGlossMap ? null : metallic);
}
else
{
hasGlossMap = specGlossMap.textureValue != null;
metallicSpecSmoothnessChannelName = Styles.specularSmoothnessChannelNames;
m_MaterialEditor.TexturePropertySingleLine(Styles.specularMapText, specGlossMap,
hasGlossMap ? null : specColor);
}
bool showSmoothnessScale = hasGlossMap;
if (smoothnessMapChannel != null)
{
int smoothnessChannel = (int)smoothnessMapChannel.floatValue;
if (smoothnessChannel == (int)SmoothnessMapChannel.AlbedoAlpha)
showSmoothnessScale = true;
}
int indentation = 2; // align with labels of texture properties
m_MaterialEditor.ShaderProperty(showSmoothnessScale ? smoothnessScale : smoothness, showSmoothnessScale ? Styles.smoothnessScaleText : Styles.smoothnessText, indentation);
int prevIndentLevel = EditorGUI.indentLevel;
EditorGUI.indentLevel = 3;
if (smoothnessMapChannel != null)
DoPopup(Styles.smoothnessMapChannelText.text, smoothnessMapChannel, metallicSpecSmoothnessChannelName);
EditorGUI.indentLevel = prevIndentLevel;
}
public static void SetupMaterialWithBlendMode(Material material, BlendMode blendMode)
{
switch (blendMode)
{
case BlendMode.Opaque:
material.SetOverrideTag("RenderType", "");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.DisableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = -1;
break;
case BlendMode.Cutout:
material.SetOverrideTag("RenderType", "TransparentCutout");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
material.SetInt("_ZWrite", 1);
material.EnableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;
break;
case BlendMode.Fade:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHATEST_ON");
material.EnableKeyword("_ALPHABLEND_ON");
material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
break;
case BlendMode.Transparent:
material.SetOverrideTag("RenderType", "Transparent");
material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
material.SetInt("_ZWrite", 0);
material.DisableKeyword("_ALPHATEST_ON");
material.DisableKeyword("_ALPHABLEND_ON");
material.EnableKeyword("_ALPHAPREMULTIPLY_ON");
material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
break;
}
}
static SmoothnessMapChannel GetSmoothnessMapChannel(Material material)
{
int ch = (int)material.GetFloat("_SmoothnessTextureChannel");
if (ch == (int)SmoothnessMapChannel.AlbedoAlpha)
return SmoothnessMapChannel.AlbedoAlpha;
else
return SmoothnessMapChannel.SpecularMetallicAlpha;
}
static void SetMaterialKeywords(Material material)
{
// Note: keywords must be based on Material value not on MaterialProperty due to multi-edit & material animation
// (MaterialProperty value might come from renderer material property block)
bool isSpecularWorkFlow = (WorkflowMode)material.GetFloat("_WorkflowMode") == WorkflowMode.Specular;
bool hasGlossMap = false;
if (isSpecularWorkFlow)
hasGlossMap = material.GetTexture("_SpecGlossMap");
else
hasGlossMap = material.GetTexture("_MetallicGlossMap");
LightweightShaderHelper.SetKeyword(material, "_SPECULAR_SETUP", isSpecularWorkFlow);
LightweightShaderHelper.SetKeyword(material, "_METALLIC_SETUP", !isSpecularWorkFlow);
LightweightShaderHelper.SetKeyword(material, "_METALLICSPECGLOSSMAP", hasGlossMap);
LightweightShaderHelper.SetKeyword(material, "_SPECGLOSSMAP", hasGlossMap && isSpecularWorkFlow);
LightweightShaderHelper.SetKeyword(material, "_METALLICGLOSSMAP", hasGlossMap && !isSpecularWorkFlow);
LightweightShaderHelper.SetKeyword(material, "_NORMALMAP", material.GetTexture("_BumpMap"));
LightweightShaderHelper.SetKeyword(material, "_SPECULARHIGHLIGHTS_OFF", material.GetFloat("_SpecularHighlights") == 0.0f);
LightweightShaderHelper.SetKeyword(material, "_GLOSSYREFLECTIONS_OFF", material.GetFloat("_GlossyReflections") == 0.0f);
LightweightShaderHelper.SetKeyword(material, "_OCCLUSIONMAP", material.GetTexture("_OcclusionMap"));
LightweightShaderHelper.SetKeyword(material, "_PARALLAXMAP", material.GetTexture("_ParallaxMap"));
LightweightShaderHelper.SetKeyword(material, "_DETAIL_MULX2", material.GetTexture("_DetailAlbedoMap") || material.GetTexture("_DetailNormalMap"));
// A material's GI flag internally keeps track of whether emission is enabled at all, it's enabled but has no effect
// or is enabled and may be modified at runtime. This state depends on the values of the current flag and emissive color.
// The fixup routine makes sure that the material is in the correct state if/when changes are made to the mode or color.
MaterialEditor.FixupEmissiveFlag(material);
bool shouldEmissionBeEnabled = (material.globalIlluminationFlags & MaterialGlobalIlluminationFlags.EmissiveIsBlack) == 0;
LightweightShaderHelper.SetKeyword(material, "_EMISSION", shouldEmissionBeEnabled);
if (material.HasProperty("_SmoothnessTextureChannel"))
{
LightweightShaderHelper.SetKeyword(material, "_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A", GetSmoothnessMapChannel(material) == SmoothnessMapChannel.AlbedoAlpha);
}
}
static void MaterialChanged(Material material)
{
material.shaderKeywords = null;
SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode"));
SetMaterialKeywords(material);
}
}
}

253
ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightStandardSimpleLightingGUI.cs


using System;
using UnityEditor;
using UnityEngine;
using UnityEditor.Experimental.Rendering.LightweightPipeline;
public class LightweightStandardSimpleLightingGUI : ShaderGUI
{
private const float kMinShininessValue = 0.01f;
private MaterialProperty blendModeProp = null;
private MaterialProperty albedoMapProp = null;
private MaterialProperty albedoColorProp = null;
private MaterialProperty alphaCutoffProp = null;
private MaterialProperty specularSourceProp = null;
private MaterialProperty glossinessSourceProp = null;
private MaterialProperty specularGlossMapProp = null;
private MaterialProperty specularColorProp = null;
private MaterialProperty shininessProp = null;
private MaterialProperty bumpMapProp = null;
private MaterialProperty emissionMapProp = null;
private MaterialProperty emissionColorProp = null;
private MaterialEditor m_MaterialEditor = null;
private const float kMaxfp16 = 65536f; // Clamp to a value that fits into fp16.
private ColorPickerHDRConfig m_ColorPickerHDRConfig = new ColorPickerHDRConfig(0f, kMaxfp16, 1 / kMaxfp16, 3f);
private static class Styles
{
public static GUIContent[] albedoGlosinessLabels =
{
new GUIContent("Base (RGB) Glossiness (A)", "Base Color (RGB) and Glossiness (A)"),
new GUIContent("Base (RGB)", "Base Color (RGB)")
};
public static GUIContent albedoAlphaLabel = new GUIContent("Base (RGB) Alpha (A)",
"Base Color (RGB) and Transparency (A)");
public static GUIContent[] specularGlossMapLabels =
{
new GUIContent("Specular Map (RGB)", "Specular Color (RGB)"),
new GUIContent("Specular Map (RGB) Glossiness (A)", "Specular Color (RGB) Glossiness (A)")
};
public static GUIContent normalMapText = new GUIContent("Normal Map", "Normal Map");
public static GUIContent emissionMapLabel = new GUIContent("Emission Map", "Emission Map");
public static readonly string[] blendNames = Enum.GetNames(typeof(UpgradeBlendMode));
public static readonly string[] glossinessSourceNames = Enum.GetNames(typeof(GlossinessSource));
public static string renderingModeLabel = "Rendering Mode";
public static string specularSourceLabel = "Specular";
public static string glossinessSourceLabel = "Glossiness Source";
public static string glossinessSource = "Glossiness Source";
public static string albedoColorLabel = "Base Color";
public static string albedoMapAlphaLabel = "Base(RGB) Alpha(A)";
public static string albedoMapGlossinessLabel = "Base(RGB) Glossiness (A)";
public static string alphaCutoffLabel = "Alpha Cutoff";
public static string shininessLabel = "Shininess";
public static string normalMapLabel = "Normal map";
public static string emissionColorLabel = "Emission Color";
}
private void FindMaterialProperties(MaterialProperty[] properties)
{
blendModeProp = FindProperty("_Mode", properties);
albedoMapProp = FindProperty("_MainTex", properties);
albedoColorProp = FindProperty("_Color", properties);
alphaCutoffProp = FindProperty("_Cutoff", properties);
specularSourceProp = FindProperty("_SpecSource", properties);
glossinessSourceProp = FindProperty("_GlossinessSource", properties);
specularGlossMapProp = FindProperty("_SpecGlossMap", properties);
specularColorProp = FindProperty("_SpecColor", properties);
shininessProp = FindProperty("_Shininess", properties);
bumpMapProp = FindProperty("_BumpMap", properties);
emissionMapProp = FindProperty("_EmissionMap", properties);
emissionColorProp = FindProperty("_EmissionColor", properties);
}
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
{
Material material = materialEditor.target as Material;
m_MaterialEditor = materialEditor;
FindMaterialProperties(properties);
EditorGUI.BeginChangeCheck();
{
DoBlendMode();
EditorGUILayout.Space();
DoSpecular();
EditorGUILayout.Space();
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, bumpMapProp);
EditorGUILayout.Space();
DoEmissionArea(material);
EditorGUI.BeginChangeCheck();
m_MaterialEditor.TextureScaleOffsetProperty(albedoMapProp);
if (EditorGUI.EndChangeCheck())
emissionMapProp.textureScaleAndOffset = albedoMapProp.textureScaleAndOffset; // Apply the main texture scale and offset to the emission texture as well, for Enlighten's sake
}
if (EditorGUI.EndChangeCheck())
LegacyBlinnPhongUpgrader.UpdateMaterialKeywords(material);
EditorGUILayout.Space();
EditorGUILayout.Space();
materialEditor.RenderQueueField();
EditorGUILayout.Space();
EditorGUILayout.Space();
}
public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
{
base.AssignNewShaderToMaterial(material, oldShader, newShader);
// Shininess value cannot be zero since it will produce undefined values for cases where pow(0, 0).
float shininess = material.GetFloat("_Shininess");
material.SetFloat("_Shininess", Mathf.Clamp(shininess, kMinShininessValue, 1.0f));
string oldShaderName = oldShader.name;
string[] shaderStrings = oldShaderName.Split('/');
if (shaderStrings[0].Equals("Legacy Shaders") || shaderStrings[0].Equals("Mobile"))
{
ConvertFromLegacy(material, oldShaderName);
}
LegacyBlinnPhongUpgrader.UpdateMaterialKeywords(material);
}
private void DoBlendMode()
{
int modeValue = (int)blendModeProp.floatValue;
EditorGUI.BeginChangeCheck();
modeValue = EditorGUILayout.Popup(Styles.renderingModeLabel, modeValue, Styles.blendNames);
if (EditorGUI.EndChangeCheck())
blendModeProp.floatValue = modeValue;
UpgradeBlendMode mode = (UpgradeBlendMode)blendModeProp.floatValue;
EditorGUILayout.Space();
if (mode == UpgradeBlendMode.Opaque)
{
int glossSource = (int)glossinessSourceProp.floatValue;
m_MaterialEditor.TexturePropertySingleLine(Styles.albedoGlosinessLabels[glossSource], albedoMapProp,
albedoColorProp);
m_MaterialEditor.TextureScaleOffsetProperty(albedoMapProp);}
else
{
m_MaterialEditor.TexturePropertySingleLine(Styles.albedoAlphaLabel, albedoMapProp, albedoColorProp);
if (mode == UpgradeBlendMode.Cutout)
m_MaterialEditor.RangeProperty(alphaCutoffProp, "Cutoff");
}
}
private void DoSpecular()
{
EditorGUILayout.Space();
SpecularSource specularSource = (SpecularSource)specularSourceProp.floatValue;
EditorGUI.BeginChangeCheck();
bool enabled = EditorGUILayout.Toggle(Styles.specularSourceLabel, specularSource == SpecularSource.SpecularTextureAndColor);
if (EditorGUI.EndChangeCheck())
specularSourceProp.floatValue = enabled ? (float)SpecularSource.SpecularTextureAndColor : (float)SpecularSource.NoSpecular;
SpecularSource specSource = (SpecularSource)specularSourceProp.floatValue;
if (specSource != SpecularSource.NoSpecular)
{
bool hasSpecularMap = specularGlossMapProp.textureValue != null;
m_MaterialEditor.TexturePropertySingleLine(Styles.specularGlossMapLabels[(int)glossinessSourceProp.floatValue], specularGlossMapProp, hasSpecularMap ? null : specularColorProp);
EditorGUI.indentLevel += 2;
GUI.enabled = hasSpecularMap;
int glossinessSource = hasSpecularMap ? (int)glossinessSourceProp.floatValue : (int)GlossinessSource.BaseAlpha;
EditorGUI.BeginChangeCheck();
glossinessSource = EditorGUILayout.Popup(Styles.glossinessSourceLabel, glossinessSource, Styles.glossinessSourceNames);
if (EditorGUI.EndChangeCheck())
glossinessSourceProp.floatValue = glossinessSource;
GUI.enabled = true;
EditorGUI.BeginChangeCheck();
float shininess = EditorGUILayout.Slider(Styles.shininessLabel, shininessProp.floatValue,
kMinShininessValue, 1.0f);
if (EditorGUI.EndChangeCheck())
shininessProp.floatValue = shininess;
EditorGUI.indentLevel -= 2;
}
}
void DoEmissionArea(Material material)
{
// Emission for GI?
if (m_MaterialEditor.EmissionEnabledProperty())
{
bool hadEmissionTexture = emissionMapProp.textureValue != null;
// Texture and HDR color controls
m_MaterialEditor.TexturePropertyWithHDRColor(Styles.emissionMapLabel, emissionMapProp, emissionColorProp, m_ColorPickerHDRConfig, false);
// If texture was assigned and color was black set color to white
float brightness = emissionColorProp.colorValue.maxColorComponent;
if (emissionMapProp.textureValue != null && !hadEmissionTexture && brightness <= 0f)
emissionColorProp.colorValue = Color.white;
// LW does not support RealtimeEmissive. We set it to bake emissive and handle the emissive is black right.
material.globalIlluminationFlags = MaterialGlobalIlluminationFlags.BakedEmissive;
if (brightness <= 0f)
material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.EmissiveIsBlack;
}
}
private void ConvertFromLegacy(Material material, string oldShaderName)
{
UpgradeParams shaderUpgradeParams;
if (oldShaderName.Contains("Transp"))
{
shaderUpgradeParams.blendMode = UpgradeBlendMode.Alpha;
shaderUpgradeParams.glosinessSource = GlossinessSource.SpecularAlpha;
}
else if (oldShaderName.Contains("Cutout"))
{
shaderUpgradeParams.blendMode = UpgradeBlendMode.Cutout;
shaderUpgradeParams.glosinessSource = GlossinessSource.SpecularAlpha;
}
else
{
shaderUpgradeParams.blendMode = UpgradeBlendMode.Opaque;
shaderUpgradeParams.glosinessSource = GlossinessSource.BaseAlpha;
}
if (oldShaderName.Contains("Spec"))
shaderUpgradeParams.specularSource = SpecularSource.SpecularTextureAndColor;
else
shaderUpgradeParams.specularSource = SpecularSource.NoSpecular;
material.SetFloat("_Mode", (float)shaderUpgradeParams.blendMode);
material.SetFloat("_SpecSource", (float)shaderUpgradeParams.specularSource);
material.SetFloat("_GlossinessSource", (float)shaderUpgradeParams.glosinessSource);
if (oldShaderName.Contains("Self-Illumin"))
{
material.SetTexture("_EmissionMap", material.GetTexture("_MainTex"));
material.SetTexture("_MainTex", null);
material.SetColor("_EmissionColor", Color.white);
}
}
}

67
ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightUnlitGUI.cs


using System;
using UnityEditor;
using UnityEngine;
using UnityEditor.Experimental.Rendering.LightweightPipeline;
public class LightweightUnlitGUI : ShaderGUI
{
private MaterialProperty blendModeProp = null;
private MaterialProperty mainTexProp = null;
private MaterialProperty mainColorProp = null;
private MaterialProperty alphaCutoffProp = null;
private MaterialEditor m_MaterialEditor = null;
private static class Styles
{
public static GUIContent[] mainTexLabels =
{
new GUIContent("MainTex (RGB)", "Base Color"),
new GUIContent("MainTex (RGB) Alpha (A)", "Base Color and Alpha")
};
public static readonly string[] blendNames = Enum.GetNames(typeof(UpgradeBlendMode));
public static string renderingModeLabel = "Rendering Mode";
public static string alphaCutoffLabel = "Alpha Cutoff";
}
private void FindMaterialProperties(MaterialProperty[] properties)
{
blendModeProp = FindProperty("_Mode", properties);
mainTexProp = FindProperty("_MainTex", properties);
mainColorProp = FindProperty("_MainColor", properties);
alphaCutoffProp = FindProperty("_Cutoff", properties);
}
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
{
Material material = materialEditor.target as Material;
m_MaterialEditor = materialEditor;
FindMaterialProperties(properties);
int modeValue = (int)blendModeProp.floatValue;
EditorGUI.BeginChangeCheck();
modeValue = EditorGUILayout.Popup(Styles.renderingModeLabel, modeValue, Styles.blendNames);
if (EditorGUI.EndChangeCheck())
blendModeProp.floatValue = modeValue;
GUIContent mainTexLabel = Styles.mainTexLabels[Math.Min(modeValue, 1)];
m_MaterialEditor.TexturePropertySingleLine(mainTexLabel, mainTexProp, mainColorProp);
m_MaterialEditor.TextureScaleOffsetProperty(mainTexProp);
if ((UpgradeBlendMode) modeValue == UpgradeBlendMode.Cutout)
m_MaterialEditor.RangeProperty(alphaCutoffProp, Styles.alphaCutoffLabel);
EditorGUILayout.Space();
EditorGUILayout.Space();
materialEditor.RenderQueueField();
LightweightShaderHelper.SetMaterialBlendMode(material);
EditorGUILayout.Space();
EditorGUILayout.Space();
}
}

12
ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightStandardSimpleLightingGUI.cs.meta


fileFormatVersion: 2
guid: 0e3f7c90539343c4eaf7aa690b0e0391
timeCreated: 1487767801
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

13
ScriptableRenderPipeline/LightweightPipeline/Editor/ShaderGUI/LightweightStandardGUI.cs.meta


fileFormatVersion: 2
guid: a72ab9c46e7987c40bcd48bcf9e7c0dd
timeCreated: 1504689095
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

32
ScriptableRenderPipeline/LightweightPipeline/Editor/StandardToLightweightMaterialUpgrader.cs


using System.Collections.Generic;
namespace UnityEditor.Experimental.Rendering.LightweightPipeline
{
public class StandardToLightweightMaterialUpgrader
{
[MenuItem("RenderPipeline/Lightweight Pipeline/Material Upgraders/Upgrade Project Materials", false, 1)]
private static void UpgradeMaterialsToLDProject()
{
List<MaterialUpgrader> upgraders = new List<MaterialUpgrader>();
GetUpgraders(ref upgraders);
MaterialUpgrader.UpgradeProjectFolder(upgraders, "Upgrade to Lightweight Pipeline Materials");
}
[MenuItem("RenderPipeline/Lightweight Pipeline/Material Upgraders/Upgrade Selected Materials", false, 2)]
private static void UpgradeMaterialsToLDSelection()
{
List<MaterialUpgrader> upgraders = new List<MaterialUpgrader>();
GetUpgraders(ref upgraders);
MaterialUpgrader.UpgradeSelection(upgraders, "Upgrade to Lightweight Pipeline Materials");
}
private static void GetUpgraders(ref List<MaterialUpgrader> upgraders)
{
upgraders.Add(new StandardUpgrader("Standard (Specular setup)"));
upgraders.Add(new StandardUpgrader("Standard"));
upgraders.Add(new TerrainUpgrader("TerrainSurface"));
}
}
}

35
ScriptableRenderPipeline/LightweightPipeline/Editor/UpgradeCommon.cs


namespace UnityEditor.Experimental.Rendering.LightweightPipeline
{
public enum UpgradeBlendMode
{
Opaque,
Cutout,
Alpha
}
public enum SpecularSource
{
SpecularTextureAndColor,
NoSpecular
}
public enum GlossinessSource
{
BaseAlpha,
SpecularAlpha
}
public enum ReflectionSource
{
NoReflection,
Cubemap,
ReflectionProbe
}
public struct UpgradeParams
{
public UpgradeBlendMode blendMode;
public SpecularSource specularSource;
public GlossinessSource glosinessSource;
}
}

24
ScriptableRenderPipeline/LightweightPipeline/LightweightConstantBuffer.cs


using UnityEngine;
namespace UnityEngine.Experimental.Rendering.LightweightPipeline
{
public static class PerFrameBuffer
{
public static int _GlossyEnvironmentColor;
public static int _AttenuationTexture;
}
public static class PerCameraBuffer
{
public static int _MainLightPosition;
public static int _MainLightColor;
public static int _MainLightAttenuationParams;
public static int _MainLightSpotDir;
public static int _AdditionalLightCount;
public static int _AdditionalLightPosition;
public static int _AdditionalLightColor;
public static int _AdditionalLightAttenuationParams;
public static int _AdditionalLightSpotDir;
}
}

13
ScriptableRenderPipeline/LightweightPipeline/LightweightConstantBuffer.cs.meta


fileFormatVersion: 2
guid: 2462b9b2044ad4b62a8c7fcd6f012f8e
timeCreated: 1506514389
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

984
ScriptableRenderPipeline/LightweightPipeline/LightweightPipeline.cs


using System;
using System.Collections.Generic;
using UnityEngine.Rendering;
using UnityEngine.Rendering.PostProcessing;
using UnityEngine.XR;
namespace UnityEngine.Experimental.Rendering.LightweightPipeline
{
[Serializable]
public class ShadowSettings
{
public bool enabled;
public int shadowAtlasWidth;
public int shadowAtlasHeight;
public float maxShadowDistance;
public int directionalLightCascadeCount;
public Vector3 directionalLightCascades;
public float directionalLightNearPlaneOffset;
static ShadowSettings defaultShadowSettings = null;
public static ShadowSettings Default
{
get
{
if (defaultShadowSettings == null)
{
defaultShadowSettings = new ShadowSettings();
defaultShadowSettings.enabled = true;
defaultShadowSettings.shadowAtlasHeight = defaultShadowSettings.shadowAtlasWidth = 4096;
defaultShadowSettings.directionalLightCascadeCount = 1;
defaultShadowSettings.directionalLightCascades = new Vector3(0.05F, 0.2F, 0.3F);
defaultShadowSettings.directionalLightCascadeCount = 4;
defaultShadowSettings.directionalLightNearPlaneOffset = 5;
defaultShadowSettings.maxShadowDistance = 1000.0F;
}
return defaultShadowSettings;
}
}
}
public struct ShadowSliceData
{
public Matrix4x4 shadowTransform;
public int atlasX;
public int atlasY;
public int shadowResolution;
}
public struct LightData
{
public int pixelAdditionalLightsCount;
public int totalAdditionalLightsCount;
public int mainLightIndex;
public bool shadowsRendered;
}
public class LightweightPipeline : RenderPipeline
{
private readonly LightweightPipelineAsset m_Asset;
// Maximum amount of visible lights the shader can process. This controls the constant global light buffer size.
// It must match the MAX_VISIBLE_LIGHTS in LightweightCore.cginc
private static readonly int kMaxVisibleAdditionalLights = 16;
// Lights are culled per-object. This holds the maximum amount of additional lights that can shade each object.
// The engine fills in the lights indices per-object in unity4_LightIndices0 and unity_4LightIndices1
private static readonly int kMaxPerObjectAdditionalLights = 8;
private Vector4[] m_LightPositions = new Vector4[kMaxVisibleAdditionalLights];
private Vector4[] m_LightColors = new Vector4[kMaxVisibleAdditionalLights];
private Vector4[] m_LightAttenuations = new Vector4[kMaxVisibleAdditionalLights];
private Vector4[] m_LightSpotDirections = new Vector4[kMaxVisibleAdditionalLights];
private Camera m_CurrCamera = null;
private static readonly int kMaxCascades = 4;
private int m_ShadowCasterCascadesCount = kMaxCascades;
private int m_ShadowMapTexture;
private int m_CameraColorTexture;
private int m_CameraDepthTexture;
private int m_CameraCopyDepthTexture;
private RenderTargetIdentifier m_ShadowMapRT;
private RenderTargetIdentifier m_CameraColorRT;
private RenderTargetIdentifier m_CameraDepthRT;
private RenderTargetIdentifier m_CameraCopyDepthRT;
private bool m_IntermediateTextureArray = false;
private const int kShadowDepthBufferBits = 16;
private const int kCameraDepthBufferBits = 32;
private Vector4[] m_DirectionalShadowSplitDistances = new Vector4[kMaxCascades];
private ShadowSettings m_ShadowSettings = ShadowSettings.Default;
private ShadowSliceData[] m_ShadowSlices = new ShadowSliceData[kMaxCascades];
private static readonly ShaderPassName m_LitPassName = new ShaderPassName("LightweightForward");
private static readonly ShaderPassName m_UnlitPassName = new ShaderPassName("SRPDefaultUnlit");
private RenderTextureFormat m_ColorFormat;
private PostProcessRenderContext m_PostProcessRenderContext;
private PostProcessLayer m_CameraPostProcessLayer;
private CameraComparer m_CameraComparer = new CameraComparer();
private LightComparer m_LightCompararer = new LightComparer();
// Maps from sorted light indices to original unsorted. We need this for shadow rendering
// and per-object light lists.
private List<int> m_SortedLightIndexMap = new List<int>();
private Mesh m_BlitQuad;
private Material m_BlitMaterial;
private Material m_CopyDepthMaterial;
private int m_BlitTexID = Shader.PropertyToID("_BlitTex");
private CopyTextureSupport m_CopyTextureSupport;
public LightweightPipeline(LightweightPipelineAsset asset)
{
m_Asset = asset;
BuildShadowSettings();
PerFrameBuffer._GlossyEnvironmentColor = Shader.PropertyToID("_GlossyEnvironmentColor");
PerFrameBuffer._AttenuationTexture = Shader.PropertyToID("_AttenuationTexture");
PerCameraBuffer._MainLightPosition = Shader.PropertyToID("_MainLightPosition");
PerCameraBuffer._MainLightColor = Shader.PropertyToID("_MainLightColor");
PerCameraBuffer._MainLightAttenuationParams = Shader.PropertyToID("_MainLightAttenuationParams");
PerCameraBuffer._MainLightSpotDir = Shader.PropertyToID("_MainLightSpotDir");
PerCameraBuffer._AdditionalLightCount = Shader.PropertyToID("_AdditionalLightCount");
PerCameraBuffer._AdditionalLightPosition = Shader.PropertyToID("_AdditionalLightPosition");
PerCameraBuffer._AdditionalLightColor = Shader.PropertyToID("_AdditionalLightColor");
PerCameraBuffer._AdditionalLightAttenuationParams = Shader.PropertyToID("_AdditionalLightAttenuationParams");
PerCameraBuffer._AdditionalLightSpotDir = Shader.PropertyToID("_AdditionalLightSpotDir");
m_ShadowMapTexture = Shader.PropertyToID("_ShadowMap");
m_CameraColorTexture = Shader.PropertyToID("_CameraColorTexture");
m_CameraDepthTexture = Shader.PropertyToID("_CameraDepthTexture");
m_CameraCopyDepthTexture = Shader.PropertyToID("_CameraCopyDepthTexture");
m_ShadowMapRT = new RenderTargetIdentifier(m_ShadowMapTexture);
m_CameraColorRT = new RenderTargetIdentifier(m_CameraColorTexture);
m_CameraDepthRT = new RenderTargetIdentifier(m_CameraDepthTexture);
m_CameraCopyDepthRT = new RenderTargetIdentifier(m_CameraCopyDepthTexture);
m_PostProcessRenderContext = new PostProcessRenderContext();
m_CopyTextureSupport = SystemInfo.copyTextureSupport;
// Let engine know we have MSAA on for cases where we support MSAA backbuffer
if (QualitySettings.antiAliasing != m_Asset.MSAASampleCount)
QualitySettings.antiAliasing = m_Asset.MSAASampleCount;
Shader.globalRenderPipeline = "LightweightPipeline";
m_BlitQuad = LightweightUtils.CreateQuadMesh(false);
m_BlitMaterial = new Material(m_Asset.BlitShader)
{
hideFlags = HideFlags.HideAndDontSave
};
m_CopyDepthMaterial = new Material(m_Asset.CopyDepthShader)
{
hideFlags = HideFlags.HideAndDontSave
};
}
public override void Dispose()
{
base.Dispose();
Shader.globalRenderPipeline = "";
}
CullResults m_CullResults;
public override void Render(ScriptableRenderContext context, Camera[] cameras)
{
base.Render(context, cameras);
bool stereoEnabled = XRSettings.isDeviceActive;
// TODO: This is at the moment required for all pipes. We should not implicitly change user project settings
// instead this should be forced when using SRP, since all SRP use linear lighting.
GraphicsSettings.lightsUseLinearIntensity = true;
SetupPerFrameShaderConstants(ref context);
// Sort cameras array by camera depth
Array.Sort(cameras, m_CameraComparer);
foreach (Camera camera in cameras)
{
m_CurrCamera = camera;
ScriptableCullingParameters cullingParameters;
if (!CullResults.GetCullingParameters(m_CurrCamera, stereoEnabled, out cullingParameters))
continue;
cullingParameters.shadowDistance = Mathf.Min(m_ShadowSettings.maxShadowDistance,
m_CurrCamera.farClipPlane);
#if UNITY_EDITOR
// Emit scene view UI
if (camera.cameraType == CameraType.SceneView)
ScriptableRenderContext.EmitWorldGeometryForSceneView(camera);
#endif
CullResults.Cull(ref cullingParameters, context, ref m_CullResults);
VisibleLight[] visibleLights = m_CullResults.visibleLights.ToArray();
LightData lightData;
InitializeLightData(visibleLights, out lightData);
ShadowPass(visibleLights, ref context, ref lightData);
ForwardPass(visibleLights, ref context, ref lightData, stereoEnabled);
// Release temporary RT
var cmd = CommandBufferPool.Get("After Camera Render");
cmd.ReleaseTemporaryRT(m_ShadowMapTexture);
cmd.ReleaseTemporaryRT(m_CameraColorTexture);
cmd.ReleaseTemporaryRT(m_CameraDepthTexture);
cmd.ReleaseTemporaryRT(m_CameraCopyDepthTexture);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
context.Submit();
}
}
private void ShadowPass(VisibleLight[] visibleLights, ref ScriptableRenderContext context, ref LightData lightData)
{
if (m_Asset.AreShadowsEnabled() && lightData.mainLightIndex != -1)
{
VisibleLight mainLight = visibleLights[lightData.mainLightIndex];
if (mainLight.light.shadows != LightShadows.None)
{
if (!LightweightUtils.IsSupportedShadowType(mainLight.lightType))
{
Debug.LogWarning("Only directional and spot shadows are supported by LightweightPipeline.");
return;
}
// There's no way to map shadow light indices. We need to pass in the original unsorted index.
// If no additional lights then no light sorting is performed and the indices match.
int shadowOriginalIndex = (lightData.totalAdditionalLightsCount > 0) ? GetLightUnsortedIndex(lightData.mainLightIndex) : lightData.mainLightIndex;
lightData.shadowsRendered = RenderShadows(ref m_CullResults, ref mainLight,
shadowOriginalIndex, ref context);
}
}
}
private void ForwardPass(VisibleLight[] visibleLights, ref ScriptableRenderContext context, ref LightData lightData, bool stereoEnabled)
{
FrameRenderingConfiguration frameRenderingConfiguration;
SetupFrameRendering(out frameRenderingConfiguration);
SetupIntermediateResources(frameRenderingConfiguration, ref context);
SetupShaderConstants(visibleLights, ref context, ref lightData);
// SetupCameraProperties does the following:
// Setup Camera RenderTarget and Viewport
// VR Camera Setup and SINGLE_PASS_STEREO props
// Setup camera view, proj and their inv matrices.
// Setup properties: _WorldSpaceCameraPos, _ProjectionParams, _ScreenParams, _ZBufferParams, unity_OrthoParams
// Setup camera world clip planes props
// setup HDR keyword
// Setup global time properties (_Time, _SinTime, _CosTime)
context.SetupCameraProperties(m_CurrCamera, stereoEnabled);
RendererConfiguration rendererSettings = GetRendererSettings(ref lightData);
BeginForwardRendering(ref context, frameRenderingConfiguration);
RenderOpaques(ref context, rendererSettings);
AfterOpaque(ref context, frameRenderingConfiguration);
RenderTransparents(ref context, rendererSettings);
AfterTransparent(ref context, frameRenderingConfiguration);
EndForwardRendering(ref context, frameRenderingConfiguration);
}
private void RenderOpaques(ref ScriptableRenderContext context, RendererConfiguration settings)
{
var opaqueDrawSettings = new DrawRendererSettings(m_CurrCamera, m_LitPassName);
opaqueDrawSettings.sorting.flags = SortFlags.CommonOpaque;
opaqueDrawSettings.rendererConfiguration = settings;
var opaqueFilterSettings = new FilterRenderersSettings(true)
{
renderQueueRange = RenderQueueRange.opaque
};
context.DrawRenderers(m_CullResults.visibleRenderers, ref opaqueDrawSettings, opaqueFilterSettings);
context.DrawSkybox(m_CurrCamera);
}
private void AfterOpaque(ref ScriptableRenderContext context, FrameRenderingConfiguration config)
{
if (!LightweightUtils.HasFlag(config, FrameRenderingConfiguration.RequireDepth))
return;
CommandBuffer cmd = CommandBufferPool.Get("After Opaque");
cmd.SetGlobalTexture(m_CameraDepthTexture, m_CameraDepthRT);
// When soft particles are enabled we have to copy depth to another RT so we can read and write to depth
if (m_Asset.SupportsSoftParticles)
{
RenderTargetIdentifier colorRT = (m_CurrCamera.targetTexture != null) ? BuiltinRenderTextureType.CameraTarget : m_CameraColorRT;
CopyTexture(cmd, m_CameraDepthRT, m_CameraCopyDepthTexture);
SetupRenderTargets(cmd, colorRT, m_CameraCopyDepthRT);
}
// Only takes effect if custom BeforeTransparent PostProcessing effects are active
if (LightweightUtils.HasFlag(config, FrameRenderingConfiguration.PostProcess))
RenderPostProcess(cmd , true);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
private void AfterTransparent(ref ScriptableRenderContext context, FrameRenderingConfiguration config)
{
if (!LightweightUtils.HasFlag(config, FrameRenderingConfiguration.PostProcess))
return;
CommandBuffer cmd = CommandBufferPool.Get("After Transparent");
RenderPostProcess(cmd, false);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
private void RenderTransparents(ref ScriptableRenderContext context, RendererConfiguration config)
{
var transparentSettings = new DrawRendererSettings(m_CurrCamera, m_LitPassName);
transparentSettings.SetShaderPassName(1, m_UnlitPassName);
transparentSettings.sorting.flags = SortFlags.CommonTransparent;
transparentSettings.rendererConfiguration = config;
var transparentFilterSettings = new FilterRenderersSettings(true)
{
renderQueueRange = RenderQueueRange.transparent
};
context.DrawRenderers(m_CullResults.visibleRenderers, ref transparentSettings, transparentFilterSettings);
}
private void BuildShadowSettings()
{
m_ShadowSettings = ShadowSettings.Default;
m_ShadowSettings.directionalLightCascadeCount = m_Asset.CascadeCount;
m_ShadowSettings.shadowAtlasWidth = m_Asset.ShadowAtlasResolution;
m_ShadowSettings.shadowAtlasHeight = m_Asset.ShadowAtlasResolution;
m_ShadowSettings.maxShadowDistance = m_Asset.ShadowDistance;
switch (m_ShadowSettings.directionalLightCascadeCount)
{
case 1:
m_ShadowSettings.directionalLightCascades = new Vector3(1.0f, 0.0f, 0.0f);
break;
case 2:
m_ShadowSettings.directionalLightCascades = new Vector3(m_Asset.Cascade2Split, 1.0f, 0.0f);
break;
default:
m_ShadowSettings.directionalLightCascades = m_Asset.Cascade4Split;
break;
}
}
private void SetupFrameRendering(out FrameRenderingConfiguration configuration)
{
configuration = (XRSettings.enabled) ? FrameRenderingConfiguration.Stereo : FrameRenderingConfiguration.None;
if (XRSettings.enabled && XRSettings.eyeTextureDesc.dimension == TextureDimension.Tex2DArray)
m_IntermediateTextureArray = true;
else
m_IntermediateTextureArray = false;
bool intermediateTexture = m_CurrCamera.targetTexture != null || m_CurrCamera.cameraType == CameraType.SceneView ||
m_Asset.RenderScale < 1.0f || m_CurrCamera.allowHDR;
m_ColorFormat = m_CurrCamera.allowHDR ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32;
m_CameraPostProcessLayer = m_CurrCamera.GetComponent<PostProcessLayer>();
bool postProcessEnabled = m_CameraPostProcessLayer != null && m_CameraPostProcessLayer.enabled;
if (postProcessEnabled || m_Asset.SupportsSoftParticles)
{
configuration |= FrameRenderingConfiguration.RequireDepth;
intermediateTexture = true;
if (postProcessEnabled)
configuration |= FrameRenderingConfiguration.PostProcess;
}
// When post process or soft particles are enabled we disable msaa due to lack of depth resolve
// One can still use PostFX AA
else if (m_CurrCamera.allowMSAA && m_Asset.MSAASampleCount > 1)
{
configuration |= FrameRenderingConfiguration.Msaa;
intermediateTexture = !LightweightUtils.PlatformSupportsMSAABackBuffer();
}
Rect cameraRect = m_CurrCamera.rect;
if (cameraRect.x > 0.0f || cameraRect.y > 0.0f || cameraRect.width < 1.0f || cameraRect.height < 1.0f)
intermediateTexture = true;
else
configuration |= FrameRenderingConfiguration.DefaultViewport;
if (intermediateTexture)
configuration |= FrameRenderingConfiguration.IntermediateTexture;
}
private void SetupIntermediateResources(FrameRenderingConfiguration renderingConfig, ref ScriptableRenderContext context)
{
CommandBuffer cmd = CommandBufferPool.Get("Setup Intermediate Resources");
float renderScale = (m_CurrCamera.cameraType == CameraType.Game) ? m_Asset.RenderScale : 1.0f;
int rtWidth = (int)((float)m_CurrCamera.pixelWidth * renderScale);
int rtHeight = (int)((float)m_CurrCamera.pixelHeight * renderScale);
int msaaSamples = (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.Msaa)) ? m_Asset.MSAASampleCount : 1;
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.IntermediateTexture))
{
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.Stereo))
{
RenderTextureDescriptor rtDesc = new RenderTextureDescriptor();
rtDesc = XRSettings.eyeTextureDesc;
rtDesc.colorFormat = m_ColorFormat;
rtDesc.msaaSamples = msaaSamples;
cmd.GetTemporaryRT(m_CameraColorTexture, rtDesc, FilterMode.Bilinear);
}
else if (m_CurrCamera.targetTexture == null)
{
cmd.GetTemporaryRT(m_CameraColorTexture, rtWidth, rtHeight, kCameraDepthBufferBits,
FilterMode.Bilinear, m_ColorFormat, RenderTextureReadWrite.Default, msaaSamples);
}
}
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.RequireDepth))
{
cmd.GetTemporaryRT(m_CameraDepthTexture, rtWidth, rtHeight, kCameraDepthBufferBits, FilterMode.Bilinear, RenderTextureFormat.Depth);
if (m_Asset.SupportsSoftParticles)
cmd.GetTemporaryRT(m_CameraCopyDepthTexture, rtWidth, rtHeight, kCameraDepthBufferBits, FilterMode.Bilinear, RenderTextureFormat.Depth);
}
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
private void SetupShaderConstants(VisibleLight[] visibleLights, ref ScriptableRenderContext context, ref LightData lightData)
{
CommandBuffer cmd = CommandBufferPool.Get("SetupShaderConstants");
SetupShaderLightConstants(cmd, visibleLights, ref lightData, ref m_CullResults, ref context);
SetShaderKeywords(cmd, ref lightData, visibleLights);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
private void InitializeLightData(VisibleLight[] visibleLights, out LightData lightData)
{
int visibleLightsCount = visibleLights.Length;
m_SortedLightIndexMap.Clear();
lightData.shadowsRendered = false;
if (visibleLightsCount <= 1)
{
// If there's exactly one visible light that will be picked as main light.
// Otherwise we disable main light by setting its index to -1.
lightData.mainLightIndex = visibleLightsCount - 1;
lightData.pixelAdditionalLightsCount = 0;
lightData.totalAdditionalLightsCount = 0;
return;
}
// We always support at least one per-pixel light, which is main light. Shade objects up to a limit of per-object
// pixel lights defined in the pipeline settings.
int maxSupportedPixelLights = Math.Min(m_Asset.MaxAdditionalPixelLights, kMaxPerObjectAdditionalLights) + 1;
int maxPixelLights = Math.Min(maxSupportedPixelLights, visibleLightsCount);
// If vertex lighting is enabled in the pipeline settings, then we shade the remaining visible lights per-vertex
// up to the maximum amount of per-object lights.
int vertexLights = (m_Asset.SupportsVertexLight) ? kMaxPerObjectAdditionalLights - maxPixelLights - 1: 0;
lightData.mainLightIndex = SortLights(visibleLights);
lightData.pixelAdditionalLightsCount = maxPixelLights - 1;
lightData.totalAdditionalLightsCount = lightData.pixelAdditionalLightsCount + vertexLights;
}
private int SortLights(VisibleLight[] visibleLights)
{
int totalVisibleLights = visibleLights.Length;
Dictionary<int, int> visibleLightsIDMap = new Dictionary<int, int>();
for (int i = 0; i < totalVisibleLights; ++i)
visibleLightsIDMap.Add(visibleLights[i].GetHashCode(), i);
// Sorts light so we have all directionals first, then local lights.
// Directionals are sorted further by shadow, cookie and intensity
// Locals are sorted further by shadow, cookie and distance to camera
m_LightCompararer.CurrCamera = m_CurrCamera;
Array.Sort(visibleLights, m_LightCompararer);
for (int i = 0; i < totalVisibleLights; ++i)
m_SortedLightIndexMap.Add(visibleLightsIDMap[visibleLights[i].GetHashCode()]);
return GetMainLight(visibleLights);
}
// How main light is decided:
// If shadows enabled, main light is always a shadow casting light. Directional has priority over local lights.
// Otherwise directional lights have priority based on cookie support and intensity
// If no directional light in the scene local lights based on cookie support and distance to camera
private int GetMainLight(VisibleLight[] visibleLights)
{
int totalVisibleLights = visibleLights.Length;
bool shadowsEnabled = m_Asset.AreShadowsEnabled();
// If shadows are supported and the first visible light has shadows then this is main light
if (shadowsEnabled && visibleLights[0].light.shadows != LightShadows.None)
return 0;
// We don't have any directional shadow casting light, skip until we find the first non directional light
int lightIndex = 0;
while (lightIndex < totalVisibleLights && visibleLights[lightIndex].lightType == LightType.Directional)
lightIndex++;
// If first non-directional light has shadows we return it, otherwise we return first light
return (lightIndex < totalVisibleLights && visibleLights[lightIndex].light.shadows != LightShadows.None) ? lightIndex : 0;
}
private void InitializeLightConstants(VisibleLight[] lights, int lightIndex, out Vector4 lightPos, out Vector4 lightColor, out Vector4 lightSpotDir,
out Vector4 lightAttenuationParams)
{
lightPos = new Vector4(0.0f, 0.0f, 1.0f, 0.0f);
lightColor = Color.black;
lightAttenuationParams = new Vector4(0.0f, 1.0f, 0.0f, 0.0f);
lightSpotDir = new Vector4(0.0f, 0.0f, 1.0f, 0.0f);
// When no lights are visible, main light will be set to -1.
// In this case we initialize it to default values and return
if (lightIndex < 0)
return;
VisibleLight light = lights[lightIndex];
if (light.lightType == LightType.Directional)
{
Vector4 dir = -light.localToWorld.GetColumn(2);
lightPos = new Vector4(dir.x, dir.y, dir.z, 0.0f);
}
else
{
Vector4 pos = light.localToWorld.GetColumn(3);
lightPos = new Vector4(pos.x, pos.y, pos.z, 1.0f);
}
lightColor = light.finalColor;
float rangeSq = light.range * light.range;
float quadAtten = 0.0f;
if (light.lightType != LightType.Directional)
quadAtten = (m_Asset.AttenuationTexture != null) ? 1.0f : 25.0f / rangeSq;
if (light.lightType == LightType.Spot)
{
Vector4 dir = light.localToWorld.GetColumn(2);
lightSpotDir = new Vector4(-dir.x, -dir.y, -dir.z, 0.0f);
// Spot Attenuation with a linear falloff can be defined as
// (SdotL - cosOuterAngle) / (cosInnerAngle - cosOuterAngle)
// This can be rewritten as
// invAngleRange = 1.0 / (cosInnerAngle - cosOuterAngle)
// SdotL * invAngleRange + (-cosOuterAngle * invAngleRange)
// If we precompute the terms in a MAD instruction
float spotAngle = Mathf.Deg2Rad * light.spotAngle;
float cosOuterAngle = Mathf.Cos(spotAngle * 0.5f);
float cosInneAngle = Mathf.Cos(spotAngle * 0.25f);
float smoothAngleRange = cosInneAngle - cosOuterAngle;
if (Mathf.Approximately(smoothAngleRange, 0.0f))
smoothAngleRange = 1.0f;
float invAngleRange = 1.0f / smoothAngleRange;
float add = -cosOuterAngle * invAngleRange;
lightAttenuationParams = new Vector4(invAngleRange, add, quadAtten, rangeSq);
}
else
{
lightSpotDir = new Vector4(0.0f, 0.0f, 1.0f, 0.0f);
lightAttenuationParams = new Vector4(0.0f, 1.0f, quadAtten, rangeSq);
}
}
private void SetupPerFrameShaderConstants(ref ScriptableRenderContext context)
{
// When glossy reflections are OFF in the shader we set a constant color to use as indirect specular
SphericalHarmonicsL2 ambientSH = RenderSettings.ambientProbe;
Vector4 glossyEnvColor = new Vector4(ambientSH[0, 0], ambientSH[1, 0], ambientSH[2, 0]) * RenderSettings.reflectionIntensity;
CommandBuffer cmd = CommandBufferPool.Get("SetupPerFrameConstants");
cmd.SetGlobalVector(PerFrameBuffer._GlossyEnvironmentColor, glossyEnvColor);
if (m_Asset.AttenuationTexture != null) cmd.SetGlobalTexture(PerFrameBuffer._AttenuationTexture, m_Asset.AttenuationTexture);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release (cmd);
}
private void SetupShaderLightConstants(CommandBuffer cmd, VisibleLight[] lights, ref LightData lightData, ref CullResults cullResults, ref ScriptableRenderContext context)
{
// Main light has an optimized shader path for main light. This will benefit games that only care about a single light.
// Lightweight pipeline also supports only a single shadow light, if available it will be the main light.
SetupMainLightConstants(cmd, lights, lightData.mainLightIndex, ref context);
if (lightData.shadowsRendered)
SetupShadowShaderConstants(cmd, ref context, ref lights[lightData.mainLightIndex], m_ShadowCasterCascadesCount);
if (lightData.totalAdditionalLightsCount > 0)
SetupAdditionalListConstants(cmd, lights, ref lightData, ref context);
}
private void SetupMainLightConstants(CommandBuffer cmd, VisibleLight[] lights, int lightIndex, ref ScriptableRenderContext context)
{
Vector4 lightPos, lightColor, lightSpotDir, lightAttenuationParams;
InitializeLightConstants(lights, lightIndex, out lightPos, out lightColor, out lightSpotDir, out lightAttenuationParams);
cmd.SetGlobalVector(PerCameraBuffer._MainLightPosition, lightPos);
cmd.SetGlobalColor(PerCameraBuffer._MainLightColor, lightColor);
cmd.SetGlobalVector(PerCameraBuffer._MainLightSpotDir, lightSpotDir);
cmd.SetGlobalVector(PerCameraBuffer._MainLightAttenuationParams, lightAttenuationParams);
}
private void SetupAdditionalListConstants(CommandBuffer cmd, VisibleLight[] lights, ref LightData lightData, ref ScriptableRenderContext context)
{
int additionalLightIndex = 0;
// We need to update per-object light list with the proper map to our global additional light buffer
// First we initialize all lights in the map to -1 to tell the system to discard main light index and
// remaining lights in the scene that don't fit the max additional light buffer (kMaxVisibileAdditionalLights)
int[] perObjectLightIndexMap = m_CullResults.GetLightIndexMap();
for (int i = 0; i < lights.Length; ++i)
perObjectLightIndexMap[i] = -1;
for (int i = 0; i < lights.Length && additionalLightIndex < kMaxVisibleAdditionalLights; ++i)
{
if (i != lightData.mainLightIndex)
{
// The engine performs per-object light culling and initialize 8 light indices into two vec4 constants unity_4LightIndices0 and unity_4LightIndices1.
// In the shader we iterate over each visible light using the indices provided in these constants to index our global light buffer
// ex: first light position would be m_LightPosisitions[unity_4LightIndices[0]];
// However since we sorted the lights we need to tell the engine how to map the original/unsorted indices to our global buffer
// We do it by settings the perObjectLightIndexMap to the appropriate additionalLightIndex.
perObjectLightIndexMap[GetLightUnsortedIndex(i)] = additionalLightIndex;
InitializeLightConstants(lights, i, out m_LightPositions[additionalLightIndex],
out m_LightColors[additionalLightIndex],
out m_LightSpotDirections[additionalLightIndex],
out m_LightAttenuations[additionalLightIndex]);
additionalLightIndex++;
}
}
m_CullResults.SetLightIndexMap(perObjectLightIndexMap);
cmd.SetGlobalVector(PerCameraBuffer._AdditionalLightCount, new Vector4 (lightData.pixelAdditionalLightsCount,
lightData.totalAdditionalLightsCount, 0.0f, 0.0f));
cmd.SetGlobalVectorArray (PerCameraBuffer._AdditionalLightPosition, m_LightPositions);
cmd.SetGlobalVectorArray (PerCameraBuffer._AdditionalLightColor, m_LightColors);
cmd.SetGlobalVectorArray (PerCameraBuffer._AdditionalLightAttenuationParams, m_LightAttenuations);
cmd.SetGlobalVectorArray (PerCameraBuffer._AdditionalLightSpotDir, m_LightSpotDirections);
}
private void SetupShadowShaderConstants(CommandBuffer cmd, ref ScriptableRenderContext context, ref VisibleLight shadowLight, int cascadeCount)
{
Vector3 shadowLightDir = Vector3.Normalize(shadowLight.localToWorld.GetColumn(2));
Light light = shadowLight.light;
float bias = light.shadowBias * 0.1f;
float normalBias = light.shadowNormalBias;
float shadowResolution = m_ShadowSlices[0].shadowResolution;
const int maxShadowCascades = 4;
Matrix4x4[] shadowMatrices = new Matrix4x4[maxShadowCascades];
for (int i = 0; i < cascadeCount; ++i)
shadowMatrices[i] = (cascadeCount >= i) ? m_ShadowSlices[i].shadowTransform : Matrix4x4.identity;
// TODO: shadow resolution per cascade in case cascades endup being supported.
float invShadowResolution = 1.0f / shadowResolution;
float[] pcfKernel =
{
-0.5f * invShadowResolution, 0.5f * invShadowResolution,
0.5f * invShadowResolution, 0.5f * invShadowResolution,
-0.5f * invShadowResolution, -0.5f * invShadowResolution,
0.5f * invShadowResolution, -0.5f * invShadowResolution
};
cmd.SetGlobalMatrixArray("_WorldToShadow", shadowMatrices);
cmd.SetGlobalVectorArray("_DirShadowSplitSpheres", m_DirectionalShadowSplitDistances);
cmd.SetGlobalVector("_ShadowLightDirection", new Vector4(-shadowLightDir.x, -shadowLightDir.y, -shadowLightDir.z, 0.0f));
cmd.SetGlobalVector("_ShadowData", new Vector4(0.0f, bias, normalBias, 0.0f));
cmd.SetGlobalFloatArray("_PCFKernel", pcfKernel);
}
private void SetShaderKeywords(CommandBuffer cmd, ref LightData lightData, VisibleLight[] visibleLights)
{
int vertexLightsCount = lightData.totalAdditionalLightsCount - lightData.pixelAdditionalLightsCount;
LightweightUtils.SetKeyword(cmd, "_VERTEX_LIGHTS", vertexLightsCount > 0);
int mainLightIndex = lightData.mainLightIndex;
LightweightUtils.SetKeyword (cmd, "_MAIN_DIRECTIONAL_LIGHT", mainLightIndex == -1 || visibleLights[mainLightIndex].lightType == LightType.Directional);
LightweightUtils.SetKeyword (cmd, "_MAIN_SPOT_LIGHT", mainLightIndex != -1 && visibleLights[mainLightIndex].lightType == LightType.Spot);
LightweightUtils.SetKeyword (cmd, "_MAIN_POINT_LIGHT", mainLightIndex != -1 && visibleLights[mainLightIndex].lightType == LightType.Point);
LightweightUtils.SetKeyword(cmd, "_ADDITIONAL_LIGHTS", lightData.totalAdditionalLightsCount > 0);
string[] shadowKeywords = new string[] { "_HARD_SHADOWS", "_SOFT_SHADOWS", "_HARD_SHADOWS_CASCADES", "_SOFT_SHADOWS_CASCADES" };
for (int i = 0; i < shadowKeywords.Length; ++i)
cmd.DisableShaderKeyword(shadowKeywords[i]);
if (m_Asset.AreShadowsEnabled() && lightData.shadowsRendered)
{
int keywordIndex = (int)m_Asset.ShadowSetting - 1;
if (m_Asset.CascadeCount > 1)
keywordIndex += 2;
cmd.EnableShaderKeyword(shadowKeywords[keywordIndex]);
}
LightweightUtils.SetKeyword(cmd, "SOFTPARTICLES_ON", m_Asset.SupportsSoftParticles);
}
private bool RenderShadows(ref CullResults cullResults, ref VisibleLight shadowLight, int shadowLightIndex, ref ScriptableRenderContext context)
{
m_ShadowCasterCascadesCount = m_ShadowSettings.directionalLightCascadeCount;
if (shadowLight.lightType == LightType.Spot)
m_ShadowCasterCascadesCount = 1;
int shadowResolution = GetMaxTileResolutionInAtlas(m_ShadowSettings.shadowAtlasWidth, m_ShadowSettings.shadowAtlasHeight, m_ShadowCasterCascadesCount);
Bounds bounds;
if (!cullResults.GetShadowCasterBounds(shadowLightIndex, out bounds))
return false;
var setRenderTargetCommandBuffer = CommandBufferPool.Get();
setRenderTargetCommandBuffer.name = "Render packed shadows";
setRenderTargetCommandBuffer.GetTemporaryRT(m_ShadowMapTexture, m_ShadowSettings.shadowAtlasWidth,
m_ShadowSettings.shadowAtlasHeight, kShadowDepthBufferBits, FilterMode.Bilinear, RenderTextureFormat.Depth);
setRenderTargetCommandBuffer.SetRenderTarget(m_ShadowMapRT);
setRenderTargetCommandBuffer.ClearRenderTarget(true, true, Color.black);
context.ExecuteCommandBuffer(setRenderTargetCommandBuffer);
CommandBufferPool.Release(setRenderTargetCommandBuffer);
float shadowNearPlane = m_Asset.ShadowNearOffset;
Vector3 splitRatio = m_ShadowSettings.directionalLightCascades;
Matrix4x4 view, proj;
var settings = new DrawShadowsSettings(cullResults, shadowLightIndex);
bool needRendering = false;
if (shadowLight.lightType == LightType.Spot)
{
needRendering = cullResults.ComputeSpotShadowMatricesAndCullingPrimitives(shadowLightIndex, out view, out proj,
out settings.splitData);
if (!needRendering)
return false;
SetupShadowSliceTransform(0, shadowResolution, proj, view);
RenderShadowSlice(ref context, 0, proj, view, settings);
}
else if (shadowLight.lightType == LightType.Directional)
{
for (int cascadeIdx = 0; cascadeIdx < m_ShadowCasterCascadesCount; ++cascadeIdx)
{
needRendering = cullResults.ComputeDirectionalShadowMatricesAndCullingPrimitives(shadowLightIndex,
cascadeIdx, m_ShadowCasterCascadesCount, splitRatio, shadowResolution, shadowNearPlane, out view, out proj,
out settings.splitData);
m_DirectionalShadowSplitDistances[cascadeIdx] = settings.splitData.cullingSphere;
m_DirectionalShadowSplitDistances[cascadeIdx].w *= settings.splitData.cullingSphere.w;
if (!needRendering)
return false;
SetupShadowSliceTransform(cascadeIdx, shadowResolution, proj, view);
RenderShadowSlice(ref context, cascadeIdx, proj, view, settings);
}
}
else
{
Debug.LogWarning("Only spot and directional shadow casters are supported in lightweight pipeline");
return false;
}
return true;
}
private void SetupShadowSliceTransform(int cascadeIndex, int shadowResolution, Matrix4x4 proj, Matrix4x4 view)
{
// Assumes MAX_CASCADES = 4
m_ShadowSlices[cascadeIndex].atlasX = (cascadeIndex % 2) * shadowResolution;
m_ShadowSlices[cascadeIndex].atlasY = (cascadeIndex / 2) * shadowResolution;
m_ShadowSlices[cascadeIndex].shadowResolution = shadowResolution;
m_ShadowSlices[cascadeIndex].shadowTransform = Matrix4x4.identity;
var matScaleBias = Matrix4x4.identity;
matScaleBias.m00 = 0.5f;
matScaleBias.m11 = 0.5f;
matScaleBias.m22 = 0.5f;
matScaleBias.m03 = 0.5f;
matScaleBias.m23 = 0.5f;
matScaleBias.m13 = 0.5f;
// Later down the pipeline the proj matrix will be scaled to reverse-z in case of DX.
// We need account for that scale in the shadowTransform.
if (SystemInfo.usesReversedZBuffer)
matScaleBias.m22 = -0.5f;
var matTile = Matrix4x4.identity;
matTile.m00 = (float)m_ShadowSlices[cascadeIndex].shadowResolution /
(float)m_ShadowSettings.shadowAtlasWidth;
matTile.m11 = (float)m_ShadowSlices[cascadeIndex].shadowResolution /
(float)m_ShadowSettings.shadowAtlasHeight;
matTile.m03 = (float)m_ShadowSlices[cascadeIndex].atlasX / (float)m_ShadowSettings.shadowAtlasWidth;
matTile.m13 = (float)m_ShadowSlices[cascadeIndex].atlasY / (float)m_ShadowSettings.shadowAtlasHeight;
m_ShadowSlices[cascadeIndex].shadowTransform = matTile * matScaleBias * proj * view;
}
private void RenderShadowSlice(ref ScriptableRenderContext context, int cascadeIndex,
Matrix4x4 proj, Matrix4x4 view, DrawShadowsSettings settings)
{
var buffer = CommandBufferPool.Get("Prepare Shadowmap Slice");
buffer.SetViewport(new Rect(m_ShadowSlices[cascadeIndex].atlasX, m_ShadowSlices[cascadeIndex].atlasY,
m_ShadowSlices[cascadeIndex].shadowResolution, m_ShadowSlices[cascadeIndex].shadowResolution));
buffer.SetViewProjectionMatrices(view, proj);
context.ExecuteCommandBuffer(buffer);
context.DrawShadows(ref settings);
CommandBufferPool.Release(buffer);
}
private int GetMaxTileResolutionInAtlas(int atlasWidth, int atlasHeight, int tileCount)
{
int resolution = Mathf.Min(atlasWidth, atlasHeight);
if (tileCount > Mathf.Log(resolution))
{
Debug.LogError(
String.Format(
"Cannot fit {0} tiles into current shadowmap atlas of size ({1}, {2}). ShadowMap Resolution set to zero.",
tileCount, atlasWidth, atlasHeight));
return 0;
}
int currentTileCount = atlasWidth / resolution * atlasHeight / resolution;
while (currentTileCount < tileCount)
{
resolution = resolution >> 1;
currentTileCount = atlasWidth / resolution * atlasHeight / resolution;
}
return resolution;
}
private void BeginForwardRendering(ref ScriptableRenderContext context, FrameRenderingConfiguration renderingConfig)
{
RenderTargetIdentifier colorRT = BuiltinRenderTextureType.CameraTarget;
RenderTargetIdentifier depthRT = BuiltinRenderTextureType.None;
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.Stereo))
context.StartMultiEye(m_CurrCamera);
CommandBuffer cmd = CommandBufferPool.Get("SetCameraRenderTarget");
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.IntermediateTexture))
{
if (m_CurrCamera.targetTexture == null)
colorRT = m_CameraColorRT;
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.RequireDepth))
depthRT = m_CameraDepthRT;
}
SetupRenderTargets(cmd, colorRT, depthRT);
// Clear RenderTarget to avoid tile initialization on mobile GPUs
// https://community.arm.com/graphics/b/blog/posts/mali-performance-2-how-to-correctly-handle-framebuffers
if (m_CurrCamera.clearFlags != CameraClearFlags.Nothing)
{
bool clearDepth = (m_CurrCamera.clearFlags != CameraClearFlags.Nothing);
bool clearColor = (m_CurrCamera.clearFlags == CameraClearFlags.Color || m_CurrCamera.clearFlags == CameraClearFlags.Skybox);
cmd.ClearRenderTarget(clearDepth, clearColor, m_CurrCamera.backgroundColor.linear);
}
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
private void EndForwardRendering(ref ScriptableRenderContext context, FrameRenderingConfiguration renderingConfig)
{
// No additional rendering needs to be done if this is an offscren rendering camera (unless camera is scene view)
if (m_CurrCamera.targetTexture != null && m_CurrCamera.cameraType != CameraType.SceneView)
return;
var cmd = CommandBufferPool.Get("Blit");
if (m_IntermediateTextureArray)
{
cmd.SetRenderTarget(BuiltinRenderTextureType.CameraTarget, 0, CubemapFace.Unknown, -1);
cmd.Blit(m_CameraColorRT, BuiltinRenderTextureType.CurrentActive);
}
else if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.IntermediateTexture))
{
// If PostProcessing is enabled, it is already blit to CameraTarget.
if (!LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.PostProcess))
Blit(cmd, renderingConfig, BuiltinRenderTextureType.CurrentActive, BuiltinRenderTextureType.CameraTarget);
}
SetupRenderTargets(cmd, BuiltinRenderTextureType.CameraTarget, BuiltinRenderTextureType.None);
context.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.Stereo))
{
context.StopMultiEye(m_CurrCamera);
context.StereoEndRender(m_CurrCamera);
}
}
RendererConfiguration GetRendererSettings(ref LightData lightData)
{
RendererConfiguration settings = RendererConfiguration.PerObjectReflectionProbes | RendererConfiguration.PerObjectLightmaps | RendererConfiguration.PerObjectLightProbe;
if (lightData.totalAdditionalLightsCount > 0)
settings |= RendererConfiguration.PerObjectLightIndices8;
return settings;
}
private void SetupRenderTargets(CommandBuffer cmd, RenderTargetIdentifier colorRT, RenderTargetIdentifier depthRT)
{
int depthSlice = (m_IntermediateTextureArray) ? -1 : 0;
if (depthRT != BuiltinRenderTextureType.None)
cmd.SetRenderTarget(colorRT, depthRT, 0, CubemapFace.Unknown, depthSlice);
else
cmd.SetRenderTarget(colorRT, 0, CubemapFace.Unknown, depthSlice);
}
private void RenderPostProcess(CommandBuffer cmd, bool opaqueOnly)
{
m_PostProcessRenderContext.Reset();
m_PostProcessRenderContext.camera = m_CurrCamera;
m_PostProcessRenderContext.source = BuiltinRenderTextureType.CurrentActive;
m_PostProcessRenderContext.sourceFormat = m_ColorFormat;
m_PostProcessRenderContext.destination = BuiltinRenderTextureType.CameraTarget;
m_PostProcessRenderContext.command = cmd;
m_PostProcessRenderContext.flip = true;
if (opaqueOnly)
m_CameraPostProcessLayer.RenderOpaqueOnly(m_PostProcessRenderContext);
else
m_CameraPostProcessLayer.Render(m_PostProcessRenderContext);
}
private int GetLightUnsortedIndex(int index)
{
Debug.Assert(index >= 0 && index < m_SortedLightIndexMap.Count, "Invalid index while accessing light index map. If you only have a single light in scene you should not try to map indices");
return m_SortedLightIndexMap[index];
}
private void Blit(CommandBuffer cmd, FrameRenderingConfiguration renderingConfig, RenderTargetIdentifier sourceRT, RenderTargetIdentifier destRT, Material material = null)
{
if (LightweightUtils.HasFlag(renderingConfig, FrameRenderingConfiguration.DefaultViewport))
{
cmd.Blit(sourceRT, destRT, material);
}
else
{
if (m_BlitQuad == null)
m_BlitQuad = LightweightUtils.CreateQuadMesh(false);
cmd.SetGlobalTexture(m_BlitTexID, sourceRT);
cmd.SetRenderTarget(destRT);
cmd.SetViewport(m_CurrCamera.pixelRect);
cmd.DrawMesh(m_BlitQuad, Matrix4x4.identity, m_BlitMaterial);
}
}
private void CopyTexture(CommandBuffer cmd, RenderTargetIdentifier sourceRT, RenderTargetIdentifier destRT)
{
if (m_CopyTextureSupport != CopyTextureSupport.None)
cmd.CopyTexture(m_CameraDepthRT, m_CameraCopyDepthRT);
else
cmd.Blit(m_CameraDepthRT, m_CameraCopyDepthRT, m_CopyDepthMaterial);
}
}
}

12
ScriptableRenderPipeline/LightweightPipeline/LightweightPipeline.cs.meta


fileFormatVersion: 2
guid: ae13646e45aa3634da32df7c7da1c380
timeCreated: 1481548757
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

37
ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.asset


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: bf2edee5c58d82540a51f03df9d42094, type: 3}
m_Name: LightweightPipelineAsset
m_EditorClassIdentifier:
m_MaxAdditionalPixelLights: 4
m_SupportsVertexLight: 0
m_SupportSoftParticles: 1
m_MSAA: 4
m_RenderScale: 1
m_ShadowType: 1
m_ShadowAtlasResolution: 1024
m_ShadowNearPlaneOffset: 2
m_ShadowDistance: 50
m_ShadowCascades: 1
m_Cascade2Split: 0.25
m_Cascade4Split: {x: 0.067, y: 0.2, z: 0.467}
m_AttenuationTexture: {fileID: 2800000, guid: ee420ad43ff580149a07f10ad66c49ff,
type: 3}
m_DefaultDiffuseMaterial: {fileID: 2100000, guid: 31321ba15b8f8eb4c954353edc038b1d,
type: 2}
m_DefaultParticleMaterial: {fileID: 2100000, guid: e823cd5b5d27c0f4b8256e7c12ee3e6d,
type: 2}
m_DefaultLineMaterial: {fileID: 2100000, guid: 541b04d3bf488324f816937313973e15,
type: 2}
m_DefaultSpriteMaterial: {fileID: 2100000, guid: e3ef893926d86c448a80512fe05b8a37,
type: 2}
m_DefaultUIMaterial: {fileID: 2100000, guid: 786cc499ea3906946b10ab7d24c8d0e7, type: 2}
m_DefaultShader: {fileID: 4800000, guid: 933532a4fcc9baf4fa0491de14d08ed7, type: 3}

9
ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.asset.meta


fileFormatVersion: 2
guid: e6987eea1dd29074597d54ed91a54a26
timeCreated: 1489068733
licenseType: Pro
NativeFormatImporter:
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

227
ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.cs


namespace UnityEngine.Experimental.Rendering.LightweightPipeline
{
public enum ShadowCascades
{
NO_CASCADES = 1,
TWO_CASCADES = 2,
FOUR_CASCADES = 4,
}
public enum ShadowType
{
NO_SHADOW = 0,
HARD_SHADOWS,
SOFT_SHADOWS,
}
public enum ShadowResolution
{
_512 = 512,
_1024 = 1024,
_2048 = 2048
}
public enum MSAAQuality
{
Disabled = 1,
_2x = 2,
_4x = 4,
_8x = 8
}
public class LightweightPipelineAsset : RenderPipelineAsset
{
public static readonly string m_SimpleLightShaderPath = "LightweightPipeline/Standard (Simple Lighting)";
public static readonly string m_StandardShaderPath = "LightweightPipeline/Standard (Physically Based)";
public static readonly string m_BlitShaderPath = "Hidden/LightweightPipeline/Blit";
public static readonly string m_CopyDephPath = "Hidden/LightweightPipeline/CopyDepth";
private static readonly string m_PipelineFolder = "Assets/LightweightPipeline";
private static readonly string m_AssetName = "LightweightPipelineAsset.asset";
[SerializeField] private int m_MaxAdditionalPixelLights = 1;
[SerializeField] private bool m_SupportsVertexLight = true;
[SerializeField] private bool m_SupportSoftParticles = false;
[SerializeField] private MSAAQuality m_MSAA = MSAAQuality.Disabled;
[SerializeField] private float m_RenderScale = 1.0f;
[SerializeField] private ShadowType m_ShadowType = ShadowType.HARD_SHADOWS;
[SerializeField] private ShadowResolution m_ShadowAtlasResolution = ShadowResolution._1024;
[SerializeField] private float m_ShadowNearPlaneOffset = 2.0f;
[SerializeField] private float m_ShadowDistance = 50.0f;
[SerializeField] private ShadowCascades m_ShadowCascades = ShadowCascades.NO_CASCADES;
[SerializeField] private float m_Cascade2Split = 0.25f;
[SerializeField] private Vector3 m_Cascade4Split = new Vector3(0.067f, 0.2f, 0.467f);
[SerializeField] private Texture2D m_AttenuationTexture;
[SerializeField] private Material m_DefaultDiffuseMaterial;
[SerializeField] private Material m_DefaultParticleMaterial;
[SerializeField] private Material m_DefaultLineMaterial;
[SerializeField] private Material m_DefaultSpriteMaterial;
[SerializeField] private Material m_DefaultUIMaterial;
[SerializeField] private Shader m_DefaultShader;
#if UNITY_EDITOR
[UnityEditor.MenuItem("RenderPipeline/Lightweight Pipeline/Create Pipeline Asset", false, 15)]
static void CreateLightweightPipeline()
{
var instance = ScriptableObject.CreateInstance<LightweightPipelineAsset>();
string[] paths = m_PipelineFolder.Split('/');
string currentPath = paths[0];
for (int i = 1; i < paths.Length; ++i)
{
string folder = currentPath + "/" + paths[i];
if (!UnityEditor.AssetDatabase.IsValidFolder(folder))
UnityEditor.AssetDatabase.CreateFolder(currentPath, paths[i]);
currentPath = folder;
}
UnityEditor.AssetDatabase.CreateAsset(instance, m_PipelineFolder + "/" + m_AssetName);
}
#endif
protected override IRenderPipeline InternalCreatePipeline()
{
return new LightweightPipeline(this);
}
void OnValidate()
{
DestroyCreatedInstances();
}
public bool AreShadowsEnabled()
{
return ShadowSetting != ShadowType.NO_SHADOW;
}
public int MaxAdditionalPixelLights
{
get { return m_MaxAdditionalPixelLights; }
}
public bool SupportsVertexLight
{
get { return m_SupportsVertexLight; }
}
public bool SupportsSoftParticles
{
get { return m_SupportSoftParticles; }
}
public int MSAASampleCount
{
get { return (int)m_MSAA; }
set { m_MSAA = (MSAAQuality)value; }
}
public float RenderScale
{
get { return m_RenderScale; }
set { m_RenderScale = value; }
}
public ShadowType ShadowSetting
{
get { return m_ShadowType; }
private set { m_ShadowType = value; }
}
public int ShadowAtlasResolution
{
get { return (int)m_ShadowAtlasResolution; }
private set { m_ShadowAtlasResolution = (ShadowResolution)value; }
}
public float ShadowNearOffset
{
get { return m_ShadowNearPlaneOffset; }
private set { m_ShadowNearPlaneOffset = value; }
}
public float ShadowDistance
{
get { return m_ShadowDistance; }
private set { m_ShadowDistance = value; }
}
public int CascadeCount
{
get { return (int)m_ShadowCascades; }
private set { m_ShadowCascades = (ShadowCascades)value; }
}
public float Cascade2Split
{
get { return m_Cascade2Split; }
private set { m_Cascade2Split = value; }
}
public Vector3 Cascade4Split
{
get { return m_Cascade4Split; }
private set { m_Cascade4Split = value; }
}
public Texture2D AttenuationTexture
{
get { return m_AttenuationTexture; }
set { m_AttenuationTexture = value; }
}
public override Material GetDefaultMaterial()
{
return m_DefaultDiffuseMaterial;
}
public override Material GetDefaultParticleMaterial()
{
return m_DefaultParticleMaterial;
}
public override Material GetDefaultLineMaterial()
{
return m_DefaultLineMaterial;
}
public override Material GetDefaultTerrainMaterial()
{
return m_DefaultDiffuseMaterial;
}
public override Material GetDefaultUIMaterial()
{
return m_DefaultUIMaterial;
}
public override Material GetDefaultUIOverdrawMaterial()
{
return m_DefaultDiffuseMaterial;
}
public override Material GetDefaultUIETC1SupportedMaterial()
{
return m_DefaultDiffuseMaterial;
}
public override Material GetDefault2DMaterial()
{
return m_DefaultSpriteMaterial;
}
public override Shader GetDefaultShader()
{
return m_DefaultShader;
}
public Shader BlitShader
{
get { return Shader.Find(LightweightPipelineAsset.m_BlitShaderPath); }
}
public Shader CopyDepthShader
{
get { return Shader.Find(LightweightPipelineAsset.m_CopyDephPath); }
}
}
}

12
ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineAsset.cs.meta


fileFormatVersion: 2
guid: bf2edee5c58d82540a51f03df9d42094
timeCreated: 1488808083
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

136
ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineUtils.cs


using System;
using System.Collections.Generic;
using UnityEngine.Rendering;
namespace UnityEngine.Experimental.Rendering.LightweightPipeline
{
public class CameraComparer : IComparer<Camera>
{
public int Compare(Camera lhs, Camera rhs)
{
return (int)(lhs.depth - rhs.depth);
}
}
public class LightComparer : IComparer<VisibleLight>
{
public Camera CurrCamera { get; set; }
// Sorts on the following priority:
// Directionals have priority over local lights
// ShadowLight type
// Has Cookie
// Intensity if Directional, Distance to camera otherwise
public int Compare(VisibleLight lhs, VisibleLight rhs)
{
Light lhsLight = lhs.light;
Light rhsLight = rhs.light;
if (lhs.lightType != rhs.lightType)
{
if (lhs.lightType == LightType.Directional) return -1;
if (rhs.lightType == LightType.Directional) return 1;
}
// Particle Lights have the Light reference set to null
// They are at the end of the priority
if (lhsLight == null) return 1;
if (rhsLight == null) return -1;
// In the following priority: Soft, Hard, None
if (lhsLight.shadows != rhsLight.shadows)
return (int)rhsLight.shadows - (int)lhsLight.shadows;
if (lhsLight.cookie != rhsLight.cookie)
return (lhsLight.cookie != null) ? -1 : 1;
if (lhs.lightType == LightType.Directional)
return (int)(lhsLight.intensity*100.0f) - (int)(rhsLight.intensity*100.0f);
else
return (int)(SquaredDistanceToCamera(lhsLight.transform.position) - SquaredDistanceToCamera(rhsLight.transform.position));
}
public float SquaredDistanceToCamera(Vector3 lightPos)
{
Vector3 lightCameraVector = lightPos - CurrCamera.transform.position;
return Vector3.Dot(lightCameraVector, lightCameraVector);
}
}
[Flags]
public enum FrameRenderingConfiguration
{
None = 0,
Stereo = (1 << 0),
Msaa = (1 << 1),
PostProcess = (1 << 2),
RequireDepth = (1 << 3),
DefaultViewport = (1 << 4),
IntermediateTexture = (1 << 5),
}
public static class LightweightUtils
{
public static void SetKeyword(CommandBuffer cmd, string keyword, bool enable)
{
if (enable)
cmd.EnableShaderKeyword(keyword);
else
cmd.DisableShaderKeyword(keyword);
}
public static bool IsSupportedShadowType(LightType lightType)
{
return lightType == LightType.Directional || lightType == LightType.Spot;
}
public static bool PlatformSupportsMSAABackBuffer()
{
#if UNITY_ANDROID || UNITY_IPHONE || UNITY_TVOS || UNITY_SAMSUNGTV
return true;
#else
return false;
#endif
}
public static bool HasFlag(FrameRenderingConfiguration mask, FrameRenderingConfiguration flag)
{
return (mask & flag) != 0;
}
public static Mesh CreateQuadMesh(bool uvStartsAtTop)
{
float topV, bottomV;
if (uvStartsAtTop)
{
topV = 0.0f;
bottomV = 1.0f;
}
else
{
topV = 1.0f;
bottomV = 0.0f;
}
Mesh mesh = new Mesh();
mesh.vertices = new Vector3[]
{
new Vector3(-1.0f, -1.0f, 0.0f),
new Vector3(-1.0f, 1.0f, 0.0f),
new Vector3( 1.0f, -1.0f, 0.0f),
new Vector3( 1.0f, 1.0f, 0.0f)
};
mesh.uv = new Vector2[]
{
new Vector2(0.0f, bottomV),
new Vector2(0.0f, topV),
new Vector2(1.0f, bottomV),
new Vector2(1.0f, topV)
};
mesh.triangles = new int[] { 0, 1, 2, 2, 1, 3 };
return mesh;
}
}
}

13
ScriptableRenderPipeline/LightweightPipeline/LightweightPipelineUtils.cs.meta


fileFormatVersion: 2
guid: 1556a6d19597541c8bed4b90c704fb06
timeCreated: 1505115136
licenseType: Free
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

9
ScriptableRenderPipeline/LightweightPipeline/Materials.meta


fileFormatVersion: 2
guid: bc5fccbcb91216745b747fafd8514a24
folderAsset: yes
timeCreated: 1496317987
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

79
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultETC1.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Lightweight-DefaultETC1
m_Shader: {fileID: 4800000, guid: 8d2bb70cbf9db8d4da26e15b26e74248, type: 3}
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Cube:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossinessSource: 0
- _GlossyReflections: 1
- _Mode: 0
- _Parallax: 0.02
- _ReflectionSource: 0
- _Shininess: 1
- _SmoothnessTextureChannel: 0
- _SpecSource: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _SpecColor: {r: 1, g: 1, b: 1, a: 1}

10
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultETC1.mat.meta


fileFormatVersion: 2
guid: 77da5f76bec40af47be3a3b79da0e81c
timeCreated: 1499350842
licenseType: Pro
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

76
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultLine.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Lightweight-DefaultLine
m_Shader: {fileID: 46, guid: 0000000000000000f000000000000000, type: 0}
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossyReflections: 1
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}

10
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultLine.mat.meta


fileFormatVersion: 2
guid: 541b04d3bf488324f816937313973e15
timeCreated: 1499342258
licenseType: Pro
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

10
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultParticle.mat.meta


fileFormatVersion: 2
guid: e823cd5b5d27c0f4b8256e7c12ee3e6d
timeCreated: 1499342173
licenseType: Pro
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

87
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultSprite.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Lightweight-DefaultSprite
m_Shader: {fileID: 10753, guid: 0000000000000000f000000000000000, type: 0}
m_ShaderKeywords: ETC1_EXTERNAL_ALPHA
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _AlphaTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Cube:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- PixelSnap: 0
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _EnableExternalAlpha: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossinessSource: 0
- _GlossyReflections: 1
- _Mode: 0
- _Parallax: 0.02
- _ReflectionSource: 0
- _Shininess: 1
- _SmoothnessTextureChannel: 0
- _SpecSource: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _Flip: {r: 1, g: 1, b: 1, a: 1}
- _RendererColor: {r: 1, g: 1, b: 1, a: 1}
- _SpecColor: {r: 1, g: 1, b: 1, a: 1}

9
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultSprite.mat.meta


fileFormatVersion: 2
guid: e3ef893926d86c448a80512fe05b8a37
timeCreated: 1496318020
licenseType: Pro
NativeFormatImporter:
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

86
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultUI.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Lightweight-DefaultUI
m_Shader: {fileID: 10770, guid: 0000000000000000f000000000000000, type: 0}
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Cube:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _ColorMask: 15
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossinessSource: 0
- _GlossyReflections: 1
- _Mode: 0
- _Parallax: 0.02
- _ReflectionSource: 0
- _Shininess: 1
- _SmoothnessTextureChannel: 0
- _SpecSource: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _Stencil: 0
- _StencilComp: 8
- _StencilOp: 0
- _StencilReadMask: 255
- _StencilWriteMask: 255
- _UVSec: 0
- _UseUIAlphaClip: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _SpecColor: {r: 1, g: 1, b: 1, a: 1}

10
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultUI.mat.meta


fileFormatVersion: 2
guid: 786cc499ea3906946b10ab7d24c8d0e7
timeCreated: 1499329524
licenseType: Pro
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

10
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-StandardShader.mat.meta


fileFormatVersion: 2
guid: 31321ba15b8f8eb4c954353edc038b1d
timeCreated: 1503473114
licenseType: Pro
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

77
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-DefaultParticle.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Lightweight-DefaultParticle
m_Shader: {fileID: 202, guid: 0000000000000000f000000000000000, type: 0}
m_ShaderKeywords:
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 10300, guid: 0000000000000000f000000000000000, type: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossyReflections: 1
- _InvFade: 1
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _SmoothnessTextureChannel: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}

94
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-StandardShader.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Lightweight-StandardShader
m_Shader: {fileID: 4800000, guid: 933532a4fcc9baf4fa0491de14d08ed7, type: 3}
m_ShaderKeywords: _METALLIC_SETUP
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Cube:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MetallicSpecGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _OcclusionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossinessSource: 0
- _GlossyReflections: 1
- _Metallic: 0
- _Mode: 0
- _OcclusionStrength: 1
- _Parallax: 0.02
- _ReflectionSource: 0
- _Shininess: 1
- _SmoothnessTextureChannel: 0
- _SpecSource: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _WorkflowMode: 1
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _SpecColor: {r: 1, g: 1, b: 1, a: 1}

9
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-StandardSimpleLighting.mat.meta


fileFormatVersion: 2
guid: 6a1143ee683302f4aa628c052723efc1
timeCreated: 1496318109
licenseType: Pro
NativeFormatImporter:
mainObjectFileID: 2100000
userData:
assetBundleName:
assetBundleVariant:

79
ScriptableRenderPipeline/LightweightPipeline/Materials/Lightweight-StandardSimpleLighting.mat


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
serializedVersion: 6
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_Name: Lightweight-StandardSimpleLighting
m_Shader: {fileID: 4800000, guid: 8d2bb70cbf9db8d4da26e15b26e74248, type: 3}
m_ShaderKeywords: _GLOSSINESS_FROM_BASE_ALPHA _SPECULAR_COLOR
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
- _BumpMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Cube:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailAlbedoMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailMask:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _DetailNormalMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _EmissionMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _MainTex:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _ParallaxMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _SpecGlossMap:
m_Texture: {fileID: 0}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats:
- _BumpScale: 1
- _Cutoff: 0.5
- _DetailNormalMapScale: 1
- _DstBlend: 0
- _GlossMapScale: 1
- _Glossiness: 0.5
- _GlossinessSource: 0
- _GlossyReflections: 1
- _Mode: 0
- _Parallax: 0.02
- _ReflectionSource: 0
- _Shininess: 0.15
- _SmoothnessTextureChannel: 0
- _SpecSource: 0
- _SpecularHighlights: 1
- _SrcBlend: 1
- _UVSec: 0
- _ZWrite: 1
m_Colors:
- _Color: {r: 1, g: 1, b: 1, a: 1}
- _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
- _SpecColor: {r: 1, g: 1, b: 1, a: 1}

9
ScriptableRenderPipeline/LightweightPipeline/Shaders.meta


fileFormatVersion: 2
guid: 81841919e91d4b24ba3a6ca4a5167bce
folderAsset: yes
timeCreated: 1490023078
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

46
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightBlit.shader


Shader "Hidden/LightweightPipeline/Blit"
{
SubShader
{
Tags { "RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline"}
LOD 100
Pass
{
Tags { "LightMode" = "LightweightForward"}
CGPROGRAM
#pragma vertex Vertex
#pragma fragment Fragment
struct VertexInput
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct VertexOutput
{
half4 pos : SV_POSITION;
half2 uv : TEXCOORD0;
};
sampler2D _BlitTex;
VertexOutput Vertex(VertexInput i)
{
VertexOutput o;
o.pos = half4(i.vertex.xyz, 1.0);
o.uv = i.uv;
return o;
}
fixed4 Fragment(VertexOutput i) : SV_Target
{
fixed4 col = tex2D(_BlitTex, i.uv);
return col;
}
ENDCG
}
}
}

10
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightBlit.shader.meta


fileFormatVersion: 2
guid: c17132b1f77d20942aa75f8429c0f8bc
timeCreated: 1505729520
licenseType: Pro
ShaderImporter:
externalObjects: {}
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

46
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightCopyDepth.shader


Shader "Hidden/LightweightPipeline/CopyDepth"
{
SubShader
{
Tags { "RenderType" = "Opaque" "RenderPipeline" = "LightiweightPipeline"}
Pass
{
ColorMask 0
ZTest Always
ZWrite On
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
sampler2D_float _CameraDepthTexture;
struct VertexInput
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct VertexOutput
{
float4 position : SV_POSITION;
float2 uv : TEXCOORD0;
};
VertexOutput vert(VertexInput i)
{
VertexOutput o;
o.uv = i.uv;
o.position = UnityObjectToClipPos(i.vertex);
return o;
}
float frag(VertexOutput i) : SV_Depth
{
return tex2D(_CameraDepthTexture, i.uv).r;
}
ENDCG
}
}
}

10
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightCopyDepth.shader.meta


fileFormatVersion: 2
guid: d6dae50ee9e1bfa4db75f19f99355220
timeCreated: 1506692614
licenseType: Pro
ShaderImporter:
externalObjects: {}
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

185
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightCore.cginc


#ifndef LIGHTWEIGHT_PIPELINE_CORE_INCLUDED
#define LIGHTWEIGHT_PIPELINE_CORE_INCLUDED
#include "UnityCG.cginc"
#define MAX_VISIBLE_LIGHTS 16
#if defined(UNITY_COLORSPACE_GAMMA)
#define LIGHTWEIGHT_GAMMA_TO_LINEAR(gammaColor) gammaColor * gammaColor
#define LIGHTWEIGHT_LINEAR_TO_GAMMA(linColor) sqrt(color)
#else
#define LIGHTWEIGHT_GAMMA_TO_LINEAR(color) color
#define LIGHTWEIGHT_LINEAR_TO_GAMMA(color) color
#endif
#ifdef _SPECULAR_SETUP
#define SAMPLE_METALLICSPECULAR(uv) tex2D(_SpecGlossMap, uv)
#else
#define SAMPLE_METALLICSPECULAR(uv) tex2D(_MetallicGlossMap, uv)
#endif
CBUFFER_START(_PerObject)
half4 unity_LightIndicesOffsetAndCount;
half4 unity_4LightIndices0;
half4 unity_4LightIndices1;
half _Shininess;
CBUFFER_END
CBUFFER_START(_PerCamera)
float4 _MainLightPosition;
half4 _MainLightColor;
float4 _MainLightAttenuationParams;
half4 _MainLightSpotDir;
half4 _AdditionalLightCount;
float4 _AdditionalLightPosition[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightColor[MAX_VISIBLE_LIGHTS];
float4 _AdditionalLightAttenuationParams[MAX_VISIBLE_LIGHTS];
half4 _AdditionalLightSpotDir[MAX_VISIBLE_LIGHTS];
CBUFFER_END
CBUFFER_START(_PerFrame)
half4 _GlossyEnvironmentColor;
sampler2D _AttenuationTexture;
CBUFFER_END
half3 TangentToWorldNormal(half3 normalTangent, half3 tangent, half3 binormal, half3 normal)
{
half3x3 tangentToWorld = half3x3(tangent, binormal, normal);
return normalize(mul(normalTangent, tangentToWorld));
}
float ComputeFogFactor(float z)
{
float clipZ_01 = UNITY_Z_0_FAR_FROM_CLIPSPACE(z);
#if defined(FOG_LINEAR)
// factor = (end-z)/(end-start) = z * (-1/(end-start)) + (end/(end-start))
float fogFactor = saturate(clipZ_01 * unity_FogParams.z + unity_FogParams.w);
return half(fogFactor);
#elif defined(FOG_EXP)
// factor = exp(-density*z)
float unityFogFactor = unity_FogParams.y * clipZ_01;
return half(saturate(exp2(-unityFogFactor)));
#elif defined(FOG_EXP2)
// factor = exp(-(density*z)^2)
float unityFogFactor = unity_FogParams.x * clipZ_01;
return half(saturate(exp2(-unityFogFactor*unityFogFactor)));
#else
return 0.0h;
#endif
}
void ApplyFog(inout half3 color, half fogFactor)
{
#if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)
color = lerp(unity_FogColor, color, fogFactor);
#endif
}
half4 OutputColor(half3 color, half alpha)
{
#if defined(_ALPHABLEND_ON) || defined(_ALPHAPREMULTIPLY_ON)
return half4(LIGHTWEIGHT_LINEAR_TO_GAMMA(color), alpha);
#else
return half4(LIGHTWEIGHT_LINEAR_TO_GAMMA(color), 1);
#endif
}
inline half Alpha(half albedoAlpha)
{
#if defined(_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A)
half alpha = _Color.a;
#else
half alpha = albedoAlpha * _Color.a;
#endif
#if defined(_ALPHATEST_ON)
clip(alpha - _Cutoff);
#endif
return alpha;
}
half3 Normal(float2 uv)
{
#if _NORMALMAP
return UnpackNormal(tex2D(_BumpMap, uv));
#else
return half3(0.0h, 0.0h, 1.0h);
#endif
}
inline void SpecularGloss(half2 uv, half alpha, out half4 specularGloss)
{
specularGloss = half4(0, 0, 0, 1);
#ifdef _SPECGLOSSMAP
specularGloss = tex2D(_SpecGlossMap, uv);
specularGloss.rgb = LIGHTWEIGHT_GAMMA_TO_LINEAR(specularGloss.rgb);
#elif defined(_SPECULAR_COLOR)
specularGloss = _SpecColor;
#endif
#ifdef _GLOSSINESS_FROM_BASE_ALPHA
specularGloss.a = alpha;
#endif
}
half4 MetallicSpecGloss(float2 uv, half albedoAlpha)
{
half4 specGloss;
#ifdef _METALLICSPECGLOSSMAP
specGloss = specGloss = SAMPLE_METALLICSPECULAR(uv);
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
specGloss.a = albedoAlpha * _GlossMapScale;
#else
specGloss.a *= _GlossMapScale;
#endif
#else // _METALLICSPECGLOSSMAP
#if _METALLIC_SETUP
specGloss.rgb = _Metallic.rrr;
#else
specGloss.rgb = _SpecColor.rgb;
#endif
#ifdef _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
specGloss.a = albedoAlpha * _GlossMapScale;
#else
specGloss.a = _Glossiness;
#endif
#endif
return specGloss;
}
half OcclusionLW(float2 uv)
{
#ifdef _OCCLUSIONMAP
#if (SHADER_TARGET < 30)
// SM20: instruction count limitation
// SM20: simpler occlusion
return tex2D(_OcclusionMap, uv).g;
#else
half occ = tex2D(_OcclusionMap, uv).g;
return LerpOneTo(occ, _OcclusionStrength);
#endif
#else
return 1.0;
#endif
}
half3 EmissionLW(float2 uv)
{
#ifndef _EMISSION
return 0;
#else
return LIGHTWEIGHT_GAMMA_TO_LINEAR(tex2D(_EmissionMap, uv).rgb) * _EmissionColor.rgb;
#endif
}
#endif

9
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightCore.cginc.meta


fileFormatVersion: 2
guid: 53686bf58189656459fca4c6ab04ebe5
timeCreated: 1488965025
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

320
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightLighting.cginc


#ifndef LIGHTWEIGHT_LIGHTING_INCLUDED
#define LIGHTWEIGHT_LIGHTING_INCLUDED
#include "LightweightCore.cginc"
#include "LightweightShadows.cginc"
#define PI 3.14159265359f
#define kDieletricSpec half4(0.04, 0.04, 0.04, 1.0 - 0.04) // standard dielectric reflectivity coef at incident angle (= 4%)
// Main light initialized without indexing
#define INITIALIZE_MAIN_LIGHT(light) \
light.pos = _MainLightPosition; \
light.color = _MainLightColor; \
light.atten = _MainLightAttenuationParams; \
light.spotDir = _MainLightSpotDir;
// Indexing might have a performance hit for old mobile hardware
#define INITIALIZE_LIGHT(light, i) \
half4 indices = (i < 4) ? unity_4LightIndices0 : unity_4LightIndices1; \
int index = (i < 4) ? i : i - 4; \
int lightIndex = indices[index]; \
light.pos = _AdditionalLightPosition[lightIndex]; \
light.color = _AdditionalLightColor[lightIndex]; \
light.atten = _AdditionalLightAttenuationParams[lightIndex]; \
light.spotDir = _AdditionalLightSpotDir[lightIndex]
struct LightInput
{
float4 pos;
half4 color;
float4 atten;
half4 spotDir;
};
struct SurfaceData
{
half3 albedo;
half3 specular;
half metallic;
half smoothness;
half3 normal;
half3 emission;
half occlusion;
half alpha;
};
struct SurfaceInput
{
float4 lightmapUV;
half3 normalWS;
half3 tangentWS;
half3 bitangentWS;
float3 positionWS;
half3 viewDirectionWS;
half fogFactor;
};
struct BRDFData
{
half3 diffuse;
half3 specular;
half perceptualRoughness;
half roughness;
half grazingTerm;
};
inline void InitializeSurfaceData(out SurfaceData outSurfaceData)
{
outSurfaceData.albedo = half3(1.0h, 1.0h, 1.0h);
outSurfaceData.specular = half3(0.0h, 0.0h, 0.0h);
outSurfaceData.metallic = 1.0h;
outSurfaceData.smoothness = 0.5h;
outSurfaceData.normal = half3(0.0h, 0.0h, 1.0h);
outSurfaceData.occlusion = 1.0h;
outSurfaceData.emission = half3(0.0h, 0.0h, 0.0h);
outSurfaceData.alpha = 1.0h;
}
half SpecularReflectivity(half3 specular)
{
#if (SHADER_TARGET < 30)
// SM2.0: instruction count limitation
// SM2.0: simplified SpecularStrength
return specular.r; // Red channel - because most metals are either monocrhome or with redish/yellowish tint
#else
return max(max(specular.r, specular.g), specular.b);
#endif
}
inline void InitializeBRDFData(half3 albedo, half metallic, half3 specular, half smoothness, half alpha, out BRDFData outBRDFData)
{
// BRDF SETUP
#ifdef _METALLIC_SETUP
// We'll need oneMinusReflectivity, so
// 1-reflectivity = 1-lerp(dielectricSpec, 1, metallic) = lerp(1-dielectricSpec, 0, metallic)
// store (1-dielectricSpec) in kDieletricSpec.a, then
// 1-reflectivity = lerp(alpha, 0, metallic) = alpha + metallic*(0 - alpha) =
// = alpha - metallic * alpha
half oneMinusDielectricSpec = kDieletricSpec.a;
half oneMinusReflectivity = oneMinusDielectricSpec - metallic * oneMinusDielectricSpec;
half reflectivity = 1.0 - oneMinusReflectivity;
outBRDFData.diffuse = albedo * oneMinusReflectivity;
outBRDFData.specular = lerp(kDieletricSpec.rgb, albedo, metallic);
#else
half reflectivity = SpecularReflectivity(specular);
outBRDFData.diffuse = albedo * (half3(1.0h, 1.0h, 1.0h) - specular);
outBRDFData.specular = specular;
#endif
outBRDFData.grazingTerm = saturate(smoothness + reflectivity);
outBRDFData.perceptualRoughness = 1.0h - smoothness;
outBRDFData.roughness = outBRDFData.perceptualRoughness * outBRDFData.perceptualRoughness;
#ifdef _ALPHAPREMULTIPLY_ON
outBRDFData.diffuse *= alpha;
alpha = reflectivity + alpha * (1.0 - reflectivity);
#endif
}
// Based on Minimalist CookTorrance BRDF
// Implementation is slightly different from original derivation: http://www.thetenthplanet.de/archives/255
//
// * NDF [Modified] GGX
// * Modified Kelemen and Szirmay-​Kalos for Visibility term
// * Fresnel approximated with 1/LdotH
half3 LightweightBDRF(BRDFData brdfData, half roughness2, half3 normal, half3 lightDirection, half3 viewDir)
{
#ifndef _SPECULARHIGHLIGHTS_OFF
half3 halfDir = Unity_SafeNormalize(lightDirection + viewDir);
half NoH = saturate(dot(normal, halfDir));
half LoH = saturate(dot(lightDirection, halfDir));
// GGX Distribution multiplied by combined approximation of Visibility and Fresnel
// See "Optimizing PBR for Mobile" from Siggraph 2015 moving mobile graphics course
// https://community.arm.com/events/1155
half d = NoH * NoH * (roughness2 - 1.h) + 1.00001h;
half LoH2 = LoH * LoH;
half specularTerm = roughness2 / ((d * d) * max(0.1h, LoH2) * (brdfData.roughness + 0.5h) * 4);
// on mobiles (where half actually means something) denominator have risk of overflow
// clamp below was added specifically to "fix" that, but dx compiler (we convert bytecode to metal/gles)
// sees that specularTerm have only non-negative terms, so it skips max(0,..) in clamp (leaving only min(100,...))
#if defined (SHADER_API_MOBILE)
specularTerm = specularTerm - 1e-4h;
#endif
#if defined (SHADER_API_MOBILE)
specularTerm = clamp(specularTerm, 0.0, 100.0); // Prevent FP16 overflow on mobiles
#endif
half3 color = specularTerm * brdfData.specular + brdfData.diffuse;
return color;
#else
return brdfData.diffuse;
#endif
}
half3 LightweightBRDFIndirect(BRDFData brdfData, UnityIndirect indirect, half roughness2, half fresnelTerm)
{
half3 c = indirect.diffuse * brdfData.diffuse;
float surfaceReduction = 1.0 / (roughness2 + 1.0);
c += surfaceReduction * indirect.specular * lerp(brdfData.specular, brdfData.grazingTerm, fresnelTerm);
return c;
}
UnityIndirect LightweightGI(float4 lightmapUV, half3 normalWorld, half3 reflectVec, half occlusion, half perceptualRoughness)
{
UnityIndirect o = (UnityIndirect)0;
#ifdef LIGHTMAP_ON
o.diffuse += (DecodeLightmap(UNITY_SAMPLE_TEX2D(unity_Lightmap, lightmapUV.xy))) * occlusion;
#else
o.diffuse = ShadeSH9(half4(normalWorld, 1.0)) * occlusion;
#endif
#ifndef _GLOSSYREFLECTIONS_OFF
Unity_GlossyEnvironmentData g;
g.roughness = perceptualRoughness;
g.reflUVW = reflectVec;
o.specular = Unity_GlossyEnvironment(UNITY_PASS_TEXCUBE(unity_SpecCube0), unity_SpecCube0_HDR, g) * occlusion;
#else
o.specular = _GlossyEnvironmentColor * occlusion;
#endif
return o;
}
half SpotAttenuation(half3 spotDirection, half3 lightDirection, float4 attenuationParams)
{
// Spot Attenuation with a linear falloff can be defined as
// (SdotL - cosOuterAngle) / (cosInnerAngle - cosOuterAngle)
// This can be rewritten as
// invAngleRange = 1.0 / (cosInnerAngle - cosOuterAngle)
// SdotL * invAngleRange + (-cosOuterAngle * invAngleRange)
// If we precompute the terms in a MAD instruction
half SdotL = dot(spotDirection, lightDirection);
// attenuationParams.x = invAngleRange
// attenuationParams.y = (-cosOuterAngle invAngleRange)
return saturate(SdotL * attenuationParams.x + attenuationParams.y);
}
// In per-vertex falloff there's no smooth falloff to light range. A hard cut will be noticed
inline half ComputeVertexLightAttenuation(LightInput lightInput, half3 normal, float3 worldPos, out half3 lightDirection)
{
float4 attenuationParams = lightInput.atten;
float3 posToLightVec = lightInput.pos - worldPos * lightInput.pos.w;
float distanceSqr = max(dot(posToLightVec, posToLightVec), 0.001);
// normalized light dir
lightDirection = half3(posToLightVec * rsqrt(distanceSqr));
// attenuationParams.z = kQuadFallOff = (25.0) / (lightRange * lightRange)
// attenuationParams.w = lightRange * lightRange
half lightAtten = half(1.0 / (1.0 + distanceSqr * attenuationParams.z));
lightAtten *= SpotAttenuation(lightInput.spotDir.xyz, lightDirection, attenuationParams);
return lightAtten;
}
// In per-pixel falloff attenuation smoothly decreases to light range.
inline half ComputePixelLightAttenuation(LightInput lightInput, half3 normal, float3 worldPos, out half3 lightDirection)
{
float4 attenuationParams = lightInput.atten;
float3 posToLightVec = lightInput.pos.xyz - worldPos * lightInput.pos.w;
float distanceSqr = max(dot(posToLightVec, posToLightVec), 0.001);
// normalized light dir
lightDirection = half3(posToLightVec * rsqrt(distanceSqr));
float u = (distanceSqr * attenuationParams.z) / attenuationParams.w;
half lightAtten = tex2D(_AttenuationTexture, float2(u, 0.0)).a;
lightAtten *= SpotAttenuation(lightInput.spotDir.xyz, lightDirection, attenuationParams);
return lightAtten;
}
inline half ComputeMainLightAttenuation(LightInput lightInput, half3 normal, float3 worldPos, out half3 lightDirection)
{
#ifdef _MAIN_DIRECTIONAL_LIGHT
// Light pos holds normalized light dir
lightDirection = lightInput.pos;
return 1.0;
#else
return ComputePixelLightAttenuation(lightInput, normal, worldPos, lightDirection);
#endif
}
inline half3 LightingLambert(half3 diffuseColor, half3 lightDir, half3 normal, half atten)
{
half NdotL = saturate(dot(normal, lightDir));
return diffuseColor * (NdotL * atten);
}
inline half3 LightingBlinnPhong(half3 diffuseColor, half4 specularGloss, half3 lightDir, half3 normal, half3 viewDir, half atten)
{
half NdotL = saturate(dot(normal, lightDir));
half3 diffuse = diffuseColor * NdotL;
half3 halfVec = normalize(lightDir + viewDir);
half NdotH = saturate(dot(normal, halfVec));
half3 specular = specularGloss.rgb * pow(NdotH, _Shininess * 128.0) * specularGloss.a;
return (diffuse + specular) * atten;
}
half4 LightweightFragmentPBR(half4 lightmapUV, float3 positionWS, half3 normalWS, half3 tangentWS, half3 bitangentWS,
half3 viewDirectionWS, half fogFactor, half3 albedo, half metallic, half3 specular, half smoothness,
half3 normalTS, half ambientOcclusion, half3 emission, half alpha)
{
BRDFData brdfData;
InitializeBRDFData(albedo, metallic, specular, smoothness, alpha, brdfData);
half3 vertexNormal = normalWS;
#if _NORMALMAP
normalWS = TangentToWorldNormal(normalTS, tangentWS, bitangentWS, normalWS);
#else
normalWS = normalize(normalWS);
#endif
half3 reflectVec = reflect(-viewDirectionWS, normalWS);
half roughness2 = brdfData.roughness * brdfData.roughness;
UnityIndirect indirectLight = LightweightGI(lightmapUV, normalWS, reflectVec, ambientOcclusion, brdfData.perceptualRoughness);
// PBS
half fresnelTerm = Pow4(1.0 - saturate(dot(normalWS, viewDirectionWS)));
half3 color = LightweightBRDFIndirect(brdfData, indirectLight, roughness2, fresnelTerm);
half3 lightDirectionWS;
LightInput light;
INITIALIZE_MAIN_LIGHT(light);
half lightAtten = ComputeMainLightAttenuation(light, normalWS, positionWS, lightDirectionWS);
lightAtten *= LIGHTWEIGHT_SHADOW_ATTENUATION(positionWS, normalize(vertexNormal), _ShadowLightDirection.xyz);
half NdotL = saturate(dot(normalWS, lightDirectionWS));
half3 radiance = light.color * (lightAtten * NdotL);
color += LightweightBDRF(brdfData, roughness2, normalWS, lightDirectionWS, viewDirectionWS) * radiance;
#ifdef _ADDITIONAL_LIGHTS
int pixelLightCount = min(_AdditionalLightCount.x, unity_LightIndicesOffsetAndCount.y);
for (int lightIter = 0; lightIter < pixelLightCount; ++lightIter)
{
LightInput light;
INITIALIZE_LIGHT(light, lightIter);
half lightAtten = ComputePixelLightAttenuation(light, normalWS, positionWS, lightDirectionWS);
half NdotL = saturate(dot(normalWS, lightDirectionWS));
half3 radiance = light.color * (lightAtten * NdotL);
color += LightweightBDRF(brdfData, roughness2, normalWS, lightDirectionWS, viewDirectionWS) * radiance;
}
#endif
color += emission;
// Computes fog factor per-vertex
ApplyFog(color, fogFactor);
return OutputColor(color, alpha);
}
#endif

9
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightLighting.cginc.meta


fileFormatVersion: 2
guid: 762f0a4829f44584ba01e2f0661150d9
timeCreated: 1488965025
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

226
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPassLit.cginc


#ifndef LIGHTWEIGHT_PASS_LIT_INCLUDED
#define LIGHTWEIGHT_PASS_LIT_INCLUDED
#include "LightweightLighting.cginc"
struct LightweightVertexInput
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 tangent : TANGENT;
float2 texcoord : TEXCOORD0;
float2 lightmapUV : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct LightweightVertexOutput
{
float2 uv : TEXCOORD0;
float4 ambientOrLightmapUV : TEXCOORD1; // xy: lightmapUV, zw: dynamicLightmapUV OR color from SH
float4 posWS : TEXCOORD2;
#if _NORMALMAP
half3 tangent : TEXCOORD3;
half3 binormal : TEXCOORD4;
half3 normal : TEXCOORD5;
#else
half3 normal : TEXCOORD3;
#endif
half4 viewDir : TEXCOORD6; // xyz: viewDir
half4 fogFactorAndVertexLight : TEXCOORD7; // x: fogFactor, yzw: vertex light
float4 clipPos : SV_POSITION;
UNITY_VERTEX_OUTPUT_STEREO
};
inline void InitializeStandardLitSurfaceData(LightweightVertexOutput IN, out SurfaceData outSurfaceData)
{
float2 uv = IN.uv;
half4 albedoAlpha = tex2D(_MainTex, uv);
half4 specGloss = MetallicSpecGloss(uv, albedoAlpha);
outSurfaceData.albedo = LIGHTWEIGHT_GAMMA_TO_LINEAR(albedoAlpha.rgb) * _Color.rgb;
#if _METALLIC_SETUP
outSurfaceData.metallic = specGloss.r;
outSurfaceData.specular = half3(0.0h, 0.0h, 0.0h);
#else
outSurfaceData.metallic = 1.0h;
outSurfaceData.specular = specGloss.rgb;
#endif
outSurfaceData.smoothness = specGloss.a;
outSurfaceData.normal = Normal(uv);
outSurfaceData.occlusion = OcclusionLW(uv);
outSurfaceData.emission = EmissionLW(uv);
outSurfaceData.emission += IN.fogFactorAndVertexLight.yzw;
outSurfaceData.alpha = Alpha(albedoAlpha.a);
}
void InitializeSurfaceInput(LightweightVertexOutput IN, out SurfaceInput outSurfaceInput)
{
#if LIGHTMAP_ON
outSurfaceInput.lightmapUV = float4(IN.ambientOrLightmapUV.xy, 0.0, 0.0);
#else
outSurfaceInput.lightmapUV = float4(0.0, 0.0, 0.0, 0.0);
#endif
#if _NORMALMAP
outSurfaceInput.tangentWS = IN.tangent;
outSurfaceInput.bitangentWS = IN.binormal;
#else
outSurfaceInput.tangentWS = half3(1.0h, 0.0h, 0.0h);
outSurfaceInput.bitangentWS = half3(0.0h, 1.0h, 0.0h);
#endif
outSurfaceInput.normalWS = IN.normal;
outSurfaceInput.positionWS = IN.posWS;
outSurfaceInput.viewDirectionWS = IN.viewDir;
outSurfaceInput.fogFactor = IN.fogFactorAndVertexLight.x;
}
LightweightVertexOutput LitPassVertex(LightweightVertexInput v)
{
LightweightVertexOutput o = (LightweightVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.uv = TRANSFORM_TEX(v.texcoord, _MainTex);
float3 worldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
o.posWS.xyz = worldPos;
half3 viewDir = normalize(_WorldSpaceCameraPos - worldPos);
o.viewDir.xyz = viewDir;
half3 normal = normalize(UnityObjectToWorldNormal(v.normal));
#if _NORMALMAP
half sign = v.tangent.w * unity_WorldTransformParams.w;
o.tangent = normalize(mul((half3x3)unity_ObjectToWorld, v.tangent.xyz));
o.binormal = cross(normal, o.tangent) * sign;
o.normal = normal;
#else
o.normal = normal;
#endif
#ifdef LIGHTMAP_ON
o.ambientOrLightmapUV.xy = v.lightmapUV * unity_LightmapST.xy + unity_LightmapST.zw;
// TODO: Dynamic Lightmap
o.ambientOrLightmapUV.zw = float2(0.0, 0.0);
// TODO: Currently there's no way to pass in ambient contribution to fragmentPBR.
// We should allow to create custom ambient computation for things like SH evaluation, lightmap, ambient color etc.
//#else
// o.ambientOrLightmapUV = half4(SHEvalLinearL2(half4(normal, 1.0)), 0.0h);
#endif
o.fogFactorAndVertexLight.yzw = half3(0.0h, 0.0h, 0.0h);
#if defined(_VERTEX_LIGHTS)
half3 diffuse = half3(1.0, 1.0, 1.0);
int vertexLightStart = _AdditionalLightCount.x;
int vertexLightEnd = min(_AdditionalLightCount.y, unity_LightIndicesOffsetAndCount.y);
for (int lightIter = vertexLightStart; lightIter < vertexLightEnd; ++lightIter)
{
LightInput lightData;
INITIALIZE_LIGHT(lightData, lightIter);
half3 lightDirection;
half atten = ComputeVertexLightAttenuation(lightData, normal, worldPos, lightDirection);
o.fogFactorAndVertexLight.yzw += LightingLambert(diffuse, lightDirection, normal, atten) * lightData.color;
}
#endif
float4 clipPos = UnityObjectToClipPos(v.vertex);
o.fogFactorAndVertexLight.x = ComputeFogFactor(clipPos.z);
o.clipPos = clipPos;
return o;
}
half4 LitPassFragment(LightweightVertexOutput IN) : SV_Target
{
SurfaceData surfaceData;
InitializeStandardLitSurfaceData(IN, surfaceData);
SurfaceInput surfaceInput;
InitializeSurfaceInput(IN, surfaceInput);
return LightweightFragmentPBR(surfaceInput.lightmapUV, surfaceInput.positionWS, surfaceInput.normalWS, surfaceInput.tangentWS, surfaceInput.bitangentWS, surfaceInput.viewDirectionWS, surfaceInput.fogFactor, surfaceData.albedo, surfaceData.metallic, surfaceData.specular, surfaceData.smoothness, surfaceData.normal, surfaceData.occlusion, surfaceData.emission, surfaceData.alpha);
}
half4 LitPassFragmentSimple(LightweightVertexOutput IN) : SV_Target
{
float2 uv = IN.uv;
half4 diffuseAlpha = tex2D(_MainTex, uv);
half3 diffuse = LIGHTWEIGHT_GAMMA_TO_LINEAR(diffuseAlpha.rgb) * _Color.rgb;
#ifdef _GLOSSINESS_FROM_BASE_ALPHA
half alpha = _Color.a;
#else
half alpha = diffuseAlpha.a * _Color.a;
#endif
// Keep for compatibility reasons. Shader Inpector throws a warning when using cutoff
// due overdraw performance impact.
#ifdef _ALPHATEST_ON
clip(alpha - _Cutoff);
#endif
#if _NORMALMAP
half3 normalTangent = Normal(uv);
half3 normalWorld = TangentToWorldNormal(normalTangent, IN.tangent, IN.binormal, IN.normal);
#else
half3 normalWorld = normalize(IN.normal);
#endif
half4 specularGloss;
SpecularGloss(uv, alpha, specularGloss);
half3 viewDir = IN.viewDir.xyz;
float3 worldPos = IN.posWS.xyz;
half3 lightDirection;
#if defined(LIGHTMAP_ON)
half3 color = DecodeLightmap(UNITY_SAMPLE_TEX2D(unity_Lightmap, IN.ambientOrLightmapUV.xy)) * diffuse;
#else
half3 color = (ShadeSH9(half4(normalWorld, 1.0)) + IN.ambientOrLightmapUV.xyz) * diffuse;
#endif
LightInput lightInput;
INITIALIZE_MAIN_LIGHT(lightInput);
half lightAtten = ComputeMainLightAttenuation(lightInput, normalWorld, worldPos, lightDirection);
lightAtten *= LIGHTWEIGHT_SHADOW_ATTENUATION(worldPos, normalize(IN.normal), _ShadowLightDirection.xyz);
#if defined(_SPECGLOSSMAP) || defined(_SPECULAR_COLOR)
color += LightingBlinnPhong(diffuse, specularGloss, lightDirection, normalWorld, viewDir, lightAtten) * lightInput.color;
#else
color += LightingLambert(diffuse, lightDirection, normalWorld, lightAtten) * lightInput.color;
#endif
#ifdef _ADDITIONAL_LIGHTS
int pixelLightCount = min(_AdditionalLightCount.x, unity_LightIndicesOffsetAndCount.y);
for (int lightIter = 0; lightIter < pixelLightCount; ++lightIter)
{
LightInput lightData;
INITIALIZE_LIGHT(lightData, lightIter);
half lightAtten = ComputePixelLightAttenuation(lightData, normalWorld, worldPos, lightDirection);
#if defined(_SPECGLOSSMAP) || defined(_SPECULAR_COLOR)
color += LightingBlinnPhong(diffuse, specularGloss, lightDirection, normalWorld, viewDir, lightAtten) * lightData.color;
#else
color += LightingLambert(diffuse, lightDirection, normalWorld, lightAtten) * lightData.color;
#endif
}
#endif // _ADDITIONAL_LIGHTS
color += EmissionLW(uv);
color += IN.fogFactorAndVertexLight.yzw;
// Computes Fog Factor per vextex
ApplyFog(color, IN.fogFactorAndVertexLight.x);
return OutputColor(color, alpha);
};
#endif

9
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPassLit.cginc.meta


fileFormatVersion: 2
guid: 116bd973269b9f741b7177c8523b9e50
timeCreated: 1488965025
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

20
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPassShadow.cginc


#ifndef LIGHTWEIGHT_PASS_SHADOW_INCLUDED
#define LIGHTWEIGHT_PASS_SHADOW_INCLUDED
float4 ShadowPassVertex(float4 pos : POSITION) : SV_POSITION
{
float4 clipPos = UnityObjectToClipPos(pos);
#if defined(UNITY_REVERSED_Z)
clipPos.z = min(clipPos.z, UNITY_NEAR_CLIP_VALUE);
#else
clipPos.z = max(clipPos.z, UNITY_NEAR_CLIP_VALUE);
#endif
return clipPos;
}
half4 ShadowPassFragment() : SV_TARGET
{
return 0;
}
#endif

9
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightPassShadow.cginc.meta


fileFormatVersion: 2
guid: 9a48a2987a0e11645adf07fe4a8d5ec9
timeCreated: 1488965025
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

93
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightShadows.cginc


#ifndef LIGHTWEIGHT_SHADOWS_INCLUDED
#define LIGHTWEIGHT_SHADOWS_INCLUDED
#define MAX_SHADOW_CASCADES 4
#if defined(_HARD_SHADOWS) || defined(_SOFT_SHADOWS) || defined(_HARD_SHADOWS_CASCADES) || defined(_SOFT_SHADOWS_CASCADES)
#define _SHADOWS
#endif
#if defined(_HARD_SHADOWS_CASCADES) || defined(_SOFT_SHADOWS_CASCADES)
#define _SHADOW_CASCADES
#endif
#ifdef _SHADOWS
#define LIGHTWEIGHT_SHADOW_ATTENUATION(posWorld, vertexNormal, shadowDir) ComputeShadowAttenuation(posWorld, vertexNormal, shadowDir)
#else
#define LIGHTWEIGHT_SHADOW_ATTENUATION(posWorld, vertexNormal, shadowDir) 1.0h
#endif
sampler2D_float _ShadowMap;
float _PCFKernel[8];
float4x4 _WorldToShadow[MAX_SHADOW_CASCADES];
float4 _DirShadowSplitSpheres[MAX_SHADOW_CASCADES];
half4 _ShadowData;
half4 _ShadowLightDirection;
inline half ShadowAttenuation(float3 shadowCoord)
{
if (shadowCoord.x <= 0 || shadowCoord.x >= 1 || shadowCoord.y <= 0 || shadowCoord.y >= 1)
return 1;
float depth = tex2D(_ShadowMap, shadowCoord).r;
#if defined(UNITY_REVERSED_Z)
return step(depth - _ShadowData.y, shadowCoord.z);
#else
return step(shadowCoord.z, depth + _ShadowData.y);
#endif
}
inline half ComputeCascadeIndex(float3 wpos)
{
float3 fromCenter0 = wpos.xyz - _DirShadowSplitSpheres[0].xyz;
float3 fromCenter1 = wpos.xyz - _DirShadowSplitSpheres[1].xyz;
float3 fromCenter2 = wpos.xyz - _DirShadowSplitSpheres[2].xyz;
float3 fromCenter3 = wpos.xyz - _DirShadowSplitSpheres[3].xyz;
float4 distances2 = float4(dot(fromCenter0, fromCenter0), dot(fromCenter1, fromCenter1), dot(fromCenter2, fromCenter2), dot(fromCenter3, fromCenter3));
float4 vDirShadowSplitSphereSqRadii;
vDirShadowSplitSphereSqRadii.x = _DirShadowSplitSpheres[0].w;
vDirShadowSplitSphereSqRadii.y = _DirShadowSplitSpheres[1].w;
vDirShadowSplitSphereSqRadii.z = _DirShadowSplitSpheres[2].w;
vDirShadowSplitSphereSqRadii.w = _DirShadowSplitSpheres[3].w;
fixed4 weights = fixed4(distances2 < vDirShadowSplitSphereSqRadii);
weights.yzw = saturate(weights.yzw - weights.xyz);
return 4 - dot(weights, fixed4(4, 3, 2, 1));
}
inline half ShadowPCF(half3 shadowCoord)
{
// TODO: simulate textureGatherOffset not available, simulate it
half2 offset = half2(0, 0);
half attenuation = ShadowAttenuation(half3(shadowCoord.xy + half2(_PCFKernel[0], _PCFKernel[1]) + offset, shadowCoord.z)) +
ShadowAttenuation(half3(shadowCoord.xy + half2(_PCFKernel[2], _PCFKernel[3]) + offset, shadowCoord.z)) +
ShadowAttenuation(half3(shadowCoord.xy + half2(_PCFKernel[4], _PCFKernel[5]) + offset, shadowCoord.z)) +
ShadowAttenuation(half3(shadowCoord.xy + half2(_PCFKernel[6], _PCFKernel[7]) + offset, shadowCoord.z));
return attenuation * 0.25;
}
inline half ComputeShadowAttenuation(float3 posWorld, half3 vertexNormal, half3 shadowDir)
{
half NdotL = dot(vertexNormal, shadowDir);
half bias = saturate(1.0 - NdotL) * _ShadowData.z;
float3 posWorldOffsetNormal = posWorld + vertexNormal * bias;
int cascadeIndex = 0;
#ifdef _SHADOW_CASCADES
cascadeIndex = ComputeCascadeIndex(posWorldOffsetNormal);
if (cascadeIndex >= MAX_SHADOW_CASCADES)
return 1.0;
#endif
float4 shadowCoord = mul(_WorldToShadow[cascadeIndex], float4(posWorldOffsetNormal, 1.0));
shadowCoord.xyz /= shadowCoord.w;
shadowCoord.z = saturate(shadowCoord.z);
#if defined(_SOFT_SHADOWS) || defined(_SOFT_SHADOWS_CASCADES)
return ShadowPCF(shadowCoord.xyz);
#else
return ShadowAttenuation(shadowCoord.xyz);
#endif
}
#endif

9
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightShadows.cginc.meta


fileFormatVersion: 2
guid: 5cb845b7decdb4db6a7fcc676b127b6d
timeCreated: 1488965025
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

142
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightStandard.shader


Shader "LightweightPipeline/Standard (Physically Based)"
{
Properties
{
// Specular vs Metallic workflow
[HideInInspector] _WorkflowMode("WorkflowMode", Float) = 1.0
_Color("Color", Color) = (1,1,1,1)
_MainTex("Albedo", 2D) = "white" {}
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
_Glossiness("Smoothness", Range(0.0, 1.0)) = 0.5
_GlossMapScale("Smoothness Scale", Range(0.0, 1.0)) = 1.0
_SmoothnessTextureChannel("Smoothness texture channel", Float) = 0
[Gamma] _Metallic("Metallic", Range(0.0, 1.0)) = 0.0
_MetallicGlossMap("Metallic", 2D) = "white" {}
_SpecColor("Specular", Color) = (0.2, 0.2, 0.2)
_SpecGlossMap("Specular", 2D) = "white" {}
[Toggle] _SpecularHighlights("Specular Highlights", Float) = 1.0
[Toggle] _GlossyReflections("Glossy Reflections", Float) = 1.0
_BumpScale("Scale", Float) = 1.0
_BumpMap("Normal Map", 2D) = "bump" {}
_Parallax("Height Scale", Range(0.005, 0.08)) = 0.02
_ParallaxMap("Height Map", 2D) = "black" {}
_OcclusionStrength("Strength", Range(0.0, 1.0)) = 1.0
_OcclusionMap("Occlusion", 2D) = "white" {}
_EmissionColor("Color", Color) = (0,0,0)
_EmissionMap("Emission", 2D) = "white" {}
_DetailMask("Detail Mask", 2D) = "white" {}
_DetailAlbedoMap("Detail Albedo x2", 2D) = "grey" {}
_DetailNormalMapScale("Scale", Float) = 1.0
_DetailNormalMap("Normal Map", 2D) = "bump" {}
[Enum(UV0,0,UV1,1)] _UVSec("UV Set for secondary textures", Float) = 0
// Blending state
[HideInInspector] _Mode("__mode", Float) = 0.0
[HideInInspector] _SrcBlend("__src", Float) = 1.0
[HideInInspector] _DstBlend("__dst", Float) = 0.0
[HideInInspector] _ZWrite("__zw", Float) = 1.0
}
SubShader
{
Tags{"RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline"}
LOD 300
// ------------------------------------------------------------------
// Base forward pass (directional light, emission, lightmaps, ...)
Pass
{
Tags{"LightMode" = "LightweightForward"}
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]
CGPROGRAM
#pragma target 3.0
// -------------------------------------
#pragma shader_feature _METALLIC_SETUP _SPECULAR_SETUP
#pragma shader_feature _NORMALMAP
#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON _ALPHAPREMULTIPLY_ON
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICSPECGLOSSMAP
#pragma shader_feature _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature _SPECULARHIGHLIGHTS_OFF
#pragma shader_feature _GLOSSYREFLECTIONS_OFF
#pragma shader_feature _OCCLUSIONMAP
#pragma multi_compile _MAIN_DIRECTIONAL_LIGHT _MAIN_SPOT_LIGHT _MAIN_POINT_LIGHT
#pragma multi_compile _ _ADDITIONAL_LIGHTS
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ _HARD_SHADOWS _SOFT_SHADOWS _HARD_SHADOWS_CASCADES _SOFT_SHADOWS_CASCADES
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile_fog
#pragma multi_compile_instancing
#pragma vertex LitPassVertex
#pragma fragment LitPassFragment
#include "UnityStandardInput.cginc"
#include "LightweightPassLit.cginc"
ENDCG
}
Pass
{
Tags{"Lightmode" = "ShadowCaster"}
ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 2.0
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#include "UnityCG.cginc"
#include "LightweightPassShadow.cginc"
ENDCG
}
Pass
{
Tags{"Lightmode" = "DepthOnly"}
ZWrite On
CGPROGRAM
#pragma target 2.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
float4 vert(float4 pos : POSITION) : SV_POSITION
{
return UnityObjectToClipPos(pos);
}
half4 frag() : SV_TARGET
{
return 0;
}
ENDCG
}
}
FallBack "Standard"
CustomEditor "LightweightStandardGUI"
}

10
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightStandard.shader.meta


fileFormatVersion: 2
guid: 933532a4fcc9baf4fa0491de14d08ed7
timeCreated: 1503472755
licenseType: Pro
ShaderImporter:
externalObjects: {}
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

172
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightStandardSimpleLighting.shader


// Shader targeted for low end devices. Single Pass Forward Rendering. Shader Model 2
Shader "LightweightPipeline/Standard (Simple Lighting)"
{
// Keep properties of StandardSpecular shader for upgrade reasons.
Properties
{
_Color("Color", Color) = (1,1,1,1)
_MainTex("Base (RGB) Glossiness / Alpha (A)", 2D) = "white" {}
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
_Shininess("Shininess", Range(0.01, 1.0)) = 1.0
_GlossMapScale("Smoothness Factor", Range(0.0, 1.0)) = 1.0
_Glossiness("Glossiness", Range(0.0, 1.0)) = 0.5
[Enum(Specular Alpha,0,Albedo Alpha,1)] _SmoothnessTextureChannel("Smoothness texture channel", Float) = 0
[HideInInspector] _SpecSource("Specular Color Source", Float) = 0.0
_SpecColor("Specular", Color) = (1.0, 1.0, 1.0)
_SpecGlossMap("Specular", 2D) = "white" {}
[HideInInspector] _GlossinessSource("Glossiness Source", Float) = 0.0
[ToggleOff] _SpecularHighlights("Specular Highlights", Float) = 1.0
[ToggleOff] _GlossyReflections("Glossy Reflections", Float) = 1.0
[HideInInspector] _BumpScale("Scale", Float) = 1.0
[NoScaleOffset] _BumpMap("Normal Map", 2D) = "bump" {}
_Parallax("Height Scale", Range(0.005, 0.08)) = 0.02
_ParallaxMap("Height Map", 2D) = "black" {}
_EmissionColor("Emission Color", Color) = (0,0,0)
_EmissionMap("Emission", 2D) = "white" {}
_DetailMask("Detail Mask", 2D) = "white" {}
_DetailAlbedoMap("Detail Albedo x2", 2D) = "grey" {}
_DetailNormalMapScale("Scale", Float) = 1.0
_DetailNormalMap("Normal Map", 2D) = "bump" {}
[Enum(UV0,0,UV1,1)] _UVSec("UV Set for secondary textures", Float) = 0
// Blending state
[HideInInspector] _Mode("__mode", Float) = 0.0
[HideInInspector] _SrcBlend("__src", Float) = 1.0
[HideInInspector] _DstBlend("__dst", Float) = 0.0
[HideInInspector] _ZWrite("__zw", Float) = 1.0
}
SubShader
{
Tags { "RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline" }
LOD 300
Pass
{
Tags { "LightMode" = "LightweightForward" }
// Use same blending / depth states as Standard shader
Blend[_SrcBlend][_DstBlend]
ZWrite[_ZWrite]
CGPROGRAM
#pragma target 3.0
#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON
#pragma shader_feature _ _SPECGLOSSMAP _SPECULAR_COLOR
#pragma shader_feature _ _GLOSSINESS_FROM_BASE_ALPHA
#pragma shader_feature _NORMALMAP
#pragma shader_feature _EMISSION
#pragma multi_compile _MAIN_DIRECTIONAL_LIGHT _MAIN_SPOT_LIGHT _MAIN_POINT_LIGHT
#pragma multi_compile _ _ADDITIONAL_LIGHTS
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ _HARD_SHADOWS _SOFT_SHADOWS _HARD_SHADOWS_CASCADES _SOFT_SHADOWS_CASCADES
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile_fog
#pragma multi_compile_instancing
#pragma vertex LitPassVertex
#pragma fragment LitPassFragmentSimple
#include "UnityStandardInput.cginc"
#include "LightweightPassLit.cginc"
ENDCG
}
Pass
{
Tags{"Lightmode" = "ShadowCaster"}
ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 2.0
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#include "UnityCG.cginc"
#include "LightweightPassShadow.cginc"
ENDCG
}
Pass
{
Tags{"Lightmode" = "DepthOnly"}
ZWrite On
CGPROGRAM
#pragma target 2.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
float4 vert(float4 pos : POSITION) : SV_POSITION
{
return UnityObjectToClipPos(pos);
}
half4 frag() : SV_TARGET
{
return 0;
}
ENDCG
}
// This pass it not used during regular rendering, only for lightmap baking.
Pass
{
Tags{ "LightMode" = "Meta" }
Cull Off
CGPROGRAM
#define UNITY_SETUP_BRDF_INPUT SpecularSetup
#pragma vertex vert_meta
#pragma fragment frag_meta_ld
#pragma shader_feature _EMISSION
#pragma shader_feature _SPECGLOSSMAP
#pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature ___ _DETAIL_MULX2
#pragma shader_feature EDITOR_VISUALIZATION
#include "UnityStandardMeta.cginc"
#include "LightweightCore.cginc"
fixed4 frag_meta_ld(v2f_meta i) : SV_Target
{
UnityMetaInput o;
UNITY_INITIALIZE_OUTPUT(UnityMetaInput, o);
o.Albedo = Albedo(i.uv);
half4 specularColor;
SpecularGloss(i.uv.xy, 1.0, specularColor);
o.SpecularColor = specularColor;
#ifdef _EMISSION
o.Emission += LIGHTWEIGHT_GAMMA_TO_LINEAR(tex2D(_EmissionMap, i.uv).rgb) * _EmissionColor;
#else
o.Emission += _EmissionColor;
#endif
return UnityMetaFragment(o);
}
ENDCG
}
}
Fallback "Standard (Specular setup)"
CustomEditor "LightweightStandardSimpleLightingGUI"
}

9
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightStandardSimpleLighting.shader.meta


fileFormatVersion: 2
guid: 8d2bb70cbf9db8d4da26e15b26e74248
timeCreated: 1487263524
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

88
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightUnlit.shader


Shader "LightweightPipeline/Unlit"
{
Properties
{
_MainTex("Texture", 2D) = "white" {}
_MainColor("MainColor", Color) = (1, 1, 1, 1)
_Cutoff("AlphaCutout", Range(0.0, 1.0)) = 0.5
// BlendMode
[HideInInspector] _Mode("Mode", Float) = 0.0
[HideInInspector] _SrcBlend("Src", Float) = 1.0
[HideInInspector] _DstBlend("Dst", Float) = 0.0
[HideInInspector] _ZWrite("ZWrite", Float) = 1.0
}
SubShader
{
Tags { "RenderType" = "Opaque" "IgnoreProjectors" = "True" "RenderPipeline" = "LightweightPipe" "Lightmode" = "LightweightForward" }
LOD 100
Blend [_SrcBlend][_DstBlend]
ZWrite [_ZWrite]
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
#pragma multi_compile_fog
#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
UNITY_VERTEX_OUTPUT_STEREO
};
sampler2D _MainTex;
float4 _MainTex_ST;
half4 _MainColor;
half _Cutoff;
v2f vert(appdata v)
{
v2f o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag(v2f i) : SV_Target
{
fixed4 texColor = tex2D(_MainTex, i.uv);
fixed alpha = texColor.a * _MainColor.a;
fixed3 color = texColor.rgb * _MainColor.rgb;
#ifdef _ALPHATEST_ON
clip(alpha - _Cutoff);
#endif
UNITY_APPLY_FOG(i.fogCoord, color);
#ifdef _ALPHABLEND_ON
return fixed4(color, alpha);
#else
return fixed4(color, 1.0);
#endif
}
ENDCG
}
}
CustomEditor "LightweightUnlitGUI"
}

9
ScriptableRenderPipeline/LightweightPipeline/Shaders/LightweightUnlit.shader.meta


fileFormatVersion: 2
guid: 650dd9526735d5b46b79224bc6e94025
timeCreated: 1496762173
licenseType: Pro
ShaderImporter:
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

10
ScriptableRenderPipeline/LightweightPipeline/Textures.meta


fileFormatVersion: 2
guid: 3c94d46d9288ec04c8b97aa427dd2a3d
folderAsset: yes
timeCreated: 1503916220
licenseType: Pro
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

3
ScriptableRenderPipeline/LightweightPipeline/Textures/LightweightLightAttenuation.png

之前 之后
宽度: 1024  |  高度: 4  |  大小: 398 B

117
ScriptableRenderPipeline/LightweightPipeline/Textures/LightweightLightAttenuation.png.meta


fileFormatVersion: 2
guid: ee420ad43ff580149a07f10ad66c49ff
timeCreated: 1503935793
licenseType: Pro
TextureImporter:
fileIDToRecycleName: {}
externalObjects: {}
serializedVersion: 4
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 0
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
isReadable: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -1
wrapU: 1
wrapV: 1
wrapW: 1
nPOTScale: 1
lightmap: 0
compressionQuality: 50
spriteMode: 0
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spritePixelsToUnits: 100
alphaUsage: 1
alphaIsTransparency: 0
spriteTessellationDetail: -1
textureType: 10
textureShape: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: 1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 1
androidETC2FallbackOverride: 0
- buildTarget: iPhone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: tvOS
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
- buildTarget: WiiU
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
spritePackingTag:
userData:
assetBundleName:
assetBundleVariant:

9
ScriptableRenderPipeline/Core/ShadowIncludes.inl.meta


fileFormatVersion: 2
guid: 781c88b8cef201942ad26d90fdace0bf
timeCreated: 1491314187
licenseType: Pro
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
正在加载...
取消
保存