浏览代码

Merge remote-tracking branch 'origin/master' into inspector-window

/main
Jens Holm 7 年前
当前提交
93fa2455
共有 115 个文件被更改,包括 1855 次插入1143 次删除
  1. 8
      MaterialGraphProject/Assets/LightweightAsset.asset
  2. 11
      MaterialGraphProject/Assets/UnityShaderEditor.meta
  3. 10
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/AbstractMaterialGraph.cs
  4. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/AbstractShaderProperty.cs
  5. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/BitangentMaterialSlot.cs
  6. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ColorMaterialSlot.cs
  7. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ColorRGBMaterialSlot.cs
  8. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ColorShaderProperty.cs
  9. 9
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/CubemapShaderProperty.cs
  10. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/FloatShaderProperty.cs
  11. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/IShaderProperty.cs
  12. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialGraphAsset.cs
  13. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialGraphAsset.cs.meta
  14. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialSlot.cs
  15. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/NormalMaterialSlot.cs
  16. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/PositionMaterialSlot.cs
  17. 7
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/SamplerStateShaderProperty.cs
  18. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ScreenPositionMaterialSlot.cs
  19. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/TangentMaterialSlot.cs
  20. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/TextureShaderProperty.cs
  21. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/UVMaterialSlot.cs
  22. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/Vector2ShaderProperty.cs
  23. 7
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/Vector3ShaderProperty.cs
  24. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/VectorShaderProperty.cs
  25. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/VertexColorMaterialSlot.cs
  26. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ViewDirectionMaterialSlot.cs
  27. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Interfaces/NeededCoordinateSpace.cs
  28. 26
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs
  29. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightUnlitSubShader.cs
  30. 7
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/AbstractMaterialNode.cs
  31. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Normal/NormalUnpackNode.cs
  32. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Basic/ColorNode.cs
  33. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/BitangentVectorNode.cs
  34. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/NormalVectorNode.cs
  35. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/PositionNode.cs
  36. 10
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs
  37. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/TangentVectorNode.cs
  38. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/UVNode.cs
  39. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/VertexColorNode.cs
  40. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/ViewDirectionNode.cs
  41. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Matrix/TransformationMatrixNode.cs
  42. 18
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/SampleCubemapNode.cs
  43. 32
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/SampleTexture2DNode.cs
  44. 341
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Utility/SubGraphNode.cs
  45. 103
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/SubGraph.cs
  46. 17
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/SubGraphOutputNode.cs
  47. 48
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/GraphUtil.cs
  48. 69
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGenerator.cs
  49. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/DefaultShaderIncludes.cs
  50. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/MaterialGraphEditWindow.cs
  51. 27
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/PreviewManager.cs
  52. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Resources.meta
  53. 92
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRExtraPasses.template
  54. 96
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRForwardPass.template
  55. 28
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightUnlitPass.template
  56. 2
      MaterialGraphProject/Assets/UnityShaderEditor/package.json
  57. 2
      MaterialGraphProject/UnityPackageManager/manifest.json
  58. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/UnlitMasterNode.cs
  59. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/PBRMasterNode.cs
  60. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline.meta
  61. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes.meta
  62. 18
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/MatrixNames.cs
  63. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/MatrixNames.cs.meta
  64. 18
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGeneratorNames.cs
  65. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGeneratorNames.cs.meta
  66. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/UvChannel.cs
  67. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/UvChannel.cs.meta
  68. 74
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/HDUnlitPassForward.template
  69. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/HDUnlitPassForward.template.meta
  70. 8
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary.meta
  71. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/HDUnlitSubShader.cs.meta
  72. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/IUnlitSubShader.cs
  73. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/IUnlitSubShader.cs.meta
  74. 201
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/HDUnlitSubShader.cs
  75. 14
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/Functions.hlsl
  76. 9
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/Functions.hlsl.meta
  77. 173
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/GeometricTools.hlsl
  78. 9
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/GeometricTools.hlsl.meta
  79. 15
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderConfig.cs.hlsl
  80. 9
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderConfig.cs.hlsl.meta
  81. 279
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariables.hlsl
  82. 9
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariables.hlsl.meta
  83. 192
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesFunctions.hlsl
  84. 10
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesFunctions.hlsl.meta
  85. 21
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesMatrixDefsLegacyUnity.hlsl
  86. 10
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesMatrixDefsLegacyUnity.hlsl.meta
  87. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/AbstractSubGraph.cs.meta
  88. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/AbstractSubGraphNode.cs.meta
  89. 65
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/AbstractSubGraph.cs
  90. 250
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/AbstractSubGraphNode.cs
  91. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/MetallicMasterNode.cs.meta
  92. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/SpecularMasterNode.cs.meta
  93. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ProjectSpecificMasterNode.cs.meta
  94. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ExportTextureMasterNode.cs.meta
  95. 97
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ProjectSpecificMasterNode.cs
  96. 156
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ExportTextureMasterNode.cs
  97. 88
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/MetallicMasterNode.cs

8
MaterialGraphProject/Assets/LightweightAsset.asset


m_EditorClassIdentifier:
m_MaxPixelLights: 4
m_SupportsVertexLight: 0
m_SupportSoftParticles: 0
m_RequireCameraDepthTexture: 0
m_MSAA: 4
m_RenderScale: 1
m_ShadowType: 1

m_DefaultShader: {fileID: 4800000, guid: 933532a4fcc9baf4fa0491de14d08ed7, type: 3}
m_BlitShader: {fileID: 4800000, guid: c17132b1f77d20942aa75f8429c0f8bc, type: 3}
m_CopyDepthShader: {fileID: 4800000, guid: d6dae50ee9e1bfa4db75f19f99355220, type: 3}
m_DefaultMaterial: {fileID: 2100000, guid: 31321ba15b8f8eb4c954353edc038b1d, type: 2}
m_DefaultParticleMaterial: {fileID: 2100000, guid: e823cd5b5d27c0f4b8256e7c12ee3e6d,
type: 2}
m_DefaultTerrainMaterial: {fileID: 2100000, guid: 594ea882c5a793440b60ff72d896021e,
type: 2}
m_ResourceAsset: {fileID: 11400000, guid: c8afc0a27fb8c0b4da18151c689a1082, type: 2}

11
MaterialGraphProject/Assets/UnityShaderEditor.meta


fileFormatVersion: 2
guid: b100142c357c2d745b9707d6e2f987fd
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
fileFormatVersion: 2
guid: 0b601fe23f0347ab8e4892edf2cf76d7
timeCreated: 1513757926

10
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/AbstractMaterialGraph.cs


using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor.Compilation;
using UnityEditor.Graphing.Util;
namespace UnityEditor.ShaderGraph
{

public IEnumerable<Guid> removedProperties
{
get { return m_RemovedProperties; }
}
[SerializeField]
SerializableGuid m_GUID = new SerializableGuid();
public Guid guid
{
get { return m_GUID.guid; }
}
#endregion

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/AbstractShaderProperty.cs


public abstract Vector4 defaultValue { get; }
public abstract string GetPropertyBlockString();
public abstract string GetPropertyDeclarationString();
public abstract string GetPropertyDeclarationString(string delimiter = ";");
public virtual string GetInlinePropertyDeclarationString()
public virtual string GetPropertyAsArgumentString()
return GetPropertyDeclarationString();
return GetPropertyDeclarationString(string.Empty);
}
public abstract PreviewProperty GetPreviewMaterialProperty();

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/BitangentMaterialSlot.cs


public override string GetDefaultValue(GenerationMode generationMode)
{
return space.ToVariableName(InterpolatorType.BiTangent);
return string.Format("IN.{0}", space.ToVariableName(InterpolatorType.BiTangent));
}
public NeededCoordinateSpace RequiresBitangent()

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ColorMaterialSlot.cs


protected override string ConcreteSlotValueAsVariable(AbstractMaterialNode.OutputPrecision precision)
{
return string.Format("IsGammaSpace() ? {0}4({1}, {2}, {3}, {4}) : {0}4 (GammaToLinearSpace({0}3({1}, {2}, {3})), {4})"
return string.Format("IsGammaSpace() ? {0}4({1}, {2}, {3}, {4}) : {0}4 (SRGBToLinear({0}3({1}, {2}, {3})), {4})"
, precision
, value.x
, value.y

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ColorRGBMaterialSlot.cs


protected override string ConcreteSlotValueAsVariable(AbstractMaterialNode.OutputPrecision precision)
{
return string.Format("IsGammaSpace() ? {0}3({1}, {2}, {3}) : GammaToLinearSpace({0}3({1}, {2}, {3}))"
return string.Format("IsGammaSpace() ? {0}3({1}, {2}, {3}) : SRGBToLinear({0}3({1}, {2}, {3}))"
, precision
, value.x
, value.y

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ColorShaderProperty.cs


return result.ToString();
}
public override string GetPropertyDeclarationString()
public override string GetPropertyDeclarationString(string delimiter = ";")
return "float4 " + referenceName + ";";
return string.Format("float4 {0}{1}", referenceName, delimiter);
}
public override PreviewProperty GetPreviewMaterialProperty()

9
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/CubemapShaderProperty.cs


result.Append("\", CUBE) = \"\" {}");
return result.ToString();
}
public override string GetPropertyDeclarationString(string delimiter = ";")
{
return string.Format("TEXTURECUBE({0}){1} SAMPLER(sampler{0}){1}", referenceName, delimiter);
}
public override string GetPropertyDeclarationString()
public override string GetPropertyAsArgumentString()
return "samplerCUBE " + referenceName + ";";
return string.Format("TEXTURECUBE_ARGS({0}, sampler{0})", referenceName);
}
public override PreviewProperty GetPreviewMaterialProperty()

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/FloatShaderProperty.cs


return result.ToString();
}
public override string GetPropertyDeclarationString()
public override string GetPropertyDeclarationString(string delimiter = ";")
return "float " + referenceName + ";";
return string.Format("float {0}{1}", referenceName, delimiter);
}
public override PreviewProperty GetPreviewMaterialProperty()

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/IShaderProperty.cs


string overrideReferenceName { get; set; }
string GetPropertyBlockString();
string GetPropertyDeclarationString();
string GetInlinePropertyDeclarationString();
string GetPropertyDeclarationString(string delimiter = ";");
string GetPropertyAsArgumentString();
PreviewProperty GetPreviewMaterialProperty();
INode ToConcreteNode();
}

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialGraphAsset.cs


using System;
using System.Linq;
using UnityEngine;
using System.Reflection;

{
public static bool ShaderHasError(Shader shader)
{
var hasErrorsCall = typeof(ShaderUtil).GetMethod("GetShaderErrorCount", BindingFlags.Static | BindingFlags.NonPublic);
var result = hasErrorsCall.Invoke(null, new object[] { shader });
return (int)result != 0;
var errors = GetShaderErrors(shader);
return errors.Any(x => x.warning == 0);
}
public struct ShaderError

3
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialGraphAsset.cs.meta


fileFormatVersion: 2
guid: 562bd27a5e73fc64d80a1d9d936ffbd5
timeCreated: 1464601236
licenseType: Pro
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialSlot.cs


return inputType == SlotValueType.Cubemap;
case SlotValueType.Dynamic:
case SlotValueType.Vector4:
return inputType == SlotValueType.Vector4
|| inputType == SlotValueType.Vector3
|| inputType == SlotValueType.Vector2
|| inputType == SlotValueType.Vector1
|| inputType == SlotValueType.Dynamic;
return inputType == SlotValueType.Vector3
|| inputType == SlotValueType.Vector2
|| inputType == SlotValueType.Vector1
|| inputType == SlotValueType.Dynamic;
return inputType == SlotValueType.Vector2
|| inputType == SlotValueType.Vector1
|| inputType == SlotValueType.Dynamic;
case SlotValueType.Vector1:
return inputType == SlotValueType.Vector4
|| inputType == SlotValueType.Vector3

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/NormalMaterialSlot.cs


public override string GetDefaultValue(GenerationMode generationMode)
{
return space.ToVariableName(InterpolatorType.Normal);
return string.Format("IN.{0}", space.ToVariableName(InterpolatorType.Normal));
}
public NeededCoordinateSpace RequiresNormal()

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/PositionMaterialSlot.cs


public override string GetDefaultValue(GenerationMode generationMode)
{
return space.ToVariableName(InterpolatorType.Position);
return string.Format("IN.{0}", space.ToVariableName(InterpolatorType.Position));
}
public NeededCoordinateSpace RequiresPosition()

7
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/SamplerStateShaderProperty.cs


return string.Empty;
}
public override string GetPropertyDeclarationString()
public override string GetPropertyDeclarationString(string delimiter = ";")
return string.Format(@"
#ifdef UNITY_COMPILER_HLSL
SamplerState {0};
#endif", referenceName);
return string.Format(@"SAMPLER2D({0}){1}", referenceName, delimiter);
}
public override PreviewProperty GetPreviewMaterialProperty()

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ScreenPositionMaterialSlot.cs


public override string GetDefaultValue(GenerationMode generationMode)
{
return ShaderGeneratorNames.ScreenPosition;
return string.Format("IN.{0}", ShaderGeneratorNames.ScreenPosition);
}
public bool RequiresScreenPosition()

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/TangentMaterialSlot.cs


public override string GetDefaultValue(GenerationMode generationMode)
{
return space.ToVariableName(InterpolatorType.Tangent);
return string.Format("IN.{0}", space.ToVariableName(InterpolatorType.Tangent));
}
public NeededCoordinateSpace RequiresTangent()

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/TextureShaderProperty.cs


return result.ToString();
}
public override string GetPropertyDeclarationString()
public override string GetPropertyDeclarationString(string delimiter = ";")
return "UNITY_DECLARE_TEX2D(" + referenceName + ");";
return string.Format("TEXTURE2D({0}){1} SAMPLER(sampler{0}){1}", referenceName, delimiter);
public override string GetInlinePropertyDeclarationString()
public override string GetPropertyAsArgumentString()
return "UNITY_DECLARE_TEX2D_NOSAMPLER(" + referenceName + ");";
return string.Format("TEXTURE2D_ARGS({0}, sampler{0})", referenceName);
}
public override PreviewProperty GetPreviewMaterialProperty()

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/UVMaterialSlot.cs


public override string GetDefaultValue(GenerationMode generationMode)
{
return string.Format("{0}.xy", channel.GetUVName());
return string.Format("IN.{0}.xy", channel.GetUVName());
}
public bool RequiresMeshUV(UVChannel channel)

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/Vector2ShaderProperty.cs


{
get { return new Vector4(value.x, value.y, 0, 0); }
}
public override string GetInlinePropertyDeclarationString()
{
return "float2 " + referenceName + ";";
}
public override PreviewProperty GetPreviewMaterialProperty()
{

7
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/Vector3ShaderProperty.cs


{
get { return new Vector4(value.x, value.y, value.z, 0); }
}
public override string GetInlinePropertyDeclarationString()
{
return "float3 " + referenceName + ";";
}
public override PreviewProperty GetPreviewMaterialProperty()
{
return new PreviewProperty(PropertyType.Vector3)

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/VectorShaderProperty.cs


return result.ToString();
}
public override string GetPropertyDeclarationString()
public override string GetPropertyDeclarationString(string delimiter = ";")
return "float4 " + referenceName + ";";
return string.Format("float4 {0}{1}", referenceName, delimiter);
}
}
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/VertexColorMaterialSlot.cs


public override string GetDefaultValue(GenerationMode generationMode)
{
return ShaderGeneratorNames.VertexColor;
return string.Format("IN.{0}", ShaderGeneratorNames.VertexColor);
}
public bool RequiresScreenPosition()

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ViewDirectionMaterialSlot.cs


public override string GetDefaultValue(GenerationMode generationMode)
{
return space.ToVariableName(InterpolatorType.ViewDirection);
return string.Format("IN.{0}", space.ToVariableName(InterpolatorType.ViewDirection));
}
public NeededCoordinateSpace RequiresViewDirection()

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Interfaces/NeededCoordinateSpace.cs


Tangent = 1 << 3
}
public enum CoordinateSpace : int
public enum CoordinateSpace
{
Object,
View,

26
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs


PBRMasterNode.MetallicSlotId,
PBRMasterNode.SmoothnessSlotId,
PBRMasterNode.OcclusionSlotId,
PBRMasterNode.AlphaSlotId
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
}
};

PBRMasterNode.SpecularSlotId,
PBRMasterNode.SmoothnessSlotId,
PBRMasterNode.OcclusionSlotId,
PBRMasterNode.AlphaSlotId
PBRMasterNode.AlphaSlotId,
PBRMasterNode.AlphaThresholdSlotId
}
};

foreach (var channel in graphRequiements.requiresMeshUVs.Distinct())
vertexInputs.AddShaderChunk(string.Format("float4 texcoord{0} : TEXCOORD{0};", (int)channel), false);
vertexInputs.AddShaderChunk("UNITY_VERTEX_INPUT_INSTANCE_ID", false);
vertexInputs.Deindent();
vertexInputs.AddShaderChunk("};", false);
}

usedSlots);
var graph = new ShaderGenerator();
graph.AddShaderChunk(shaderProperties.GetPropertiesDeclaration(2), false);
graph.AddShaderChunk(surfaceInputs.GetShaderString(2), false);
graph.AddShaderChunk(surfaceInputs.GetShaderString(2), false);
graph.AddShaderChunk(shaderProperties.GetPropertiesDeclaration(2), false);
graph.AddShaderChunk(surfaceVertexShader.GetShaderString(2), false);
graph.AddShaderChunk(surfaceDescriptionFunction.GetShaderString(2), false);

case PBRMasterNode.AlphaMode.AdditiveBlend:
defines.AddShaderChunk("#define _AlphaOut 1", true);
break;
case PBRMasterNode.AlphaMode.Clip:
defines.AddShaderChunk("#define _AlphaClip 1", true);
break;
if (masterNode.IsSlotConnected(PBRMasterNode.AlphaThresholdSlotId))
defines.AddShaderChunk("#define _AlphaClip 1", true);
surfaceOutputRemap.AddShaderChunk(slot.shaderOutputName
+ " = surf."
+ slot.shaderOutputName + ";", true);
surfaceOutputRemap.AddShaderChunk(string.Format("{0} = surf.{0};", slot.shaderOutputName), true);
}
if (!File.Exists(templateLocation))

var materialOptions = new SurfaceMaterialOptions();
switch (masterNode.alphaMode)
{
case PBRMasterNode.AlphaMode.Overwrite:
case PBRMasterNode.AlphaMode.Clip:
case PBRMasterNode.AlphaMode.Opaque:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.Zero;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightUnlitSubShader.cs


namespace UnityEditor.ShaderGraph
{
public class LightWeightUnlitSubShader
public class LightWeightUnlitSubShader : IUnlitSubShader
{
Pass m_UnlitPass = new Pass()
{

usedSlots);
var graph = new ShaderGenerator();
graph.AddShaderChunk(shaderProperties.GetPropertiesDeclaration(2), false);
graph.AddShaderChunk(surfaceInputs.GetShaderString(2), false);
graph.AddShaderChunk(surfaceInputs.GetShaderString(2), false);
graph.AddShaderChunk(shaderProperties.GetPropertiesDeclaration(2), false);
graph.AddShaderChunk(surfaceVertexShader.GetShaderString(2), false);
graph.AddShaderChunk(surfaceDescriptionFunction.GetShaderString(2), false);

return resultPass;
}
public IEnumerable<string> GetSubshader(UnlitMasterNode masterNode, GenerationMode mode)
public string GetSubshader(UnlitMasterNode masterNode, GenerationMode mode)
{
var subShader = new ShaderGenerator();
subShader.AddShaderChunk("SubShader", true);

subShader.Deindent();
subShader.AddShaderChunk("}", true);
return new[] { subShader.GetShaderString(0) };
return subShader.GetShaderString(0);
}
}
}

7
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/AbstractMaterialNode.cs


{
get { return true; }
}
public virtual bool allowedInRemapGraph
{
get { return true; }
}
public virtual bool allowedInMainGraph
{
get { return true; }

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Normal/NormalUnpackNode.cs


using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{

return
@"
{
Out = UnpackNormal(In);
Out = UnpackNormalmapRGorAG(In);
}
";
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Basic/ColorNode.cs


return;
visitor.AddShaderChunk(string.Format(
@"{0}4 {1} = IsGammaSpace() ? {0}4({2}, {3}, {4}, {5}) : {0}4(GammaToLinearSpace({0}3({2}, {3}, {4})), {5});"
@"{0}4 {1} = IsGammaSpace() ? {0}4({2}, {3}, {4}, {5}) : {0}4(SRGBToLinear({0}3({2}, {3}, {4})), {5});"
, precision
, GetVariableNameForNode()
, color.r

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/BitangentVectorNode.cs


public override string GetVariableNameForSlot(int slotId)
{
return space.ToVariableName(InterpolatorType.BiTangent);
return string.Format("IN.{0}", space.ToVariableName(InterpolatorType.BiTangent));
}
public NeededCoordinateSpace RequiresBitangent()

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/NormalVectorNode.cs


public override string GetVariableNameForSlot(int slotId)
{
return space.ToVariableName(InterpolatorType.Normal);
return string.Format("IN.{0}", space.ToVariableName(InterpolatorType.Normal));
}
public NeededCoordinateSpace RequiresNormal()

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/PositionNode.cs


public override string GetVariableNameForSlot(int slotId)
{
return space.ToVariableName(InterpolatorType.Position);
return string.Format("IN.{0}", space.ToVariableName(InterpolatorType.Position));
}
public NeededCoordinateSpace RequiresPosition()

10
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs


switch (m_ScreenSpaceType)
{
case ScreenSpaceType.Raw:
visitor.AddShaderChunk(string.Format("{0}4 {1} = {2};", precision, GetVariableNameForSlot(kOutputSlotId),
visitor.AddShaderChunk(string.Format("{0}4 {1} = In.{2};", precision, GetVariableNameForSlot(kOutputSlotId),
"float4((" + ShaderGeneratorNames.ScreenPosition + ".xy / " + ShaderGeneratorNames.ScreenPosition + ".w) * 2 - 1, 0, 0)"), true);
string.Format("float4((In.{0}.xy / In.{0}.w) * 2 - 1, 0, 0)", ShaderGeneratorNames.ScreenPosition)), true);
"float4((" + ShaderGeneratorNames.ScreenPosition + ".xy / " + ShaderGeneratorNames.ScreenPosition + ".w) * 2 - 1, 0, 0)"), true);
string.Format("float4((In.{0}.xy / In.{0}.w) * 2 - 1, 0, 0)", ShaderGeneratorNames.ScreenPosition)), true);
"float4(" + ShaderGeneratorNames.ScreenPosition + ".x * _ScreenParams.x / _ScreenParams.y, " + ShaderGeneratorNames.ScreenPosition + ".y, 0, 0)"), true);
string.Format("float4(In.{0}.x * _ScreenParams.x / _ScreenParams.y, In.{0}.y, 0, 0)", ShaderGeneratorNames.ScreenPosition)), true);
"float4(" + ShaderGeneratorNames.ScreenPosition + ".xy / " + ShaderGeneratorNames.ScreenPosition + ".w, 0, 0)"), true);
string.Format("float4(In.{0}.xy / In.{0}.w, 0, 0)", ShaderGeneratorNames.ScreenPosition)), true);
break;
}
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/TangentVectorNode.cs


public override string GetVariableNameForSlot(int slotId)
{
return space.ToVariableName(InterpolatorType.Tangent);
return string.Format("IN.{0}", space.ToVariableName(InterpolatorType.Tangent));
}
public NeededCoordinateSpace RequiresTangent()

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/UVNode.cs


public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
visitor.AddShaderChunk(precision + "4 " + GetVariableNameForSlot(OutputSlotId) + " = " + m_OutputChannel.GetUVName() + ";", true);
visitor.AddShaderChunk(string.Format("{0}4 {1} = IN.{2};", precision, GetVariableNameForSlot(OutputSlotId), m_OutputChannel.GetUVName()), true);
}
public bool RequiresMeshUV(UVChannel channel)

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/VertexColorNode.cs


public override string GetVariableNameForSlot(int slotId)
{
return ShaderGeneratorNames.VertexColor;
return string.Format("IN.{0}", ShaderGeneratorNames.VertexColor);
}
public bool RequiresVertexColor()

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/ViewDirectionNode.cs


public override string GetVariableNameForSlot(int slotId)
{
return space.ToVariableName(InterpolatorType.ViewDirection);
return string.Format("IN.{0}", space.ToVariableName(InterpolatorType.ViewDirection));
}
public NeededCoordinateSpace RequiresViewDirection()

5
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Matrix/TransformationMatrixNode.cs


using System.ComponentModel;
using UnityEditor.Graphing;
using System.Collections.Generic;
using UnityEditor.ShaderGraph.Drawing.Controls;

{TransformationMatrixType.ViewProjection, "UNITY_MATRIX_VP"},
{TransformationMatrixType.TransposeModelView, "UNITY_MATRIX_T_MV"},
{TransformationMatrixType.InverseTransposeModelView, "UNITY_MATRIX_IT_MV"},
{TransformationMatrixType.ObjectToWorld, "unity_ObjectToWorld"},
{TransformationMatrixType.WorldToObject, "unity_WorldToObject"},
{TransformationMatrixType.ObjectToWorld, "UNITY_MATRIX_M"},
{TransformationMatrixType.WorldToObject, "UNITY_MATRIX_I_M"},
};
[SerializeField]

18
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/SampleCubemapNode.cs


using System.Linq;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing.Controls;
namespace UnityEditor.ShaderGraph
{

// Node generations
public virtual void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
string result = string.Format("{0}4 {1} = texCUBElod ({2}, {0}4(reflect(-{3}, {4}), {5}));"
, precision
, GetVariableNameForSlot(OutputSlotId)
, GetSlotValue(CubemapInputId, generationMode)
, GetSlotValue(ViewDirInputId, generationMode)
, GetSlotValue(NormalInputId, generationMode)
, GetSlotValue(LODInputId, generationMode));
var id = GetSlotValue(CubemapInputId, generationMode);
string result = string.Format("{0}4 {1} = SAMPLE_TEXTURECUBE_LOD({2}, {3}, reflect(-{4}, {5}), {6});"
, precision
, GetVariableNameForSlot(OutputSlotId)
, id
, "sampler" + id
, GetSlotValue(ViewDirInputId, generationMode)
, GetSlotValue(NormalInputId, generationMode)
, GetSlotValue(LODInputId, generationMode));
visitor.AddShaderChunk(result, true);
}

32
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/SampleTexture2DNode.cs


var samplerSlot = FindInputSlot<MaterialSlot>(SamplerInput);
var edgesSampler = owner.GetEdges(samplerSlot.slotReference);
string result;
if (edgesSampler.Any())
{
result = string.Format(@"
#ifdef UNITY_COMPILER_HLSL
{0}4 {1} = {2}.Sample({3}, {4});
#else
{0}4 {1} = UNITY_SAMPLE_TEX2D({2}, {4});
#endif"
, precision
, GetVariableNameForSlot(OutputSlotRGBAId)
, GetSlotValue(TextureInputId, generationMode)
, GetSlotValue(SamplerInput, generationMode)
, uvName);
}
else
{
result = string.Format("{0}4 {1} = UNITY_SAMPLE_TEX2D({2},{3});"
, precision
, GetVariableNameForSlot(OutputSlotRGBAId)
, GetSlotValue(TextureInputId, generationMode)
, uvName);
}
var id = GetSlotValue(TextureInputId, generationMode);
var result = string.Format("{0}4 {1} = SAMPLE_TEXTURE2D({2}, {3}, {4});"
, precision
, GetVariableNameForSlot(OutputSlotRGBAId)
, id
, edgesSampler.Any() ? GetSlotValue(SamplerInput, generationMode) : "sampler" + id
, uvName);
visitor.AddShaderChunk(string.Format("{0}.rgb = UnpackNormal({0});", GetVariableNameForSlot(OutputSlotRGBAId)), true);
visitor.AddShaderChunk(string.Format("{0}.rgb = UnpackNormalmapRGorAG({0});", GetVariableNameForSlot(OutputSlotRGBAId)), true);
visitor.AddShaderChunk(string.Format("{0} {1} = {2}.r;", precision, GetVariableNameForSlot(OutputSlotRId), GetVariableNameForSlot(OutputSlotRGBAId)), true);
visitor.AddShaderChunk(string.Format("{0} {1} = {2}.g;", precision, GetVariableNameForSlot(OutputSlotGId), GetVariableNameForSlot(OutputSlotRGBAId)), true);

341
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Utility/SubGraphNode.cs


using System;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
using UnityEditor.Graphs;
public class SubGraphNode : AbstractSubGraphNode
public class SubGraphNode : AbstractMaterialNode
, IGeneratesFunction
, IMayRequireNormal
, IMayRequireTangent
, IMayRequireBitangent
, IMayRequireMeshUV
, IMayRequireScreenPosition
, IMayRequireViewDirection
, IMayRequirePosition
, IMayRequireVertexColor
, IMayRequireTime
{
[SerializeField]
private string m_SerializedSubGraph = string.Empty;

public MaterialSubGraphAsset subGraph;
}
protected override AbstractSubGraph referencedGraph
protected SubGraph referencedGraph
{
get
{

public MaterialSubGraphAsset subGraphAsset {get; set; }
#endif
public override INode outputNode
public INode outputNode
{
get
{

}
}
public override bool hasPreview
{
get { return referencedGraph != null; }
}
public override PreviewMode previewMode
{
get
{
if (referencedGraph == null)
return PreviewMode.Preview2D;
return PreviewMode.Preview3D;
}
}
public void GenerateNodeCode(ShaderGenerator shaderBodyVisitor, GenerationMode generationMode)
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
var outputString = new ShaderGenerator();
outputString.AddShaderChunk("// Subgraph for node " + GetVariableNameForNode(), false);
foreach (var outSlot in referencedGraph.graphOutputs)
visitor.AddShaderChunk(string.Format("{0} {1};", NodeUtils.ConvertConcreteSlotValueTypeToString(precision, outSlot.concreteValueType), GetVariableNameForSlot(outSlot.id)), true);
// Step 1...
// find out which output slots are actually used
//var validOutputSlots = NodeUtils.GetSlotsThatOutputToNodeRecurse(this, (graph as BaseMaterialGraph).masterNode);
s_TempSlots.Clear();
GetOutputSlots(s_TempSlots);
foreach (var slot in s_TempSlots)
var arguments = new List<string>();
foreach (var prop in referencedGraph.graphInputs)
var outDimension = NodeUtils.ConvertConcreteSlotValueTypeToString(precision, slot.concreteValueType);
outputString.AddShaderChunk(string.Format("{0} {1} = 0;", outDimension, GetVariableNameForSlot(slot.id)), false);
var inSlotId = prop.guid.GetHashCode();
if (prop is TextureShaderProperty)
arguments.Add(string.Format("TEXTURE2D_PARAM({0}, sampler{0})", GetSlotValue(inSlotId, generationMode)));
else if (prop is CubemapShaderProperty)
arguments.Add(string.Format("TEXTURECUBE_PARAM({0}, sampler{0})", GetSlotValue(inSlotId, generationMode)));
else
arguments.Add(GetSlotValue(inSlotId, generationMode));
// Step 2...
// Go into the subgraph
outputString.AddShaderChunk("{", false);
outputString.Indent();
// pass surface inputs through
arguments.Add("IN");
foreach (var outSlot in referencedGraph.graphOutputs)
arguments.Add(GetVariableNameForSlot(outSlot.id));
// Step 3...
// For each input that is used and connects through we want to generate code.
// First we assign the input variables to the subgraph
// we do this by renaming the properties to be the names of where the variables come from
// weird, but works.
var sSubGraph = SerializationHelper.Serialize(subGraphAsset.subGraph);
var dSubGraph = SerializationHelper.Deserialize<SubGraph>(sSubGraph, null);
visitor.AddShaderChunk(
string.Format("{0}({1});"
, SubGraphFunctionName()
, arguments.Aggregate((current, next) => string.Format("{0}, {1}", current, next)))
, false);
}
var subGraphInputs = dSubGraph.properties;
public void OnEnable()
{
UpdateSlots();
}
var propertyGen = new PropertyCollector();
dSubGraph.CollectShaderProperties(propertyGen, GenerationMode.ForReals);
public virtual void UpdateSlots()
{
var validNames = new List<int>();
if (referencedGraph == null)
{
RemoveSlotsNameNotMatching(validNames);
return;
}
foreach (var prop in subGraphInputs)
var props = referencedGraph.properties;
foreach (var prop in props)
var inSlotId = prop.guid.GetHashCode();
var inSlot = FindInputSlot<MaterialSlot>(inSlotId);
var propType = prop.propertyType;
SlotValueType slotType;
var edges = owner.GetEdges(inSlot.slotReference).ToArray();
switch (propType)
{
case PropertyType.Color:
slotType = SlotValueType.Vector4;
break;
case PropertyType.Texture:
slotType = SlotValueType.Texture2D;
break;
case PropertyType.Cubemap:
slotType = SlotValueType.Cubemap;
break;
case PropertyType.Float:
slotType = SlotValueType.Vector1;
break;
case PropertyType.Vector2:
slotType = SlotValueType.Vector2;
break;
case PropertyType.Vector3:
slotType = SlotValueType.Vector3;
break;
case PropertyType.Vector4:
slotType = SlotValueType.Vector4;
break;
case PropertyType.Matrix2:
slotType = SlotValueType.Matrix2;
break;
case PropertyType.Matrix3:
slotType = SlotValueType.Matrix3;
break;
case PropertyType.Matrix4:
slotType = SlotValueType.Matrix4;
break;
default:
throw new ArgumentOutOfRangeException();
}
string varValue = inSlot.GetDefaultValue(generationMode);
if (edges.Any())
var id = prop.guid.GetHashCode();
MaterialSlot slot = MaterialSlot.CreateMaterialSlot(slotType, id, prop.displayName, prop.referenceName, SlotType.Input, prop.defaultValue);
// copy default for texture for niceness
if (slotType == SlotValueType.Texture2D && propType == PropertyType.Texture)
var fromSocketRef = edges[0].outputSlot;
var fromNode = owner.GetNodeFromGuid<AbstractMaterialNode>(fromSocketRef.nodeGuid);
if (fromNode != null)
{
var slot = fromNode.FindOutputSlot<MaterialSlot>(fromSocketRef.slotId);
if (slot != null)
prop.overrideReferenceName = fromNode.GetSlotValue(slot.id, generationMode);
}
var tSlot = slot as Texture2DInputMaterialSlot;
var tProp = prop as TextureShaderProperty;
if (tSlot != null && tProp != null)
tSlot.texture = tProp.value.texture;
else if (inSlot is Texture2DInputMaterialSlot)
// copy default for cubemap for niceness
else if (slotType == SlotValueType.Cubemap && propType == PropertyType.Cubemap)
prop.overrideReferenceName = ((Texture2DInputMaterialSlot)inSlot).GetDefaultValue(generationMode);
var tSlot = slot as CubemapInputMaterialSlot;
var tProp = prop as CubemapShaderProperty;
if (tSlot != null && tProp != null)
tSlot.cubemap = tProp.value.cubemap;
else
AddSlot(slot);
validNames.Add(id);
}
var subGraphOutputNode = outputNode;
if (outputNode != null)
{
foreach (var slot in NodeExtensions.GetInputSlots<MaterialSlot>(subGraphOutputNode))
var varName = prop.referenceName;
outputString.AddShaderChunk(NodeUtils.ConvertConcreteSlotValueTypeToString(precision, inSlot.concreteValueType)
+ " "
+ varName
+ " = "
+ varValue
+ ";", false);
AddSlot(MaterialSlot.CreateMaterialSlot(slot.valueType, slot.id, slot.RawDisplayName(), slot.shaderOutputName, SlotType.Output, Vector4.zero));
validNames.Add(slot.id);
// Step 4...
// Using the inputs we can now generate the shader body :)
var bodyGenerator = new ShaderGenerator();
dSubGraph.GenerateNodeCode(bodyGenerator, GenerationMode.ForReals);
var subGraphOutputNode = dSubGraph.outputNode;
outputString.AddShaderChunk(bodyGenerator.GetShaderString(0), false);
RemoveSlotsNameNotMatching(validNames);
}
// Step 5...
// Copy the outputs to the parent context name);
s_TempSlots.Clear();
GetOutputSlots(s_TempSlots);
foreach (var slot in s_TempSlots)
public override void ValidateNode()
{
if (referencedGraph != null)
var inputValue = subGraphOutputNode.GetSlotValue(slot.id, GenerationMode.ForReals);
referencedGraph.OnEnable();
referencedGraph.ValidateGraph();
outputString.AddShaderChunk(
GetVariableNameForSlot(slot.id)
+ " = "
+ inputValue
+ ";", false);
if (referencedGraph.GetNodes<INode>().Any(x => x.hasError))
hasError = true;
outputString.Deindent();
outputString.AddShaderChunk("}", false);
outputString.AddShaderChunk("// Subgraph ends", false);
base.ValidateNode();
}
public override void CollectShaderProperties(PropertyCollector visitor, GenerationMode generationMode)
{
base.CollectShaderProperties(visitor, generationMode);
if (referencedGraph == null)
return;
shaderBodyVisitor.AddShaderChunk(outputString.GetShaderString(0), true);
referencedGraph.CollectShaderProperties(visitor, GenerationMode.ForReals);
public void OnEnable()
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
UpdateSlots();
base.CollectPreviewMaterialProperties(properties);
if (referencedGraph == null)
return;
properties.AddRange(referencedGraph.GetPreviewProperties());
}
private string SubGraphFunctionName()
{
var functionName = subGraphAsset != null ? NodeUtils.GetHLSLSafeName(subGraphAsset.name) : "ERROR";
return string.Format("{0}_{1}", functionName, GuidEncoder.Encode(referencedGraph.guid));
}
public virtual void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode)
{
if (subGraphAsset == null || referencedGraph == null)
return;
referencedGraph.GenerateNodeFunction(registry, GenerationMode.ForReals);
referencedGraph.GenerateSubGraphFunction(SubGraphFunctionName(), registry, ShaderGraphRequirements.FromNodes(new List<INode> {this}), GenerationMode.ForReals);
}
public NeededCoordinateSpace RequiresNormal()
{
if (referencedGraph == null)
return NeededCoordinateSpace.None;
return referencedGraph.activeNodes.OfType<IMayRequireNormal>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresNormal();
return mask;
});
}
public bool RequiresMeshUV(UVChannel channel)
{
if (referencedGraph == null)
return false;
return referencedGraph.activeNodes.OfType<IMayRequireMeshUV>().Any(x => x.RequiresMeshUV(channel));
}
public bool RequiresScreenPosition()
{
if (referencedGraph == null)
return false;
return referencedGraph.activeNodes.OfType<IMayRequireScreenPosition>().Any(x => x.RequiresScreenPosition());
}
public NeededCoordinateSpace RequiresViewDirection()
{
if (referencedGraph == null)
return NeededCoordinateSpace.None;
return referencedGraph.activeNodes.OfType<IMayRequireViewDirection>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresViewDirection();
return mask;
});
}
public NeededCoordinateSpace RequiresPosition()
{
if (referencedGraph == null)
return NeededCoordinateSpace.None;
return referencedGraph.activeNodes.OfType<IMayRequirePosition>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresPosition();
return mask;
});
}
public NeededCoordinateSpace RequiresTangent()
{
if (referencedGraph == null)
return NeededCoordinateSpace.None;
return referencedGraph.activeNodes.OfType<IMayRequireTangent>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresTangent();
return mask;
});
}
public bool RequiresTime()
{
if (referencedGraph == null)
return false;
return referencedGraph.activeNodes.OfType<IMayRequireTime>().Any(x => x.RequiresTime());
}
public NeededCoordinateSpace RequiresBitangent()
{
if (referencedGraph == null)
return NeededCoordinateSpace.None;
return referencedGraph.activeNodes.OfType<IMayRequireBitangent>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresBitangent();
return mask;
});
}
public bool RequiresVertexColor()
{
if (referencedGraph == null)
return false;
return referencedGraph.activeNodes.OfType<IMayRequireVertexColor>().Any(x => x.RequiresVertexColor());
}
}
}

103
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/SubGraph.cs


namespace UnityEditor.ShaderGraph
{
[Serializable]
public class SubGraph : AbstractSubGraph
public class SubGraph : AbstractMaterialGraph
, IGeneratesBodyCode
, IGeneratesFunction
{
[NonSerialized]
private SubGraphOutputNode m_OutputNode;

base.AddNode(node);
}
public override IEnumerable<AbstractMaterialNode> activeNodes
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
foreach (var node in activeNodes)
{
if (node is IGeneratesBodyCode)
(node as IGeneratesBodyCode).GenerateNodeCode(visitor, generationMode);
}
}
public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode)
{
foreach (var node in activeNodes)
{
if (node is IGeneratesFunction)
(node as IGeneratesFunction).GenerateNodeFunction(registry, generationMode);
}
}
public IEnumerable<IShaderProperty> graphInputs
{
get { return properties.OrderBy(x => x.guid); }
}
public IEnumerable<MaterialSlot> graphOutputs
{
get
{
return outputNode != null ? outputNode.graphOutputs : new List<MaterialSlot>();
}
}
public void GenerateSubGraphFunction(string functionName, FunctionRegistry registry, ShaderGraphRequirements reqs, GenerationMode generationMode)
{
registry.ProvideFunction(functionName, s =>
{
s.AppendLine("// Subgraph function");
// Generate arguments... first INPUTS
var arguments = new List<string>();
foreach (var prop in graphInputs)
arguments.Add(string.Format("{0}", prop.GetPropertyAsArgumentString()));
// now pass surface inputs
arguments.Add("SurfaceInputs IN");
// Now generate outputs
foreach (var slot in graphOutputs)
arguments.Add(string.Format("out {0} {1}", slot.concreteValueType.ToString(outputNode.precision), slot.shaderOutputName));
// Create the function protoype from the arguments
s.AppendLine("void {0}({1})"
, functionName
, arguments.Aggregate((current, next) => string.Format("{0}, {1}", current, next)));
// now generate the function
using (s.BlockScope())
{
// Just grab the body from the active nodes
var bodyGenerator = new ShaderGenerator();
GenerateNodeCode(bodyGenerator, GenerationMode.ForReals);
if (outputNode != null)
outputNode.RemapOutputs(bodyGenerator, GenerationMode.ForReals);
s.Append(bodyGenerator.GetShaderString(1));
}
});
}
public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode)
{
// if we are previewing the graph we need to
// export 'exposed props' if we are 'for real'
// then we are outputting the graph in the
// nested context and the needed values will
// be copied into scope.
if (generationMode == GenerationMode.Preview)
{
foreach (var prop in properties)
collector.AddShaderProperty(prop);
}
foreach (var node in activeNodes)
{
if (node is IGenerateProperties)
(node as IGenerateProperties).CollectShaderProperties(collector, generationMode);
}
}
public IEnumerable<PreviewProperty> GetPreviewProperties()
{
List<PreviewProperty> props = new List<PreviewProperty>();
foreach (var node in activeNodes)
node.CollectPreviewMaterialProperties(props);
return props;
}
public IEnumerable<AbstractMaterialNode> activeNodes
{
get
{

17
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/SubGraphOutputNode.cs


using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing.Controls;

RemoveSlot(index);
}
public override bool allowedInRemapGraph { get { return false; } }
public void RemapOutputs(ShaderGenerator visitor, GenerationMode generationMode)
{
foreach (var slot in graphOutputs)
visitor.AddShaderChunk(string.Format("{0} = {1};", slot.shaderOutputName, GetSlotValue(slot.id, generationMode)), true);
}
public IEnumerable<MaterialSlot> graphOutputs
{
get
{
return NodeExtensions.GetInputSlots<MaterialSlot>(this).OrderBy(x=>x.id);
}
}
}
}

48
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/GraphUtil.cs


vertexInputIndex++;
}
vertexInputs.AddShaderChunk("UNITY_VERTEX_INPUT_INSTANCE_ID", false);
vertexInputs.Deindent();
vertexInputs.AddShaderChunk("};", false);
}

finalBuilder.AppendLines(shaderProperties.GetPropertiesBlock(0));
}
finalBuilder.AppendLine(@"CGINCLUDE");
finalBuilder.AppendLine(@"#include ""UnityCG.cginc""");
finalBuilder.AppendLine(@"HLSLINCLUDE");
finalBuilder.AppendLine("#define USE_LEGACY_UNITY_MATRIX_VARIABLES");
finalBuilder.AppendLine(@"#include ""CoreRP/ShaderLibrary/Common.hlsl""");
finalBuilder.AppendLine(@"#include ""CoreRP/ShaderLibrary/Packing.hlsl""");
finalBuilder.AppendLine(@"#include ""CoreRP/ShaderLibrary/Color.hlsl""");
finalBuilder.AppendLine(@"#include ""ShaderGraphLibrary/Functions.hlsl""");
finalBuilder.AppendLine(@"#include ""ShaderGraphLibrary/ShaderVariables.hlsl""");
finalBuilder.AppendLine(@"#include ""ShaderGraphLibrary/ShaderVariablesFunctions.hlsl""");
finalBuilder.AppendLines(shaderProperties.GetPropertiesDeclaration(0));
finalBuilder.AppendLines(surfaceInputs.GetShaderString(0));
finalBuilder.AppendLines(surfaceInputs.GetShaderString(0));
finalBuilder.AppendLines(shaderProperties.GetPropertiesDeclaration(0));
finalBuilder.AppendLine(@"ENDCG");
finalBuilder.AppendLine(@"ENDHLSL");
finalBuilder.AppendLines(ShaderGenerator.GetPreviewSubShader(node, requirements));
ListPool<INode>.Release(activeNodeList);

surfaceDescriptionFunction.Indent();
surfaceDescriptionFunction.AddShaderChunk(String.Format("{0} surface = ({0})0;", surfaceDescriptionName), false);
foreach (CoordinateSpace space in Enum.GetValues(typeof(CoordinateSpace)))
{
var neededCoordinateSpace = space.ToNeededCoordinateSpace();
if ((requirements.requiresNormal & neededCoordinateSpace) > 0)
surfaceDescriptionFunction.AddShaderChunk(String.Format("float3 {0} = IN.{0};", space.ToVariableName(InterpolatorType.Normal)), false);
if ((requirements.requiresTangent & neededCoordinateSpace) > 0)
surfaceDescriptionFunction.AddShaderChunk(String.Format("float3 {0} = IN.{0};", space.ToVariableName(InterpolatorType.Tangent)), false);
if ((requirements.requiresBitangent & neededCoordinateSpace) > 0)
surfaceDescriptionFunction.AddShaderChunk(String.Format("float3 {0} = IN.{0};", space.ToVariableName(InterpolatorType.BiTangent)), false);
if ((requirements.requiresViewDir & neededCoordinateSpace) > 0)
surfaceDescriptionFunction.AddShaderChunk(String.Format("float3 {0} = IN.{0};", space.ToVariableName(InterpolatorType.ViewDirection)), false);
if ((requirements.requiresPosition & neededCoordinateSpace) > 0)
surfaceDescriptionFunction.AddShaderChunk(String.Format("float3 {0} = IN.{0};", space.ToVariableName(InterpolatorType.Position)), false);
}
if (requirements.requiresScreenPosition)
surfaceDescriptionFunction.AddShaderChunk(String.Format("float4 {0} = IN.{0};", ShaderGeneratorNames.ScreenPosition), false);
if (requirements.requiresVertexColor)
surfaceDescriptionFunction.AddShaderChunk(String.Format("float4 {0} = IN.{0};", ShaderGeneratorNames.VertexColor), false);
foreach (var channel in requirements.requiresMeshUVs.Distinct())
surfaceDescriptionFunction.AddShaderChunk(String.Format("half4 {0} = IN.{0};", channel.GetUVName()), false);
graph.CollectShaderProperties(shaderProperties, mode);
foreach (var activeNode in activeNodeList.OfType<AbstractMaterialNode>())

{
var outputRef = foundEdges[0].outputSlot;
var fromNode = graph.GetNodeFromGuid<AbstractMaterialNode>(outputRef.nodeGuid);
surfaceDescriptionFunction.AddShaderChunk(String.Format("surface.{0} = {1};", NodeUtils.GetHLSLSafeName(input.shaderOutputName), fromNode.GetVariableNameForSlot(outputRef.slotId)), true);
surfaceDescriptionFunction.AddShaderChunk(string.Format("surface.{0} = {1};", NodeUtils.GetHLSLSafeName(input.shaderOutputName), fromNode.GetVariableNameForSlot(outputRef.slotId)), true);
surfaceDescriptionFunction.AddShaderChunk(String.Format("surface.{0} = {1};", NodeUtils.GetHLSLSafeName(input.shaderOutputName), input.GetDefaultValue(mode)), true);
surfaceDescriptionFunction.AddShaderChunk(string.Format("surface.{0} = {1};", NodeUtils.GetHLSLSafeName(input.shaderOutputName), input.GetDefaultValue(mode)), true);
}
}
}

surfaceDescriptionFunction.AddShaderChunk(String.Format("surface.{0} = {1};", NodeUtils.GetHLSLSafeName(slot.shaderOutputName), masterNode.GetVariableNameForSlot(slot.id)), true);
surfaceDescriptionFunction.AddShaderChunk(string.Format("surface.{0} = {1};", NodeUtils.GetHLSLSafeName(slot.shaderOutputName), masterNode.GetVariableNameForSlot(slot.id)), true);
}
}

69
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGenerator.cs


namespace UnityEditor.ShaderGraph
{
public static class ShaderGeneratorNames
{
private static string[] UV = {"uv0", "uv1", "uv2", "uv3"};
public static int UVCount = 4;
public const string ScreenPosition = "screenPosition";
public const string VertexColor = "vertexColor";
public static string GetUVName(this UVChannel channel)
{
return UV[(int)channel];
}
}
public enum UVChannel
{
uv0 = 0,
uv1 = 1,
uv2 = 2,
uv3 = 3,
}
public class ShaderGenerator
{
private struct ShaderChunk

switch (convertFromType)
{
case ConcreteSlotValueType.Vector1:
return string.Format("({0}{1})", rawOutput, ".xx");
return string.Format("({0}.xx)", rawOutput);
case ConcreteSlotValueType.Vector3:
case ConcreteSlotValueType.Vector4:
return string.Format("({0}.xy)", rawOutput);

switch (convertFromType)
{
case ConcreteSlotValueType.Vector1:
return string.Format("({0}{1})", rawOutput, ".xxx");
return string.Format("({0}.xxx)", rawOutput);
case ConcreteSlotValueType.Vector2:
return string.Format("({0}3({1}.x, {1}.y, 0.0))", node.precision, rawOutput);
case ConcreteSlotValueType.Vector4:
return string.Format("({0}.xyz)", rawOutput);
default:

switch (convertFromType)
{
case ConcreteSlotValueType.Vector1:
return string.Format("({0}{1})", rawOutput, ".xxxx");
return string.Format("({0}.xxxx)", rawOutput);
case ConcreteSlotValueType.Vector2:
return string.Format("({0}4({1}.x, {1}.y, 0.0, 1.0))", node.precision, rawOutput);
case ConcreteSlotValueType.Vector3:
return string.Format("({0}4({1}.x, {1}.y, {1}.z, 1.0))", node.precision, rawOutput);
default:
return kErrorString;
}

var convertFromType = slot.concreteValueType;
// preview is always dimension 4, and we always ignore alpha
// preview is always dimension 4
switch (convertFromType)
{
case ConcreteSlotValueType.Vector1:

m_transforms[(int)CoordinateSpace.World, (int)CoordinateSpace.World] = new TransformDesc[] {};
m_transforms[(int)CoordinateSpace.Tangent, (int)CoordinateSpace.Tangent] = new TransformDesc[] {};
m_transforms[(int)CoordinateSpace.Object, (int)CoordinateSpace.World]
= new TransformDesc[] {new TransformDesc("unity_ObjectToWorld")};
= new TransformDesc[] {new TransformDesc(MatrixNames.Model)};
= new TransformDesc[] {new TransformDesc("UNITY_MATRIX_I_V")};
= new TransformDesc[] {new TransformDesc(MatrixNames.ViewInverse) };
= new TransformDesc[] {new TransformDesc("unity_WorldToObject")};
= new TransformDesc[] {new TransformDesc(MatrixNames.ModelInverse)};
= new TransformDesc[] {new TransformDesc("UNITY_MATRIX_V")};
= new TransformDesc[] {new TransformDesc(MatrixNames.View)};
for (var from = CoordinateSpace.Object; from != CoordinateSpace.Tangent; from++)
{
for (var to = CoordinateSpace.Object; to != CoordinateSpace.Tangent; to++)

public static string EmitTransform(TransformDesc[] matrices, TransformDesc[] invMatrices, string variable, bool isAffine, bool noMatrixCast, bool inverseTranspose)
{
// Use inverse transpose for situations where
// scale needs to be considered (normals)
if (isAffine)
{
variable = string.Format("float4({0},1.0)", variable);

{
matrix = "(float3x3)" + matrix;
}
// if the matrix is NOT a transpose type
// invert the order of multiplication
// it is implicit transpose.
if (m.transpose)
inverseTranspose = !inverseTranspose;
variable = inverseTranspose

{
var name = preferedCoordinateSpace.ToVariableName(InterpolatorType.ViewDirection);
interpolators.AddShaderChunk(string.Format("float3 {0} : TEXCOORD{1};", name, interpolatorIndex), false);
vertexShader.AddShaderChunk(string.Format("o.{0} = {1};", name, ConvertBetweenSpace("ObjSpaceViewDir(v.vertex)", CoordinateSpace.Object, preferedCoordinateSpace, InputType.Vector)), false);
var worldSpaceViewDir = "SafeNormalize(_WorldSpaceCameraPos.xyz - mul(GetObjectToWorldMatrix(), float4(v.vertex.xyz, 1.0)).xyz)";
vertexShader.AddShaderChunk(string.Format("o.{0} = {1};", name, ConvertBetweenSpace(worldSpaceViewDir, CoordinateSpace.World, preferedCoordinateSpace, InputType.Vector)), false);
pixelShader.AddShaderChunk(string.Format("float3 {0} = normalize(IN.{0});", name), false);
interpolatorIndex++;
}

{
interpolators.AddShaderChunk(string.Format("half4 {0} : TEXCOORD{1};", channel.GetUVName(), interpolatorIndex == 0 ? "" : interpolatorIndex.ToString()), false);
vertexShader.AddShaderChunk(string.Format("o.{0} = v.texcoord{1};", channel.GetUVName(), (int)channel), false);
pixelShader.AddShaderChunk(string.Format("float4 {0} = IN.{0};", channel.GetUVName()), false);
pixelShader.AddShaderChunk(string.Format("float4 {0} = IN.{0};", channel.GetUVName()), false);
interpolatorIndex++;
}

Pass
{
CGPROGRAM
HLSLPROGRAM
#include ""UnityCG.cginc""
struct GraphVertexOutput
{

v = PopulateVertexData(v);
GraphVertexOutput o;
o.position = UnityObjectToClipPos(v.vertex);
float3 positionWS = TransformObjectToWorld(v.vertex);
o.position = TransformWorldToHClip(positionWS);
fixed4 frag (GraphVertexOutput IN) : SV_Target
float4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}

SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
${SurfaceOutputRemap}
}
ENDCG
ENDHLSL
}
}";
}

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/DefaultShaderIncludes.cs


using System.IO;
namespace UnityEditor
{
internal static class DefaultShaderIncludes

{
return new[]
{
"Assets/ScriptableRenderPipeline/",
"Assets/SRP/ScriptableRenderPipeline/LightweightPipeline/Shaders"
Path.GetFullPath("Assets/UnityShaderEditor"),
Path.GetFullPath("Packages/com.unity.shadergraph"),
};
}
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/MaterialGraphEditWindow.cs


graphObject.graph.ValidateGraph();
}
void UpdateAbstractSubgraphOnDisk<T>(string path) where T : AbstractSubGraph
void UpdateAbstractSubgraphOnDisk<T>(string path) where T : SubGraph
{
var graph = graphObject.graph as T;
if (graph == null)

{
if (graphObject != null && graphObject.graph != null)
{
var subNodes = graphObject.graph.GetNodes<AbstractSubGraphNode>();
var subNodes = graphObject.graph.GetNodes<SubGraphNode>();
foreach (var node in subNodes)
node.UpdateSlots();
}

27
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/PreviewManager.cs


m_DirtyPreviews.UnionWith(m_TimeDependentPreviews);
PropagateNodeSet(m_DirtyPreviews);
m_NodesWith3DPreview.Clear();
foreach (var index in m_DirtyPreviews)
{
var node = (AbstractMaterialNode)m_Graph.GetNodeFromTempId(m_Identifiers[index]);
if (node.previewMode == PreviewMode.Preview3D)
m_NodesWith3DPreview.Add(node.tempId.index);
}
PropagateNodeSet(m_NodesWith3DPreview);
foreach (var index in m_DirtyPreviews)
{
var renderData = m_RenderDatas[index];
renderData.previewMode = m_NodesWith3DPreview.Contains(renderData.shaderData.node.tempId.index) ? PreviewMode.Preview3D : PreviewMode.Preview2D;
}
// Find nodes we need properties from
m_PropertyNodes.Clear();
m_PropertyNodes.UnionWith(m_DirtyPreviews);

if (m_DirtyShaders.Any())
{
PropagateNodeSet(m_DirtyShaders);
m_NodesWith3DPreview.Clear();
foreach (var index in m_DirtyShaders)
{
var node = (AbstractMaterialNode)m_Graph.GetNodeFromTempId(m_Identifiers[index]);
if (node.previewMode == PreviewMode.Preview3D)
m_NodesWith3DPreview.Add(node.tempId.index);
}
PropagateNodeSet(m_NodesWith3DPreview);
foreach (var index in m_DirtyShaders)
{
var renderData = m_RenderDatas[index];
renderData.previewMode = m_NodesWith3DPreview.Contains(renderData.shaderData.node.tempId.index) ? PreviewMode.Preview3D : PreviewMode.Preview2D;
}
var masterNodes = new List<MasterNode>();
var uberNodes = new List<INode>();

5
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Resources.meta


fileFormatVersion: 2
guid: c34a1714ab2ee6c47b8fb9a14777df23
guid: 64c9c5df0004c44f0896e816c69c7aa1
timeCreated: 1485544540
licenseType: Pro
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

92
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRExtraPasses.template


Pass
{
Tags{"LightMode" = "ShadowCaster"}
Pass
{
Tags{"LightMode" = "ShadowCaster"}
ZWrite On ZTest LEqual
ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 2.0
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#include "UnityCG.cginc"
#include "LightweightPassShadow.cginc"
ENDCG
}
#include "LWRP/Shaders/LightweightPassShadow.hlsl"
ENDHLSL
}
Pass
{
Tags{"LightMode" = "DepthOnly"}
Pass
{
Tags{"LightMode" = "DepthOnly"}
ZWrite On
ColorMask 0
ZWrite On
ColorMask 0
CGPROGRAM
#pragma target 2.0
#pragma vertex vert
#pragma fragment frag
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
#include "LWRP/Shaders/LightweightShaderLibrary/Core.hlsl"
float4 vert(float4 pos : POSITION) : SV_POSITION
{
return UnityObjectToClipPos(pos);
}
float4 vert(float4 pos : POSITION) : SV_POSITION
{
return TransformObjectToHClip(pos.xyz);
}
half4 frag() : SV_TARGET
{
return 0;
}
ENDHLSL
}
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
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma vertex LightweightVertexMeta
#pragma fragment LightweightFragmentMeta
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICSPECGLOSSMAP
#pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature EDITOR_VISUALIZATION
#pragma shader_feature _SPECGLOSSMAP
#include "LWRP/Shaders/LightweightPassMeta.hlsl"
ENDHLSL
}

96
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRForwardPass.template


${Culling}
${ZTest}
${ZWrite}
CGPROGRAM
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
// -------------------------------------
// Lightweight Pipeline keywords
// We have no good approach exposed to skip shader variants, e.g, ideally we would like to skip _CASCADE for all puctual lights
// Lightweight combines light classification and shadows keywords to reduce shader variants.
// Lightweight shader library declares defines based on these keywords to avoid having to check them in the shaders
// Core.hlsl defines _MAIN_LIGHT_DIRECTIONAL and _MAIN_LIGHT_SPOT (point lights can't be main light)
// Shadow.hlsl defines _SHADOWS_ENABLED, _SHADOWS_SOFT, _SHADOWS_CASCADE, _SHADOWS_PERSPECTIVE
#pragma multi_compile _ _MAIN_LIGHT_DIRECTIONAL_SHADOW _MAIN_LIGHT_DIRECTIONAL_SHADOW_CASCADE _MAIN_LIGHT_DIRECTIONAL_SHADOW_SOFT _MAIN_LIGHT_DIRECTIONAL_SHADOW_CASCADE_SOFT _MAIN_LIGHT_SPOT_SHADOW _MAIN_LIGHT_SPOT_SHADOW_SOFT
#pragma multi_compile _MAIN_DIRECTIONAL_LIGHT _MAIN_SPOT_LIGHT
#pragma multi_compile _ _VERTEX_LIGHTS
// -------------------------------------
// Unity defined keywords
#pragma multi_compile _ _HARD_SHADOWS _SOFT_SHADOWS _HARD_SHADOWS_CASCADES _SOFT_SHADOWS_CASCADES
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile_instancing
#pragma glsl
#pragma debug
#include "LightweightLighting.cginc"
#include "LWRP/Shaders/LightweightShaderLibrary/Core.hlsl"
#include "LWRP/Shaders/LightweightShaderLibrary/Lighting.hlsl"
#include "CoreRP/ShaderLibrary/Color.hlsl"
#include "ShaderGraphLibrary/Functions.hlsl"
float4 position : SV_POSITION;
#ifdef LIGHTMAP_ON
float4 lightmapUV : TEXCOORD0;
#else
float4 vertexSH : TEXCOORD0;
#endif
float4 clipPos : SV_POSITION;
float4 lightmapUVOrVertexSH : TEXCOORD0;
UNITY_VERTEX_OUTPUT_STEREO
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
float3 lwWNormal = normalize(UnityObjectToWorldNormal(v.normal));
float4 lwWorldPos = mul(unity_ObjectToWorld, v.vertex);
float4 clipPos = mul(UNITY_MATRIX_VP, lwWorldPos);
float3 lwWNormal = TransformObjectToWorldNormal(v.normal);
float3 lwWorldPos = TransformObjectToWorld(v.vertex.xyz);
float4 clipPos = TransformWorldToHClip(lwWorldPos);
#ifdef LIGHTMAP_ON
o.lightmapUV.zw = v.texcoord1 * unity_LightmapST.xy + unity_LightmapST.zw;
#else
o.vertexSH = half4(EvaluateSHPerVertex(lwWNormal), 0.0);
#endif
// We either sample GI from lightmap or SH. lightmap UV and vertex SH coefficients
// are packed in lightmapUVOrVertexSH to save interpolator.
// The following funcions initialize
OUTPUT_LIGHTMAP_UV(v.lightmapUV, unity_LightmapST, o.lightmapUVOrVertexSH);
OUTPUT_SH(lwWNormal, o.lightmapUVOrVertexSH);
o.fogFactorAndVertexLight.yzw = VertexLighting(lwWorldPos.xyz, lwWNormal);
o.fogFactorAndVertexLight.x = ComputeFogFactor(clipPos.z);
o.position = clipPos;
half3 vertexLight = VertexLighting(lwWorldPos, lwWNormal);
half fogFactor = ComputeFogFactor(clipPos.z);
o.fogFactorAndVertexLight = half4(fogFactor, vertexLight);
o.clipPos = clipPos;
fixed4 frag (GraphVertexOutput IN) : SV_Target
half4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}

float Smoothness = 0.5;
float Occlusion = 1;
float Alpha = 1;
float AlphaClipThreshold = 0;
#if defined(UNITY_COLORSPACE_GAMMA)
Albedo = Albedo * Albedo;
Emission = Emission * Emission;
#endif
#if _NORMALMAP
half3 normalWS = TangentToWorldNormal(Normal, WorldSpaceTangent, WorldSpaceBiTangent, WorldSpaceNormal);
#else

#if LIGHTMAP_ON
half3 indirectDiffuse = SampleLightmap(IN.lightmapUV.zw, normalWS);
#else
half3 indirectDiffuse = EvaluateSHPerPixel(normalWS, IN.vertexSH);
#endif
half3 indirectDiffuse = SampleGI(IN.lightmapUVOrVertexSH, normalWS);
half4 color = LightweightFragmentPBR(
WorldSpacePosition,

IN.fogFactorAndVertexLight.yzw,
IN.fogFactorAndVertexLight.yzw,
Albedo,
Metallic,
Specular,

#endif
#if _AlphaClip
clip(Alpha - 0.01);
clip(Alpha - AlphaClipThreshold);
ENDCG
}
ENDHLSL
}

28
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightUnlitPass.template


${ZTest}
${ZWrite}
CGPROGRAM
#pragma target 3.0
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ENABLE STEREO_MULTIVIEW_ENABLE
#pragma multi_compile_instancing
#pragma glsl
#pragma debug
#include "UnityCG.cginc"
// Lighting include is needed because of GI
#include "LWRP/Shaders/LightweightShaderLibrary/Core.hlsl"
#include "LWRP/Shaders/LightweightShaderLibrary/Lighting.hlsl"
#include "CoreRP/ShaderLibrary/Color.hlsl"
#include "ShaderGraphLibrary/Functions.hlsl"
${Defines}

{
float4 position : POSITION;
${Interpolators}
UNITY_VERTEX_OUTPUT_STEREO
};
GraphVertexOutput vert (GraphVertexInput v)

UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.position = UnityObjectToClipPos(v.vertex);
o.position = TransformObjectToHClip(v.vertex.xyz);
fixed4 frag (GraphVertexOutput IN) : SV_Target
half4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}

float Alpha = 0;
${SurfaceOutputRemap}
return fixed4(Color, Alpha);
return half4(Color, Alpha);
ENDCG
ENDHLSL
}

2
MaterialGraphProject/Assets/UnityShaderEditor/package.json


{
"name": "com.unity.shadergraph",
"description": "Shader Graph",
"version": "0.1.10",
"version": "0.1.11",
"unity": "2018.1",
"dependencies": {
}

2
MaterialGraphProject/UnityPackageManager/manifest.json


{
"registry": "https://staging-packages.unity.com",
"dependencies": {
"com.unity.render-pipelines.lightweight" : "0.1.20"
"com.unity.render-pipelines.lightweight" : "0.1.23"
}
}

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/UnlitMasterNode.cs


finalShader.AddShaderChunk("}", false);
var lwSub = new LightWeightUnlitSubShader();
foreach (var subshader in lwSub.GetSubshader(this, mode))
finalShader.AddShaderChunk(subshader, true);
finalShader.AddShaderChunk(lwSub.GetSubshader(this, mode), true);
//Disable HD for now as there is no mapping
// for many inputs like worldSpaceNormal and similar
/*var hdSub = new HDUnlitSubShader();
finalShader.AddShaderChunk(hdSub.GetSubshader(this, mode), true);*/
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/PBRMasterNode.cs


public const string SmoothnessSlotName = "Smoothness";
public const string OcclusionSlotName = "Occlusion";
public const string AlphaSlotName = "Alpha";
public const string AlphaClipThresholdSlotName = "AlphaClipThreshold";
public const string VertexOffsetName = "VertexPosition";
public const int AlbedoSlotId = 0;

public const int SmoothnessSlotId = 5;
public const int OcclusionSlotId = 6;
public const int AlphaSlotId = 7;
public const int AlphaThresholdSlotId = 8;
public enum Model
{

public enum AlphaMode
{
Overwrite,
Opaque,
AdditiveBlend,
Clip
AdditiveBlend
}
[SerializeField]

AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.5f, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(OcclusionSlotId, OcclusionSlotName, OcclusionSlotName, SlotType.Input, 1f, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1f, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(AlphaThresholdSlotId, AlphaClipThresholdSlotName, AlphaClipThresholdSlotName, SlotType.Input, 0f, ShaderStage.Fragment));
// clear out slot names that do not match the slots
// we support

model == Model.Metallic ? MetallicSlotId : SpecularSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId
AlphaSlotId,
AlphaThresholdSlotId
}, true);
}

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline.meta


fileFormatVersion: 2
guid: 621b9da5e0cd5cc449775c0394b63d58
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes.meta


fileFormatVersion: 2
guid: be7d4ec304eccd8489095f90e0909d93
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

18
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/MatrixNames.cs


using System;
namespace UnityEditor.ShaderGraph {
public struct MatrixNames
{
public const string Model = "UNITY_MATRIX_M";
public const string ModelInverse = "UNITY_MATRIX_I_M";
public const string View = "UNITY_MATRIX_V";
public const string ViewInverse = "UNITY_MATRIX_I_V";
public const string Projection = "UNITY_MATRIX_P";
public const string ViewProjection = "UNITY_MATRIX_VP";
public const string ModelView = "UNITY_MATRIX_MV";
public const string ModelViewTransposed = "UNITY_MATRIX_T_MV";
public const string ModelViewInverseTransposed = "UNITY_MATRIX_IT_MV";
public const string ModelViewProjection = "UNITY_MATRIX_MVP";
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/MatrixNames.cs.meta


fileFormatVersion: 2
guid: 1358e9b39cd7e8442bece5b15a2a7c63
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

18
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGeneratorNames.cs


using System;
namespace UnityEditor.ShaderGraph {
public static class ShaderGeneratorNames
{
private static string[] UV = {"uv0", "uv1", "uv2", "uv3"};
public static int UVCount = 4;
public const string ScreenPosition = "screenPosition";
public const string VertexColor = "vertexColor";
public static string GetUVName(this UVChannel channel)
{
return UV[(int)channel];
}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGeneratorNames.cs.meta


fileFormatVersion: 2
guid: 33854ecfd53cd054a99d8cb17b260170
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/UvChannel.cs


using System;
namespace UnityEditor.ShaderGraph {
public enum UVChannel
{
uv0 = 0,
uv1 = 1,
uv2 = 2,
uv3 = 3,
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/UvChannel.cs.meta


fileFormatVersion: 2
guid: d77363d2f0df1f544b21d9e8a05f01a1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

74
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/HDUnlitPassForward.template


// Unlit shader always render in forward
Pass
{
Name "ForwardUnlit"
Tags { "LightMode" = "${LightMode}" }
${Tags}
${Blending}
${Culling}
${ZTest}
${ZWrite}
HLSLPROGRAM
#pragma target 4.5
#pragma only_renderers d3d11 ps4 vulkan metal // TEMP: until we go further in dev
//#pragma enable_d3d11_debug_symbols
#pragma vertex Vert
#pragma fragment Frag
#define UNITY_MATERIAL_UNLIT // Need to be define before including Material.hlsl
#include "CoreRP/ShaderLibrary/common.hlsl"
#include "HDRP/ShaderVariables.hlsl"
#include "HDRP/ShaderPass/FragInputs.hlsl"
#include "HDRP/ShaderPass/ShaderPass.cs.hlsl"
${Defines}
#include "HDRP/Material/Material.hlsl"
// This include will define the various Attributes/Varyings structure
#include "HDRP/ShaderPass/VaryingMesh.hlsl"
${Graph}
void GetSurfaceAndBuiltinData(FragInputs input, float3 V, inout PositionInputs posInput, out SurfaceData surfaceData, out BuiltinData builtinData)
{
${LocalPixelShader}
SurfaceInputs surfaceInput;
${SurfaceInputs}
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float3 Color = 0;
float Alpha = 0;
${SurfaceOutputRemap}
surfaceData.color = Color;
#ifdef _ALPHATEST_ON
DoAlphaTest(Alpha, _AlphaCutoff);
#endif
// Builtin Data
builtinData.opacity = Alpha;
builtinData.bakeDiffuseLighting = float3(0.0, 0.0, 0.0);
builtinData.emissiveIntensity = 0;
builtinData.emissiveColor = 0;
builtinData.velocity = float2(0.0, 0.0);
builtinData.shadowMask0 = 0.0;
builtinData.shadowMask1 = 0.0;
builtinData.shadowMask2 = 0.0;
builtinData.shadowMask3 = 0.0;
builtinData.distortion = float2(0.0, 0.0);
builtinData.distortionBlur = 0.0;
builtinData.depthOffset = 0.0;
}
#include "HDRP/ShaderPass/${ShaderPassInclude}.hlsl"
ENDHLSL
}

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/HDUnlitPassForward.template.meta


fileFormatVersion: 2
guid: 6eeaaca43ab129049ae23a1bd89420c4
timeCreated: 1481194716
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

8
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary.meta


fileFormatVersion: 2
guid: c1bc9b92d5eaa40f8a85c1f48ba87de9
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/HDUnlitSubShader.cs.meta


fileFormatVersion: 2
guid: 292c6a3c80161fa4cb49a9d11d35cbe9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/IUnlitSubShader.cs


using System;
namespace UnityEditor.ShaderGraph {
public interface IUnlitSubShader
{
string GetSubshader(UnlitMasterNode masterNode, GenerationMode mode);
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/IUnlitSubShader.cs.meta


fileFormatVersion: 2
guid: 1f0e14eed65d43342acaeb7f9e597621
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

201
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/HDPipeline/HDUnlitSubShader.cs


using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
public class HDUnlitSubShader : IUnlitSubShader
{
struct Pass
{
public string Name;
public string ShaderPassName;
public string ShaderPassInclude;
public List<int> VertexShaderSlots;
public List<int> PixelShaderSlots;
}
Pass m_UnlitPassForwardOnly = new Pass()
{
Name = "ForwardOnly",
ShaderPassName = "SHADERPASS_FORWARD_UNLIT",
ShaderPassInclude = "ShaderPassForwardUnlit",
PixelShaderSlots = new List<int>()
{
UnlitMasterNode.ColorSlotId,
UnlitMasterNode.AlphaSlotId
}
};
Pass m_UnlitPassForwardDepthOnly = new Pass()
{
Name = "DepthForwardOnly",
ShaderPassName = "SHADERPASS_DEPTH_ONLY",
ShaderPassInclude = "ShaderPassDepthOnly",
PixelShaderSlots = new List<int>()
{
UnlitMasterNode.ColorSlotId,
UnlitMasterNode.AlphaSlotId
}
};
private static string GetShaderPassFromTemplate(UnlitMasterNode masterNode, Pass pass, GenerationMode mode)
{
var builder = new ShaderStringBuilder();
builder.IncreaseIndent();
builder.IncreaseIndent();
var surfaceDescriptionFunction = new ShaderGenerator();
var surfaceDescriptionStruct = new ShaderGenerator();
var surfaceInputs = new ShaderGenerator();
var functionRegistry = new FunctionRegistry(builder);
var shaderProperties = new PropertyCollector();
surfaceInputs.AddShaderChunk("struct SurfaceInputs{", false);
surfaceInputs.Indent();
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots);
var requirements = ShaderGraphRequirements.FromNodes(activeNodeList);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresNormal, InterpolatorType.Normal, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresTangent, InterpolatorType.Tangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresBitangent, InterpolatorType.BiTangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresViewDir, InterpolatorType.ViewDirection, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresPosition, InterpolatorType.Position, surfaceInputs);
ShaderGenerator defines = new ShaderGenerator();
defines.AddShaderChunk(string.Format("#define SHADERPASS {0}", pass.ShaderPassName), true);
if (requirements.requiresVertexColor)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.VertexColor), false);
if (requirements.requiresScreenPosition)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.ScreenPosition), false);
foreach (var channel in requirements.requiresMeshUVs.Distinct())
{
surfaceInputs.AddShaderChunk(string.Format("half4 {0};", channel.GetUVName()), false);
defines.AddShaderChunk(string.Format("#define ATTRIBUTES_NEED_TEXCOORD{0}", (int)channel), true);
defines.AddShaderChunk(string.Format("#define VARYINGS_NEED_TEXCOORD{0}", (int)channel), true);
}
surfaceInputs.Deindent();
surfaceInputs.AddShaderChunk("};", false);
var slots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
{
var slot = masterNode.FindSlot<MaterialSlot>(id);
if (slot != null)
slots.Add(slot);
}
GraphUtil.GenerateSurfaceDescriptionStruct(surfaceDescriptionStruct, slots, true);
var usedSlots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
usedSlots.Add(masterNode.FindSlot<MaterialSlot>(id));
GraphUtil.GenerateSurfaceDescription(
activeNodeList,
masterNode,
masterNode.owner as AbstractMaterialGraph,
surfaceDescriptionFunction,
functionRegistry,
shaderProperties,
requirements,
mode,
"PopulateSurfaceData",
"SurfaceDescription",
null,
usedSlots);
var graph = new ShaderGenerator();
graph.AddShaderChunk(shaderProperties.GetPropertiesDeclaration(2), false);
graph.AddShaderChunk(surfaceInputs.GetShaderString(2), false);
graph.AddShaderChunk(builder.ToString(), false);
graph.AddShaderChunk(surfaceDescriptionStruct.GetShaderString(2), false);
graph.AddShaderChunk(surfaceDescriptionFunction.GetShaderString(2), false);
var tagsVisitor = new ShaderGenerator();
var blendingVisitor = new ShaderGenerator();
var cullingVisitor = new ShaderGenerator();
var zTestVisitor = new ShaderGenerator();
var zWriteVisitor = new ShaderGenerator();
var materialOptions = new SurfaceMaterialOptions();
materialOptions.GetTags(tagsVisitor);
materialOptions.GetBlend(blendingVisitor);
materialOptions.GetCull(cullingVisitor);
materialOptions.GetDepthTest(zTestVisitor);
materialOptions.GetDepthWrite(zWriteVisitor);
var localPixelShader = new ShaderGenerator();
var localSurfaceInputs = new ShaderGenerator();
var surfaceOutputRemap = new ShaderGenerator();
foreach (var channel in requirements.requiresMeshUVs.Distinct())
localSurfaceInputs.AddShaderChunk(string.Format("surfaceInput.{0} = {1};", channel.GetUVName(), string.Format("half4(input.texCoord{0}, 0, 0)", (int)channel)), false);
var templateLocation = ShaderGenerator.GetTemplatePath("HDUnlitPassForward.template");
foreach (var slot in usedSlots)
{
surfaceOutputRemap.AddShaderChunk(slot.shaderOutputName
+ " = surf."
+ slot.shaderOutputName + ";", true);
}
if (!File.Exists(templateLocation))
return string.Empty;
var subShaderTemplate = File.ReadAllText(templateLocation);
var resultPass = subShaderTemplate.Replace("${Defines}", defines.GetShaderString(3));
resultPass = resultPass.Replace("${Graph}", graph.GetShaderString(3));
resultPass = resultPass.Replace("${LocalPixelShader}", localPixelShader.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceInputs}", localSurfaceInputs.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceOutputRemap}", surfaceOutputRemap.GetShaderString(3));
resultPass = resultPass.Replace("${LightMode}", pass.Name);
resultPass = resultPass.Replace("${ShaderPassInclude}", pass.ShaderPassInclude);
resultPass = resultPass.Replace("${Tags}", tagsVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${Blending}", blendingVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${Culling}", cullingVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${ZTest}", zTestVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${ZWrite}", zWriteVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${LOD}", "" + materialOptions.lod);
return resultPass;
}
public string GetSubshader(UnlitMasterNode masterNode, GenerationMode mode)
{
var subShader = new ShaderGenerator();
subShader.AddShaderChunk("SubShader", true);
subShader.AddShaderChunk("{", true);
subShader.Indent();
subShader.AddShaderChunk("Tags{ \"RenderType\" = \"Opaque\" }", true);
subShader.AddShaderChunk(
GetShaderPassFromTemplate(
masterNode,
m_UnlitPassForwardDepthOnly,
mode),
true);
subShader.AddShaderChunk(
GetShaderPassFromTemplate(
masterNode,
m_UnlitPassForwardOnly,
mode),
true);
subShader.Deindent();
subShader.AddShaderChunk("}", true);
return subShader.GetShaderString(0);
}
}
}

14
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/Functions.hlsl


// UNITY_SHADER_NO_UPGRADE
#ifndef UNITY_SHADER_GRAPH_INCLUDED
#define UNITY_SHADER_GRAPH_INCLUDED
bool IsGammaSpace()
{
#ifdef UNITY_COLORSPACE_GAMMA
return true;
#else
return false;
#endif
}
#endif // UNITY_SHADER_GRAPH_INCLUDED

9
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/Functions.hlsl.meta


fileFormatVersion: 2
guid: 76c5c0b7561134f0ca526e50f239a4a2
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

173
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/GeometricTools.hlsl


#ifndef UNITY_GEOMETRICTOOLS_INCLUDED
#define UNITY_GEOMETRICTOOLS_INCLUDED
//-----------------------------------------------------------------------------
// Intersection functions
//-----------------------------------------------------------------------------
// return furthest near intersection in x and closest far intersection in y
// if (intersections.y > intersections.x) the ray hit the box, else it miss it
// Assume dir is normalize
float2 BoxRayIntersect(float3 start, float3 dir, float3 boxMin, float3 boxMax)
{
float3 invDir = 1.0 / dir;
// Find the ray intersection with box plane
float3 firstPlaneIntersect = (boxMin - start) * invDir;
float3 secondPlaneIntersect = (boxMax - start) * invDir;
// Get the closest/furthest of these intersections along the ray (Ok because x/0 give +inf and -x/0 give �inf )
float3 closestPlane = min(firstPlaneIntersect, secondPlaneIntersect);
float3 furthestPlane = max(firstPlaneIntersect, secondPlaneIntersect);
float2 intersections;
// Find the furthest near intersection
intersections.x = max(closestPlane.x, max(closestPlane.y, closestPlane.z));
// Find the closest far intersection
intersections.y = min(min(furthestPlane.x, furthestPlane.y), furthestPlane.z);
return intersections;
}
// This simplified version assume that we care about the result only when we are inside the box
// Assume dir is normalize
float BoxRayIntersectSimple(float3 start, float3 dir, float3 boxMin, float3 boxMax)
{
float3 invDir = 1.0 / dir;
// Find the ray intersection with box plane
float3 rbmin = (boxMin - start) * invDir;
float3 rbmax = (boxMax - start) * invDir;
float3 rbminmax = (dir > 0.0) ? rbmax : rbmin;
return min(min(rbminmax.x, rbminmax.y), rbminmax.z);
}
// Assume Sphere is at the origin (i.e start = position - spherePosition)
float2 SphereRayIntersect(float3 start, float3 dir, float radius, out bool intersect)
{
float a = dot(dir, dir);
float b = dot(dir, start) * 2.0;
float c = dot(start, start) - radius * radius;
float discriminant = b * b - 4.0 * a * c;
float2 intersections = float2(0.0, 0.0);
intersect = false;
if (discriminant < 0.0 || a == 0.0)
{
intersections.x = 0.0;
intersections.y = 0.0;
}
else
{
float sqrtDiscriminant = sqrt(discriminant);
intersections.x = (-b - sqrtDiscriminant) / (2.0 * a);
intersections.y = (-b + sqrtDiscriminant) / (2.0 * a);
intersect = true;
}
return intersections;
}
// This simplified version assume that we care about the result only when we are inside the sphere
// Assume Sphere is at the origin (i.e start = position - spherePosition) and dir is normalized
// Ref: http://http.developer.nvidia.com/GPUGems/gpugems_ch19.html
float SphereRayIntersectSimple(float3 start, float3 dir, float radius)
{
float b = dot(dir, start) * 2.0;
float c = dot(start, start) - radius * radius;
float discriminant = b * b - 4.0 * c;
return abs(sqrt(discriminant) - b) * 0.5;
}
float3 RayPlaneIntersect(in float3 rayOrigin, in float3 rayDirection, in float3 planeOrigin, in float3 planeNormal)
{
float dist = dot(planeNormal, planeOrigin - rayOrigin) / dot(planeNormal, rayDirection);
return rayOrigin + rayDirection * dist;
}
//-----------------------------------------------------------------------------
// Miscellaneous functions
//-----------------------------------------------------------------------------
// Box is AABB
float DistancePointBox(float3 position, float3 boxMin, float3 boxMax)
{
return length(max(max(position - boxMax, boxMin - position), float3(0.0, 0.0, 0.0)));
}
float3 ProjectPointOnPlane(float3 position, float3 planePosition, float3 planeNormal)
{
return position - (dot(position - planePosition, planeNormal) * planeNormal);
}
// Plane equation: {(a, b, c) = N, d = -dot(N, P)}.
// Returns the distance from the plane to the point 'p' along the normal.
// Positive -> in front (above), negative -> behind (below).
float DistanceFromPlane(float3 p, float4 plane)
{
return dot(float4(p, 1.0), plane);
}
// Returns 'true' if the triangle is outside of the frustum.
// 'epsilon' is the (negative) distance to (outside of) the frustum below which we cull the triangle.
bool CullTriangleFrustum(float3 p0, float3 p1, float3 p2, float epsilon, float4 frustumPlanes[6], int numPlanes)
{
bool outside = false;
for (int i = 0; i < numPlanes; i++)
{
// If all 3 points are behind any of the planes, we cull.
outside = outside || Max3(DistanceFromPlane(p0, frustumPlanes[i]),
DistanceFromPlane(p1, frustumPlanes[i]),
DistanceFromPlane(p2, frustumPlanes[i])) < epsilon;
}
return outside;
}
// Returns 'true' if the edge of the triangle is outside of the frustum.
// The edges are defined s.t. they are on the opposite side of the point with the given index.
// 'epsilon' is the (negative) distance to (outside of) the frustum below which we cull the triangle.
bool3 CullTriangleEdgesFrustum(float3 p0, float3 p1, float3 p2, float epsilon, float4 frustumPlanes[6], int numPlanes)
{
bool3 edgesOutside = false;
for (int i = 0; i < numPlanes; i++)
{
bool3 pointsOutside = bool3(DistanceFromPlane(p0, frustumPlanes[i]) < epsilon,
DistanceFromPlane(p1, frustumPlanes[i]) < epsilon,
DistanceFromPlane(p2, frustumPlanes[i]) < epsilon);
// If both points of the edge are behind any of the planes, we cull.
edgesOutside.x = edgesOutside.x || (pointsOutside.y && pointsOutside.z);
edgesOutside.y = edgesOutside.y || (pointsOutside.x && pointsOutside.z);
edgesOutside.z = edgesOutside.z || (pointsOutside.x && pointsOutside.y);
}
return edgesOutside;
}
// Returns 'true' if a triangle defined by 3 vertices is back-facing.
// 'epsilon' is the (negative) value of dot(N, V) below which we cull the triangle.
// 'winding' can be used to change the order: pass 1 for (p0 -> p1 -> p2), or -1 for (p0 -> p2 -> p1).
bool CullTriangleBackFace(float3 p0, float3 p1, float3 p2, float epsilon, float3 viewPos, float winding)
{
float3 edge1 = p1 - p0;
float3 edge2 = p2 - p0;
float3 N = cross(edge1, edge2);
float3 V = viewPos - p0;
float NdotV = dot(N, V) * winding;
// Optimize:
// NdotV / (length(N) * length(V)) < Epsilon
// NdotV < Epsilon * length(N) * length(V)
// NdotV < Epsilon * sqrt(dot(N, N)) * sqrt(dot(V, V))
// NdotV < Epsilon * sqrt(dot(N, N) * dot(V, V))
return NdotV < epsilon * sqrt(dot(N, N) * dot(V, V));
}
#endif // UNITY_GEOMETRICTOOLS_INCLUDED

9
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/GeometricTools.hlsl.meta


fileFormatVersion: 2
guid: 07d3f5482ecfe425f91b12cd32be4cbe
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

15
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderConfig.cs.hlsl


//
// This file was automatically generated. Please don't edit by hand.
//
#ifndef SHADERCONFIG_CS_HLSL
#define SHADERCONFIG_CS_HLSL
//
// UnityEngine.Experimental.Rendering.HDPipeline.ShaderOptions: static fields
//
#define SHADEROPTIONS_VELOCITY_IN_GBUFFER (0)
#define SHADEROPTIONS_PACK_GBUFFER_IN_U16 (0)
#define SHADEROPTIONS_CAMERA_RELATIVE_RENDERING (1)
#endif

9
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderConfig.cs.hlsl.meta


fileFormatVersion: 2
guid: 2c6472a689b6ae34e806881d3066cfb3
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

279
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariables.hlsl


// UNITY_SHADER_NO_UPGRADE
#ifndef UNITY_SHADER_VARIABLES_INCLUDED
#define UNITY_SHADER_VARIABLES_INCLUDED
#include "ShaderConfig.cs.hlsl"
// CAUTION:
// Currently the shaders compiler always include regualr Unity shaderVariables, so I get a conflict here were UNITY_SHADER_VARIABLES_INCLUDED is already define, this need to be fixed.
// As I haven't change the variables name yet, I simply don't define anything, and I put the transform function at the end of the file outside the guard header.
// This need to be fixed.
#if defined (DIRECTIONAL_COOKIE) || defined (DIRECTIONAL)
#define USING_DIRECTIONAL_LIGHT
#endif
#if defined(UNITY_SINGLE_PASS_STEREO) || defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
#define USING_STEREO_MATRICES
#endif
#if defined(USING_STEREO_MATRICES)
#define glstate_matrix_projection unity_StereoMatrixP[unity_StereoEyeIndex]
#define unity_MatrixV unity_StereoMatrixV[unity_StereoEyeIndex]
#define unity_MatrixInvV unity_StereoMatrixInvV[unity_StereoEyeIndex]
#define unity_MatrixVP unity_StereoMatrixVP[unity_StereoEyeIndex]
#define unity_CameraProjection unity_StereoCameraProjection[unity_StereoEyeIndex]
#define unity_CameraInvProjection unity_StereoCameraInvProjection[unity_StereoEyeIndex]
#define unity_WorldToCamera unity_StereoWorldToCamera[unity_StereoEyeIndex]
#define unity_CameraToWorld unity_StereoCameraToWorld[unity_StereoEyeIndex]
#define _WorldSpaceCameraPos unity_StereoWorldSpaceCameraPos[unity_StereoEyeIndex]
#endif
#define UNITY_LIGHTMODEL_AMBIENT (glstate_lightmodel_ambient * 2)
// ----------------------------------------------------------------------------
CBUFFER_START(UnityPerCamera)
// Time (t = time since current level load) values from Unity
float4 _Time; // (t/20, t, t*2, t*3)
float4 _LastTime; // Last frame time (t/20, t, t*2, t*3)
float4 _SinTime; // sin(t/8), sin(t/4), sin(t/2), sin(t)
float4 _CosTime; // cos(t/8), cos(t/4), cos(t/2), cos(t)
float4 unity_DeltaTime; // dt, 1/dt, smoothdt, 1/smoothdt
#if !defined(USING_STEREO_MATRICES)
float3 _WorldSpaceCameraPos;
#endif
// x = 1 or -1 (-1 if projection is flipped)
// y = near plane
// z = far plane
// w = 1/far plane
float4 _ProjectionParams;
// x = width
// y = height
// z = 1 + 1.0/width
// w = 1 + 1.0/height
float4 _ScreenParams;
// Values used to linearize the Z buffer (http://www.humus.name/temp/Linearize%20depth.txt)
// x = 1-far/near
// y = far/near
// z = x/far
// w = y/far
// or in case of a reversed depth buffer (UNITY_REVERSED_Z is 1)
// x = -1+far/near
// y = 1
// z = x/far
// w = 1/far
float4 _ZBufferParams;
// x = orthographic camera's width
// y = orthographic camera's height
// z = unused
// w = 1.0 if camera is ortho, 0.0 if perspective
float4 unity_OrthoParams;
CBUFFER_END
CBUFFER_START(UnityPerCameraRare)
float4 unity_CameraWorldClipPlanes[6];
#if !defined(USING_STEREO_MATRICES)
// Projection matrices of the camera. Note that this might be different from projection matrix
// that is set right now, e.g. while rendering shadows the matrices below are still the projection
// of original camera.
float4x4 unity_CameraProjection;
float4x4 unity_CameraInvProjection;
float4x4 unity_WorldToCamera;
float4x4 unity_CameraToWorld;
#endif
CBUFFER_END
// ----------------------------------------------------------------------------
CBUFFER_START(UnityPerDraw : register(b0))
#ifdef UNITY_USE_PREMULTIPLIED_MATRICES
float4x4 glstate_matrix_mvp;
float4x4 glstate_matrix_modelview0;
float4x4 glstate_matrix_invtrans_modelview0;
#endif
float4x4 unity_ObjectToWorld;
float4x4 unity_WorldToObject;
float4 unity_LODFade; // x is the fade value ranging within [0,1]. y is x quantized into 16 levels
float4 unity_WorldTransformParams; // w is usually 1.0, or -1.0 for odd-negative scale transforms
float4 unity_LightmapST;
float4 unity_DynamicLightmapST;
// SH lighting environment
float4 unity_SHAr;
float4 unity_SHAg;
float4 unity_SHAb;
float4 unity_SHBr;
float4 unity_SHBg;
float4 unity_SHBb;
float4 unity_SHC;
// x = Disabled(0)/Enabled(1)
// y = Computation are done in global space(0) or local space(1)
// z = Texel size on U texture coordinate
float4 unity_ProbeVolumeParams;
float4x4 unity_ProbeVolumeWorldToObject;
float3 unity_ProbeVolumeSizeInv;
float3 unity_ProbeVolumeMin;
// This contain occlusion factor from 0 to 1 for dynamic objects (no SH here)
float4 unity_ProbesOcclusion;
CBUFFER_END
#if defined(USING_STEREO_MATRICES)
CBUFFER_START(UnityStereoGlobals)
float4x4 unity_StereoMatrixP[2];
float4x4 unity_StereoMatrixV[2];
float4x4 unity_StereoMatrixInvV[2];
float4x4 unity_StereoMatrixVP[2];
float4x4 unity_StereoCameraProjection[2];
float4x4 unity_StereoCameraInvProjection[2];
float4x4 unity_StereoWorldToCamera[2];
float4x4 unity_StereoCameraToWorld[2];
float3 unity_StereoWorldSpaceCameraPos[2];
float4 unity_StereoScaleOffset[2];
CBUFFER_END
#endif
#if defined(USING_STEREO_MATRICES) && defined(UNITY_STEREO_MULTIVIEW_ENABLED)
CBUFFER_START(UnityStereoEyeIndices)
float4 unity_StereoEyeIndices[2];
CBUFFER_END
#endif
#if defined(UNITY_STEREO_MULTIVIEW_ENABLED) && defined(SHADER_STAGE_VERTEX)
#define unity_StereoEyeIndex UNITY_VIEWID
UNITY_DECLARE_MULTIVIEW(2);
#elif defined(UNITY_STEREO_INSTANCING_ENABLED) || defined(UNITY_STEREO_MULTIVIEW_ENABLED)
static uint unity_StereoEyeIndex;
#elif defined(UNITY_SINGLE_PASS_STEREO)
CBUFFER_START(UnityStereoEyeIndex)
int unity_StereoEyeIndex;
CBUFFER_END
#endif
CBUFFER_START(UnityPerDrawRare)
float4x4 glstate_matrix_transpose_modelview0;
CBUFFER_END
// ----------------------------------------------------------------------------
CBUFFER_START(UnityPerFrame)
float4 glstate_lightmodel_ambient;
float4 unity_AmbientSky;
float4 unity_AmbientEquator;
float4 unity_AmbientGround;
float4 unity_IndirectSpecColor;
#if !defined(USING_STEREO_MATRICES)
float4x4 glstate_matrix_projection;
float4x4 unity_MatrixV;
float4x4 unity_MatrixInvV;
float4x4 unity_MatrixVP;
float4 unity_StereoScaleOffset;
int unity_StereoEyeIndex;
#endif
float3 unity_ShadowColor;
uint _TaaFrameIndex; // [0, 7]
CBUFFER_END
// ----------------------------------------------------------------------------
// These are the samplers available in the HDRenderPipeline.
// Avoid declaring extra samplers as they are 4x SGPR each on GCN.
SAMPLER(s_linear_clamp_sampler);
SAMPLER(s_trilinear_clamp_sampler);
// ----------------------------------------------------------------------------
TEXTURE2D(_MainDepthTexture);
SAMPLER(sampler_MainDepthTexture);
// Main lightmap
TEXTURE2D(unity_Lightmap);
SAMPLER(samplerunity_Lightmap);
// Dual or directional lightmap (always used with unity_Lightmap, so can share sampler)
TEXTURE2D(unity_LightmapInd);
// Dynamic GI lightmap
TEXTURE2D(unity_DynamicLightmap);
SAMPLER(samplerunity_DynamicLightmap);
TEXTURE2D(unity_DynamicDirectionality);
// We can have shadowMask only if we have lightmap, so no sampler
TEXTURE2D(unity_ShadowMask);
// TODO: Change code here so probe volume use only one transform instead of all this parameters!
TEXTURE3D(unity_ProbeVolumeSH);
SAMPLER(samplerunity_ProbeVolumeSH);
CBUFFER_START(UnityVelocityPass)
float4x4 unity_MatrixNonJitteredVP;
float4x4 unity_MatrixPreviousVP;
float4x4 unity_MatrixPreviousM;
float4x4 unity_MatrixPreviousMI;
//X : Use last frame positions (right now skinned meshes are the only objects that use this
//Y : Force No Motion
//Z : Z bias value
float4 unity_MotionVectorsParams;
CBUFFER_END
// ----------------------------------------------------------------------------
// TODO: all affine matrices should be 3x4.
// TODO: sort these vars by the frequency of use (descending), and put commonly used vars together.
// Note: please use UNITY_MATRIX_X macros instead of referencing matrix variables directly.
CBUFFER_START(UnityPerPass)
float4x4 _PrevViewProjMatrix;
float4x4 _ViewProjMatrix;
float4x4 _NonJitteredViewProjMatrix;
float4x4 _ViewMatrix;
float4x4 _ProjMatrix;
float4x4 _InvViewProjMatrix;
float4x4 _InvViewMatrix;
float4x4 _InvProjMatrix;
float4 _InvProjParam;
float4 _ScreenSize; // {w, h, 1/w, 1/h}
float4 _FrustumPlanes[6]; // {(a, b, c) = N, d = -dot(N, P)} [L, R, T, B, N, F]
CBUFFER_END
float4x4 OptimizeProjectionMatrix(float4x4 M)
{
// Matrix format (x = non-constant value).
// Orthographic Perspective Combined(OR)
// | x 0 0 x | | x 0 x 0 | | x 0 x x |
// | 0 x 0 x | | 0 x x 0 | | 0 x x x |
// | x x x x | | x x x x | | x x x x | <- oblique projection row
// | 0 0 0 1 | | 0 0 x 0 | | 0 0 x x |
// Notice that some values are always 0.
// We can avoid loading and doing math with constants.
M._21_41 = 0;
M._12_42 = 0;
return M;
}
#ifdef USE_LEGACY_UNITY_MATRIX_VARIABLES
#include "ShaderVariablesMatrixDefsLegacyUnity.hlsl"
#else
#include "ShaderVariablesMatrixDefsHDCamera.hlsl"
#endif
#include "ShaderVariablesFunctions.hlsl"
#endif // UNITY_SHADER_VARIABLES_INCLUDED

9
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariables.hlsl.meta


fileFormatVersion: 2
guid: 2bc64066748469e48861ed835a8b806d
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

192
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesFunctions.hlsl


#ifndef UNITY_SHADER_VARIABLES_FUNCTIONS_INCLUDED
#define UNITY_SHADER_VARIABLES_FUNCTIONS_INCLUDED
float4x4 GetWorldToViewMatrix()
{
return UNITY_MATRIX_V;
}
float4x4 GetObjectToWorldMatrix()
{
return UNITY_MATRIX_M;
}
float4x4 GetWorldToObjectMatrix()
{
return UNITY_MATRIX_I_M;
}
// Transform to homogenous clip space
float4x4 GetWorldToHClipMatrix()
{
return UNITY_MATRIX_VP;
}
float GetOddNegativeScale()
{
return unity_WorldTransformParams.w;
}
float3 TransformWorldToView(float3 positionWS)
{
return mul(GetWorldToViewMatrix(), float4(positionWS, 1.0)).xyz;
}
float3 TransformObjectToWorld(float3 positionOS)
{
return mul(GetObjectToWorldMatrix(), float4(positionOS, 1.0)).xyz;
}
float3 TransformWorldToObject(float3 positionWS)
{
return mul(GetWorldToObjectMatrix(), float4(positionWS, 1.0)).xyz;
}
float3 TransformObjectToWorldDir(float3 dirOS)
{
// Normalize to support uniform scaling
return normalize(mul((float3x3)GetObjectToWorldMatrix(), dirOS));
}
float3 TransformWorldToObjectDir(float3 dirWS)
{
// Normalize to support uniform scaling
return normalize(mul((float3x3)GetWorldToObjectMatrix(), dirWS));
}
// Transforms normal from object to world space
float3 TransformObjectToWorldNormal(float3 normalOS)
{
#ifdef UNITY_ASSUME_UNIFORM_SCALING
return UnityObjectToWorldDir(normalOS);
#else
// Normal need to be multiply by inverse transpose
// mul(IT_M, norm) => mul(norm, I_M) => {dot(norm, I_M.col0), dot(norm, I_M.col1), dot(norm, I_M.col2)}
return normalize(mul(normalOS, (float3x3)GetWorldToObjectMatrix()));
#endif
}
// Tranforms position from world space to homogenous space
float4 TransformWorldToHClip(float3 positionWS)
{
return mul(GetWorldToHClipMatrix(), float4(positionWS, 1.0));
}
float3 GetAbsolutePositionWS(float3 positionWS)
{
#if (SHADEROPTIONS_CAMERA_RELATIVE_RENDERING != 0)
positionWS += _WorldSpaceCameraPos;
#endif
return positionWS;
}
float3 GetCameraRelativePositionWS(float3 positionWS)
{
#if (SHADEROPTIONS_CAMERA_RELATIVE_RENDERING != 0)
positionWS -= _WorldSpaceCameraPos;
#endif
return positionWS;
}
// Note: '_WorldSpaceCameraPos' is set by the legacy Unity code.
float3 GetPrimaryCameraPosition()
{
#if (SHADEROPTIONS_CAMERA_RELATIVE_RENDERING != 0)
return float3(0, 0, 0);
#else
return _WorldSpaceCameraPos;
#endif
}
// Could be e.g. the position of a primary camera or a shadow-casting light.
float3 GetCurrentViewPosition()
{
#if defined(SHADERPASS) && (SHADERPASS != SHADERPASS_SHADOWS)
return GetPrimaryCameraPosition();
#else
// This is a generic solution.
// However, for the primary camera, using '_WorldSpaceCameraPos' is better for cache locality,
// and in case we enable camera-relative rendering, we can statically set the position is 0.
return UNITY_MATRIX_I_V._14_24_34;
#endif
}
// Returns the forward (central) direction of the current view in the world space.
float3 GetViewForwardDir()
{
float4x4 viewMat = GetWorldToViewMatrix();
return -viewMat[2].xyz;
}
// Returns 'true' if the current view performs a perspective projection.
bool IsPerspectiveProjection()
{
#if defined(SHADERPASS) && (SHADERPASS != SHADERPASS_SHADOWS)
return (unity_OrthoParams.w == 0);
#else
// TODO: set 'unity_OrthoParams' during the shadow pass.
return UNITY_MATRIX_P[3][3] == 0;
#endif
}
// Computes the world space view direction (pointing towards the viewer).
float3 GetWorldSpaceNormalizeViewDir(float3 positionWS)
{
if (IsPerspectiveProjection())
{
// Perspective
float3 V = GetCurrentViewPosition() - positionWS;
return normalize(V);
}
else
{
// Orthographic
return -GetViewForwardDir();
}
}
float3x3 CreateWorldToTangent(float3 normal, float3 tangent, float flipSign)
{
// For odd-negative scale transforms we need to flip the sign
float sgn = flipSign * GetOddNegativeScale();
float3 bitangent = cross(normal, tangent) * sgn;
return float3x3(tangent, bitangent, normal);
}
float3 TransformTangentToWorld(float3 dirTS, float3x3 worldToTangent)
{
// Use transpose transformation to go from tangent to world as the matrix is orthogonal
return mul(dirTS, worldToTangent);
}
float3 TransformWorldToTangent(float3 dirWS, float3x3 worldToTangent)
{
return mul(worldToTangent, dirWS);
}
float3 TransformTangentToObject(float3 dirTS, float3x3 worldToTangent)
{
// Use transpose transformation to go from tangent to world as the matrix is orthogonal
float3 normalWS = mul(dirTS, worldToTangent);
return mul((float3x3)GetWorldToObjectMatrix(), normalWS);
}
float3 TransformObjectToTangent(float3 dirOS, float3x3 worldToTangent)
{
return mul(worldToTangent, TransformObjectToWorldDir(dirOS));
}
// UNITY_MATRIX_V defines a right-handed view space with the Z axis pointing towards the viewer.
// This function reverses the direction of the Z axis (so that it points forward),
// making the view space coordinate system left-handed.
void GetLeftHandedViewSpaceMatrices(out float4x4 viewMatrix, out float4x4 projMatrix)
{
viewMatrix = UNITY_MATRIX_V;
viewMatrix._31_32_33_34 = -viewMatrix._31_32_33_34;
projMatrix = UNITY_MATRIX_P;
projMatrix._13_23_33_43 = -projMatrix._13_23_33_43;
}
#endif // UNITY_SHADER_VARIABLES_FUNCTIONS_INCLUDED

10
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesFunctions.hlsl.meta


fileFormatVersion: 2
guid: 919263f29f66aed49a283fe1f971c094
timeCreated: 1498227267
licenseType: Pro
ShaderImporter:
externalObjects: {}
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

21
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesMatrixDefsLegacyUnity.hlsl


#ifdef UNITY_SHADER_VARIABLES_MATRIX_DEFS_HDCAMERA_INCLUDED
#error Mixing HDCamera and legacy Unity matrix definitions
#endif
#ifndef UNITY_SHADER_VARIABLES_MATRIX_DEFS_LEGACY_UNITY_INCLUDED
#define UNITY_SHADER_VARIABLES_MATRIX_DEFS_LEGACY_UNITY_INCLUDED
#define UNITY_MATRIX_M unity_ObjectToWorld
#define UNITY_MATRIX_I_M unity_WorldToObject
#define UNITY_MATRIX_V unity_MatrixV
#define UNITY_MATRIX_I_V unity_MatrixInvV
#define UNITY_MATRIX_P OptimizeProjectionMatrix(glstate_matrix_projection)
#define UNITY_MATRIX_I_P ERROR_UNITY_MATRIX_I_P_IS_NOT_DEFINED
#define UNITY_MATRIX_VP unity_MatrixVP
#define UNITY_MATRIX_I_VP ERROR_UNITY_MATRIX_I_VP_IS_NOT_DEFINED
#define UNITY_MATRIX_MV mul(UNITY_MATRIX_V, UNITY_MATRIX_M)
#define UNITY_MATRIX_T_MV transpose(UNITY_MATRIX_MV)
#define UNITY_MATRIX_IT_MV transpose(mul(UNITY_MATRIX_I_M, UNITY_MATRIX_I_V))
#define UNITY_MATRIX_MVP mul(UNITY_MATRIX_VP, UNITY_MATRIX_M)
#endif // UNITY_SHADER_VARIABLES_MATRIX_DEFS_LEGACY_UNITY_INCLUDED

10
MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariablesMatrixDefsLegacyUnity.hlsl.meta


fileFormatVersion: 2
guid: 77ec57a2ba7588b4b96bc4c87934003f
timeCreated: 1498228363
licenseType: Pro
ShaderImporter:
externalObjects: {}
defaultTextures: []
userData:
assetBundleName:
assetBundleVariant:

3
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/AbstractSubGraph.cs.meta


fileFormatVersion: 2
guid: f2b67435729448498da7e7b90f052ebd
timeCreated: 1506844687

3
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/AbstractSubGraphNode.cs.meta


fileFormatVersion: 2
guid: bc4cf774a7a6480ba543eb6069cd1c50
timeCreated: 1506847426

65
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/AbstractSubGraph.cs


using System;
using System.Collections.Generic;
using System.Linq;
namespace UnityEditor.ShaderGraph
{
[Serializable]
public class AbstractSubGraph : AbstractMaterialGraph
, IGeneratesBodyCode
, IGeneratesFunction
{
public virtual IEnumerable<AbstractMaterialNode> activeNodes { get { return Enumerable.Empty<AbstractMaterialNode>(); } }
public PreviewMode previewMode
{
get { return activeNodes.Any(x => x.previewMode == PreviewMode.Preview3D) ? PreviewMode.Preview3D : PreviewMode.Preview2D; }
}
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
foreach (var node in activeNodes)
{
if (node is IGeneratesBodyCode)
(node as IGeneratesBodyCode).GenerateNodeCode(visitor, generationMode);
}
}
public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode)
{
foreach (var node in activeNodes)
{
if (node is IGeneratesFunction)
(node as IGeneratesFunction).GenerateNodeFunction(registry, generationMode);
}
}
public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode)
{
// if we are previewing the graph we need to
// export 'exposed props' if we are 'for real'
// then we are outputting the graph in the
// nested context and the needed values will
// be copied into scope.
if (generationMode == GenerationMode.Preview)
{
foreach (var prop in properties)
collector.AddShaderProperty(prop);
}
foreach (var node in activeNodes)
{
if (node is IGenerateProperties)
(node as IGenerateProperties).CollectShaderProperties(collector, generationMode);
}
}
public IEnumerable<PreviewProperty> GetPreviewProperties()
{
List<PreviewProperty> props = new List<PreviewProperty>();
foreach (var node in activeNodes)
node.CollectPreviewMaterialProperties(props);
return props;
}
}
}

250
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/AbstractSubGraphNode.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
public abstract class AbstractSubGraphNode : AbstractMaterialNode
, IGeneratesFunction
, IMayRequireNormal
, IMayRequireTangent
, IMayRequireBitangent
, IMayRequireMeshUV
, IMayRequireScreenPosition
, IMayRequireViewDirection
, IMayRequirePosition
, IMayRequireVertexColor
, IMayRequireTime
{
protected abstract AbstractSubGraph referencedGraph { get; }
public override bool hasPreview
{
get { return referencedGraph != null; }
}
public override PreviewMode previewMode
{
get
{
if (referencedGraph == null)
return PreviewMode.Preview2D;
return PreviewMode.Preview3D;
}
}
public virtual INode outputNode
{
get { return null; }
}
public virtual void UpdateSlots()
{
var validNames = new List<int>();
if (referencedGraph == null)
{
RemoveSlotsNameNotMatching(validNames);
return;
}
var props = referencedGraph.properties;
foreach (var prop in props)
{
var propType = prop.propertyType;
SlotValueType slotType;
switch (propType)
{
case PropertyType.Color:
slotType = SlotValueType.Vector4;
break;
case PropertyType.Texture:
slotType = SlotValueType.Texture2D;
break;
case PropertyType.Cubemap:
slotType = SlotValueType.Cubemap;
break;
case PropertyType.Float:
slotType = SlotValueType.Vector1;
break;
case PropertyType.Vector2:
slotType = SlotValueType.Vector2;
break;
case PropertyType.Vector3:
slotType = SlotValueType.Vector3;
break;
case PropertyType.Vector4:
slotType = SlotValueType.Vector4;
break;
case PropertyType.Matrix2:
slotType = SlotValueType.Matrix2;
break;
case PropertyType.Matrix3:
slotType = SlotValueType.Matrix3;
break;
case PropertyType.Matrix4:
slotType = SlotValueType.Matrix4;
break;
default:
throw new ArgumentOutOfRangeException();
}
var id = prop.guid.GetHashCode();
MaterialSlot slot = MaterialSlot.CreateMaterialSlot(slotType, id, prop.displayName, prop.referenceName, SlotType.Input, prop.defaultValue);
// copy default for texture for niceness
if (slotType == SlotValueType.Texture2D && propType == PropertyType.Texture)
{
var tSlot = slot as Texture2DInputMaterialSlot;
var tProp = prop as TextureShaderProperty;
if (tSlot != null && tProp != null)
tSlot.texture = tProp.value.texture;
}
// copy default for cubemap for niceness
else if (slotType == SlotValueType.Cubemap && propType == PropertyType.Cubemap)
{
var tSlot = slot as CubemapInputMaterialSlot;
var tProp = prop as CubemapShaderProperty;
if (tSlot != null && tProp != null)
tSlot.cubemap = tProp.value.cubemap;
}
AddSlot(slot);
validNames.Add(id);
}
var subGraphOutputNode = outputNode;
if (outputNode != null)
{
foreach (var slot in subGraphOutputNode.GetInputSlots<MaterialSlot>())
{
AddSlot(MaterialSlot.CreateMaterialSlot(slot.valueType, slot.id, slot.RawDisplayName(), slot.shaderOutputName, SlotType.Output, Vector4.zero));
validNames.Add(slot.id);
}
}
RemoveSlotsNameNotMatching(validNames);
}
public override void CollectShaderProperties(PropertyCollector visitor, GenerationMode generationMode)
{
base.CollectShaderProperties(visitor, generationMode);
if (referencedGraph == null)
return;
referencedGraph.CollectShaderProperties(visitor, GenerationMode.ForReals);
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
{
base.CollectPreviewMaterialProperties(properties);
if (referencedGraph == null)
return;
properties.AddRange(referencedGraph.GetPreviewProperties());
}
public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode)
{
if (referencedGraph == null)
return;
referencedGraph.GenerateNodeFunction(registry, GenerationMode.ForReals);
}
public NeededCoordinateSpace RequiresNormal()
{
if (referencedGraph == null)
return NeededCoordinateSpace.None;
return referencedGraph.activeNodes.OfType<IMayRequireNormal>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresNormal();
return mask;
});
}
public bool RequiresMeshUV(UVChannel channel)
{
if (referencedGraph == null)
return false;
return referencedGraph.activeNodes.OfType<IMayRequireMeshUV>().Any(x => x.RequiresMeshUV(channel));
}
public bool RequiresScreenPosition()
{
if (referencedGraph == null)
return false;
return referencedGraph.activeNodes.OfType<IMayRequireScreenPosition>().Any(x => x.RequiresScreenPosition());
}
public NeededCoordinateSpace RequiresViewDirection()
{
if (referencedGraph == null)
return NeededCoordinateSpace.None;
return referencedGraph.activeNodes.OfType<IMayRequireViewDirection>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresViewDirection();
return mask;
});
}
public NeededCoordinateSpace RequiresPosition()
{
if (referencedGraph == null)
return NeededCoordinateSpace.None;
return referencedGraph.activeNodes.OfType<IMayRequirePosition>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresPosition();
return mask;
});
}
public NeededCoordinateSpace RequiresTangent()
{
if (referencedGraph == null)
return NeededCoordinateSpace.None;
return referencedGraph.activeNodes.OfType<IMayRequireTangent>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresTangent();
return mask;
});
}
public bool RequiresTime()
{
if (referencedGraph == null)
return false;
return referencedGraph.activeNodes.OfType<IMayRequireTime>().Any(x => x.RequiresTime());
}
public NeededCoordinateSpace RequiresBitangent()
{
if (referencedGraph == null)
return NeededCoordinateSpace.None;
return referencedGraph.activeNodes.OfType<IMayRequireBitangent>().Aggregate(NeededCoordinateSpace.None, (mask, node) =>
{
mask |= node.RequiresBitangent();
return mask;
});
}
public bool RequiresVertexColor()
{
if (referencedGraph == null)
return false;
return referencedGraph.activeNodes.OfType<IMayRequireVertexColor>().Any(x => x.RequiresVertexColor());
}
}
}

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/MetallicMasterNode.cs.meta


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

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/SpecularMasterNode.cs.meta


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

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ProjectSpecificMasterNode.cs.meta


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

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ExportTextureMasterNode.cs.meta


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

97
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ProjectSpecificMasterNode.cs


/*using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Serializable]
public abstract class ProjectSpecificMasterNode : AbstractMasterNode
{
public override string GetSubShader(GenerationMode mode)
{
}
public override string GetFullShader(
GenerationMode mode,
out List<PropertyGenerator.TextureInfo> configuredTextures)
{
var shaderTemplateLocation = ShaderGenerator.GetTemplatePath("shader.template");
if (!File.Exists(shaderTemplateLocation))
{
configuredTextures = new List<PropertyGenerator.TextureInfo>();
return string.Empty;
}
var templateText = File.ReadAllText(shaderTemplateLocation);
var shaderBodyVisitor = new ShaderGenerator();
var shaderFunctionVisitor = new ShaderGenerator();
var shaderPropertiesVisitor = new PropertyGenerator();
var shaderPropertyUsagesVisitor = new ShaderGenerator();
var shaderInputVisitor = new ShaderGenerator();
var vertexShaderBlock = new ShaderGenerator();
GenerateSurfaceShaderInternal(
shaderBodyVisitor,
shaderFunctionVisitor,
shaderInputVisitor,
vertexShaderBlock,
shaderPropertiesVisitor,
shaderPropertyUsagesVisitor,
mode);
var tagsVisitor = new ShaderGenerator();
var blendingVisitor = new ShaderGenerator();
var cullingVisitor = new ShaderGenerator();
var zTestVisitor = new ShaderGenerator();
var zWriteVisitor = new ShaderGenerator();
m_MaterialOptions.GetTags(tagsVisitor);
m_MaterialOptions.GetBlend(blendingVisitor);
m_MaterialOptions.GetCull(cullingVisitor);
m_MaterialOptions.GetDepthTest(zTestVisitor);
m_MaterialOptions.GetDepthWrite(zWriteVisitor);
var resultShader = templateText.Replace("${ShaderName}", GetType() + guid.ToString());
resultShader = resultShader.Replace("${ShaderPropertiesHeader}", shaderPropertiesVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ShaderPropertyUsages}", shaderPropertyUsagesVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${LightingFunctionName}", GetLightFunction());
resultShader = resultShader.Replace("${SurfaceOutputStructureName}", GetSurfaceOutputName());
resultShader = resultShader.Replace("${ShaderFunctions}", shaderFunctionVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ShaderInputs}", shaderInputVisitor.GetShaderString(3));
resultShader = resultShader.Replace("${PixelShaderBody}", shaderBodyVisitor.GetShaderString(3));
resultShader = resultShader.Replace("${Tags}", tagsVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${Blending}", blendingVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${Culling}", cullingVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ZTest}", zTestVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ZWrite}", zWriteVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${VertexShaderDecl}", "vertex:vert");
resultShader = resultShader.Replace("${VertexShaderBody}", vertexShaderBlock.GetShaderString(3));
configuredTextures = shaderPropertiesVisitor.GetConfiguredTexutres();
return Regex.Replace(resultShader, @"\r\n|\n\r|\n|\r", Environment.NewLine);
}
private void GenerateSurfaceShaderInternal(
ShaderGenerator propertyUsages,
GenerationMode mode)
{
var activeNodeList = new List<INode>();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, this);
foreach (var node in activeNodeList.OfType<AbstractMaterialNode>())
{
node.GeneratePropertyUsages(propertyUsages, mode);
}
}
}
}*/

156
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/ExportTextureMasterNode.cs


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
/* [Serializable]
[Title("Master", "Custom Texture")]
public class ExportTextureMasterNode : MasterNode
{
public const string ColorSlotName = "Color";
public const int ColorSlotId = 0;
public ExportTextureMasterNode()
{
name = "ExportTextureMasterNode";
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new MaterialSlot(ColorSlotId, ColorSlotName, ColorSlotName, SlotType.Input, SlotValueType.Vector4, Vector4.zero));
// clear out slot names that do not match the slots we support
RemoveSlotsNameNotMatching(new[] { ColorSlotId });
}
public override PreviewMode previewMode
{
get
{
return PreviewMode.Preview2D;
}
}
public override string GetSubShader(GenerationMode mode, PropertyCollector shaderPropertiesVisitor)
{
return "";
}
public override bool has3DPreview()
{
return false;
}
public override string GetFullShader(GenerationMode generationMode, string name, out List<PropertyCollector.TextureInfo> configuredTextures)
{
// figure out what kind of preview we want!
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, this);
string templateLocation = ShaderGenerator.GetTemplatePath("ExportTexture.template");
if (!File.Exists(templateLocation))
{
configuredTextures = new List<PropertyCollector.TextureInfo>();
return string.Empty;
}
string template = File.ReadAllText(templateLocation);
var shaderBodyVisitor = new ShaderGenerator();
var shaderFunctionVisitor = new ShaderGenerator();
var shaderPropertiesVisitor = new PropertyCollector();
var shaderPropertyUsagesVisitor = new ShaderGenerator();
var shaderInputVisitor = new ShaderGenerator();
// always add color because why not.
shaderInputVisitor.AddShaderChunk("float4 color : COLOR;", true);
bool needBitangent = activeNodeList.OfType<IMayRequireBitangent>().Any(x => x.RequiresBitangent());
bool needsWorldPos = activeNodeList.OfType<IMayRequireViewDirection>().Any(x => x.RequiresViewDirection());
if (needsWorldPos || activeNodeList.OfType<IMayRequireWorldPosition>().Any(x => x.RequiresWorldPosition()))
{
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpacePosition + " = float3(0.0, 0.0, 0.0);", true);
}
if (needBitangent || activeNodeList.OfType<IMayRequireNormal>().Any(x => x.RequiresNormal()))
{
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceNormal + " = float3(0.0, 0.0, 1.0);", true);
}
for (int uvIndex = 0; uvIndex < ShaderGeneratorNames.UVCount; ++uvIndex)
{
var channel = (UVChannel)uvIndex;
if (activeNodeList.OfType<IMayRequireMeshUV>().Any(x => x.RequiresMeshUV(channel)))
{
shaderBodyVisitor.AddShaderChunk("half4 " + channel.GetUVName() + " = float4(IN.localTexcoord.xyz,1.0);", true);
}
}
if (activeNodeList.OfType<IMayRequireViewDirection>().Any(x => x.RequiresViewDirection()))
{
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceViewDirection + " = float3(0.0, 0.0, -1.0);", true);
}
if (activeNodeList.OfType<IMayRequireScreenPosition>().Any(x => x.RequiresScreenPosition()))
{
shaderBodyVisitor.AddShaderChunk("half4 " + ShaderGeneratorNames.ScreenPosition + " = float4(IN.globalTexcoord.xyz, 1.0);", true);
}
if (needBitangent || activeNodeList.OfType<IMayRequireTangent>().Any(x => x.RequiresTangent()))
{
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceTangent + " = float3(1.0,0.0,0.0);", true);
}
if (needBitangent)
{
shaderBodyVisitor.AddShaderChunk("float3 " + ShaderGeneratorNames.WorldSpaceBitangent + " = float3(0.0,1.0,0.0);", true);
}
if (activeNodeList.OfType<IMayRequireVertexColor>().Any(x => x.RequiresVertexColor()))
{
shaderBodyVisitor.AddShaderChunk("float4 " + ShaderGeneratorNames.VertexColor + " = float4(1.0,1.0,1.0,1.0);", true);
}
foreach (var activeNode in activeNodeList.OfType<AbstractMaterialNode>())
{
if (activeNode is IGeneratesFunction)
(activeNode as IGeneratesFunction).GenerateNodeFunction(shaderFunctionVisitor, generationMode);
if (activeNode is IGeneratesBodyCode)
(activeNode as IGeneratesBodyCode).GenerateNodeCode(shaderBodyVisitor, generationMode);
activeNode.GeneratePropertyBlock(shaderPropertiesVisitor, generationMode);
activeNode.GeneratePropertyUsages(shaderPropertyUsagesVisitor, generationMode);
}
var inputSlot = GetInputSlots<MaterialSlot>().First();
var edges = owner.GetEdges(inputSlot.slotReference);
if (edges.Count() > 0)
{
var outputRef = edges.First().outputSlot;
var fromNode = owner.GetNodeFromGuid<AbstractMaterialNode>(outputRef.nodeGuid);
shaderBodyVisitor.AddShaderChunk("return " + fromNode.GetVariableNameForSlot(outputRef.slotId) + ";", true);
}
else
{
shaderBodyVisitor.AddShaderChunk("return float4(0.5, 0.5, 0.5, 0.5);", true);
}
ListPool<INode>.Release(activeNodeList);
template = template.Replace("${ShaderName}", name);
template = template.Replace("${ShaderPropertiesHeader}", shaderPropertiesVisitor.GetPropertiesBlock(2));
template = template.Replace("${ShaderPropertyUsages}", shaderPropertyUsagesVisitor.GetShaderString(3));
template = template.Replace("${ShaderFunctions}", shaderFunctionVisitor.GetShaderString(3));
template = template.Replace("${PixelShaderBody}", shaderBodyVisitor.GetShaderString(4));
//In preview mode we use a different vertex shader, as the custom texture shaders are customized and not preview compatible.
template = template.Replace("${ShaderIsUsingPreview}", generationMode == GenerationMode.Preview ? "_Preview" : "");
configuredTextures = shaderPropertiesVisitor.GetConfiguredTexutres();
return Regex.Replace(template, @"\r\n|\n\r|\n|\r", Environment.NewLine);
}
}*/
}

88
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/MetallicMasterNode.cs


using System;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
/* [Serializable]
[Title("Master", "Metallic")]
public class MetallicMasterNode : AbstractSurfaceMasterNode
{
public const string MetallicSlotName = "Metallic";
public const int MetallicSlotId = 2;
public const string LightFunctionName = "Standard";
public const string SurfaceOutputStructureName = "SurfaceOutputStandard";
public MetallicMasterNode()
{
name = "MetallicMasterNode";
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new MaterialSlot(VertexOffsetId, VertexOffsetName, VertexOffsetName, SlotType.Input, SlotValueType.Vector3, Vector4.zero, ShaderStage.Vertex));
AddSlot(new MaterialSlot(AlbedoSlotId, AlbedoSlotName, AlbedoSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero, ShaderStage.Fragment));
AddSlot(new MaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero, ShaderStage.Fragment));
AddSlot(new MaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, SlotValueType.Vector3, Vector4.zero, ShaderStage.Fragment));
AddSlot(new MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero, ShaderStage.Fragment));
AddSlot(new MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero, ShaderStage.Fragment));
AddSlot(new MaterialSlot(OcclusionSlotId, OcclusionSlotName, OcclusionSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero, ShaderStage.Fragment));
AddSlot(new MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, SlotValueType.Vector1, Vector4.zero, ShaderStage.Fragment));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
MetallicSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId,
VertexOffsetId
});
}
protected override int[] surfaceInputs
{
get
{
return new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
MetallicSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId,
};
}
}
protected override int[] vertexInputs
{
get
{
return new[]
{
VertexOffsetId
};
}
}
public override string GetSurfaceOutputName()
{
return SurfaceOutputStructureName;
}
public override string GetLightFunction()
{
return LightFunctionName;
}
}*/
}

部分文件因为文件数量过多而无法显示

正在加载...
取消
保存