浏览代码

Merge branch 'master' into sliders

/main
Matt Dean 7 年前
当前提交
725a1ea9
共有 97 个文件被更改,包括 1505 次插入630 次删除
  1. 2
      LICENSE
  2. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/DynamicVectorMaterialSlot.cs
  3. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/SamplerStateShaderProperty.cs
  4. 36
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/SerializableCubemap.cs
  5. 35
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/SerializableTexture.cs
  6. 7
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/TextureSamplerState.cs
  7. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/UVMaterialSlot.cs
  8. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/Vector1MaterialSlot.cs
  9. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/Vector2MaterialSlot.cs
  10. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/Vector3MaterialSlot.cs
  11. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/Vector4MaterialSlot.cs
  12. 20
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Implementation/NodeUtils.cs
  13. 71
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs
  14. 38
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightUnlitSubShader.cs
  15. 20
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/PBRMasterNode.cs
  16. 24
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/MasterNodes/UnlitMasterNode.cs
  17. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/AbstractMaterialNode.cs
  18. 1
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Blend/BlendMode.cs
  19. 154
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Blend/BlendNode.cs
  20. 76
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Mask/ChannelMaskNode.cs
  21. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Normal/NormalCreateNode.cs
  22. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Normal/NormalStrengthNode.cs
  23. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Channel/FlipNode.cs
  24. 19
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/CodeFunctionNode.cs
  25. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Basic/TimeNode.cs
  26. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Basic/Vector1Node.cs
  27. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Basic/Vector2Node.cs
  28. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Basic/Vector3Node.cs
  29. 9
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Basic/Vector4Node.cs
  30. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs
  31. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/UVNode.cs
  32. 23
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Scene/AmbientNode.cs
  33. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Scene/CameraNode.cs
  34. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Scene/FogNode.cs
  35. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Scene/ReflectionProbeNode.cs
  36. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/SampleTexture2DNode.cs
  37. 36
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/MasterNode.cs
  38. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Advanced/LogNode.cs
  39. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Advanced/ModuloNode.cs
  40. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Advanced/PosterizeNode.cs
  41. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Advanced/ReciprocalNode.cs
  42. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Advanced/ReciprocalSquareRootNode.cs
  43. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Basic/DivideNode.cs
  44. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Basic/MultiplyNode.cs
  45. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Basic/PowerNode.cs
  46. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Basic/SubtractNode.cs
  47. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Interpolation/InverseLerpNode.cs
  48. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Interpolation/LerpNode.cs
  49. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Interpolation/SmoothstepNode.cs
  50. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Range/MinimumNode.cs
  51. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Range/OneMinusNode.cs
  52. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Range/RemapNode.cs
  53. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Round/StepNode.cs
  54. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Trigonometry/ArccosineNode.cs
  55. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Vector/CrossProductNode.cs
  56. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Vector/DotProductNode.cs
  57. 9
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Vector/FresnelEffectNode.cs
  58. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Vector/ProjectionNode.cs
  59. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Vector/ReflectionNode.cs
  60. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Vector/RejectionNode.cs
  61. 162
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/UV/FlipbookNode.cs
  62. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/UV/TwirlNode.cs
  63. 40
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/GraphUtil.cs
  64. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGenerator.cs
  65. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/UvChannel.cs
  66. 90
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ChannelMixerControl.cs
  67. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ColorControl.cs
  68. 51
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ToggleControl.cs
  69. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/EdgeConnectorListener.cs
  70. 17
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/MaterialGraphEditWindow.cs
  71. 16
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/PreviewManager.cs
  72. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/SearchWindowProvider.cs
  73. 35
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/GraphEditorView.cs
  74. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/MaterialGraphView.cs
  75. 101
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/MaterialNodeView.cs
  76. 46
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/PreviewSceneResources.cs
  77. 34
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/ShaderPort.cs
  78. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/Slots/ColorRGBSlotControlView.cs
  79. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/Slots/ColorSlotControlView.cs
  80. 16
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Importers/ShaderGraphImporter.cs
  81. 108
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Resources/Styles/MaterialGraph.uss
  82. 112
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRExtraPasses.template
  83. 97
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRForwardPass.template
  84. 31
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightUnlitPass.template
  85. 2
      MaterialGraphProject/Assets/UnityShaderEditor/LICENSE
  86. 8
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/Functions.hlsl
  87. 8
      MaterialGraphProject/Assets/UnityShaderEditor/ShaderGraphLibrary/ShaderVariables.hlsl
  88. 2
      MaterialGraphProject/Assets/UnityShaderEditor/package.json
  89. 2
      MaterialGraphProject/ProjectSettings/ProjectVersion.txt
  90. 2
      MaterialGraphProject/UnityPackageManager/manifest.json
  91. 25
      README.md
  92. 189
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/InvertColorsNode.cs
  93. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/InvertColorsNode.cs.meta
  94. 78
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ChannelEnumMaskControl.cs
  95. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ChannelEnumMaskControl.cs.meta
  96. 51
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Resources/Shaders/BlitNoAlpha.shader
  97. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Resources/Shaders/BlitNoAlpha.shader.meta

2
LICENSE


Unity Companion License (“License”)
Software Copyright © 2017 Unity Technologies ApS
Software Copyright © 2018 Unity Technologies ApS
Unity Technologies ApS (“Unity”) grants to you a worldwide, non-exclusive,
no-charge, and royalty-free copyright license to reproduce, prepare derivative

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


protected override string ConcreteSlotValueAsVariable(AbstractMaterialNode.OutputPrecision precision)
{
var channelCount = SlotValueHelper.GetChannelCount(concreteValueType);
var values = value.x.ToString();
string values = NodeUtils.FloatToShaderValue(value.x);
if (channelCount == 1)
return values;
for (var i = 1; i < channelCount; i++)

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


public override string GetPropertyDeclarationString(string delimiter = ";")
{
return string.Format(@"SAMPLER2D({0}){1}", referenceName, delimiter);
return string.Format(@"SAMPLER({0}){1}", referenceName, delimiter);
}
public override PreviewProperty GetPreviewMaterialProperty()

36
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/SerializableCubemap.cs


namespace UnityEditor.ShaderGraph
{
[Serializable]
public class SerializableCubemap : ISerializationCallbackReceiver
public class SerializableCubemap
{
[SerializeField]
private string m_SerializedCubemap;

public Cubemap cubemap;
}
Cubemap m_Cubemap;
if (m_Cubemap == null && !string.IsNullOrEmpty(m_SerializedCubemap))
{
var cube = new CubemapHelper();
EditorJsonUtility.FromJsonOverwrite(m_SerializedCubemap, cube);
m_Cubemap = cube.cubemap;
m_SerializedCubemap = null;
}
return m_Cubemap;
}
set { m_Cubemap = value; }
}
if (string.IsNullOrEmpty(m_SerializedCubemap))
return null;
public void OnBeforeSerialize()
{
var cube = new CubemapHelper { cubemap = cubemap };
m_SerializedCubemap = EditorJsonUtility.ToJson(cube, true);
}
var cube = new CubemapHelper();
EditorJsonUtility.FromJsonOverwrite(m_SerializedCubemap, cube);
return cube.cubemap;
}
set
{
if(cubemap == value)
return;
public void OnAfterDeserialize()
{
var cubemapHelper = new CubemapHelper();
cubemapHelper.cubemap = value;
m_SerializedCubemap = EditorJsonUtility.ToJson(cubemapHelper, true);
}
}
}
}

35
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/SerializableTexture.cs


namespace UnityEditor.ShaderGraph
{
[Serializable]
public class SerializableTexture : ISerializationCallbackReceiver
public class SerializableTexture
{
[SerializeField]
private string m_SerializedTexture;

public Texture texture;
}
Texture m_Texture;
if (m_Texture == null && !string.IsNullOrEmpty(m_SerializedTexture))
{
var tex = new TextureHelper();
EditorJsonUtility.FromJsonOverwrite(m_SerializedTexture, tex);
m_Texture = tex.texture;
m_SerializedTexture = null;
}
return m_Texture;
if (string.IsNullOrEmpty(m_SerializedTexture))
return null;
var tex = new TextureHelper();
EditorJsonUtility.FromJsonOverwrite(m_SerializedTexture, tex);
return tex.texture;
set { m_Texture = value; }
}
set
{
if (texture == value)
return;
public void OnBeforeSerialize()
{
var tex = new TextureHelper { texture = texture };
m_SerializedTexture = EditorJsonUtility.ToJson(tex, true);
}
public void OnAfterDeserialize()
{
var textureHelper = new TextureHelper();
textureHelper.texture = value;
m_SerializedTexture = EditorJsonUtility.ToJson(textureHelper, true);
}
}
}
}

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


public enum FilterMode
{
Linear,
Point
Point,
Trilinear
Clamp
Clamp,
Mirror,
MirrorOnce
}
[SerializeField] private FilterMode m_filter = FilterMode.Linear;

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


[Serializable]
public class UVMaterialSlot : Vector2MaterialSlot, IMayRequireMeshUV
{
private UVChannel m_Channel = UVChannel.uv0;
private UVChannel m_Channel = UVChannel.UV0;
public UVChannel channel
{

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


protected override string ConcreteSlotValueAsVariable(AbstractMaterialNode.OutputPrecision precision)
{
return value.ToString();
return NodeUtils.FloatToShaderValue(value);
}
public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode)

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


protected override string ConcreteSlotValueAsVariable(AbstractMaterialNode.OutputPrecision precision)
{
return precision + "2 (" + value.x + "," + value.y + ")";
return precision + "2 (" + NodeUtils.FloatToShaderValue(value.x) + "," + NodeUtils.FloatToShaderValue(value.y) + ")";
}
public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode)

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


protected override string ConcreteSlotValueAsVariable(AbstractMaterialNode.OutputPrecision precision)
{
return precision + "3 (" + value.x + "," + value.y + "," + value.z + ")";
return precision + "3 (" + NodeUtils.FloatToShaderValue(value.x) + "," + NodeUtils.FloatToShaderValue(value.y) + "," + NodeUtils.FloatToShaderValue(value.z) + ")";
}
public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode)

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


protected override string ConcreteSlotValueAsVariable(AbstractMaterialNode.OutputPrecision precision)
{
return precision + "4 (" + value.x + "," + value.y + "," + value.z + "," + value.w + ")";
return precision + "4 (" + NodeUtils.FloatToShaderValue(value.x) + "," + NodeUtils.FloatToShaderValue(value.y) + "," + NodeUtils.FloatToShaderValue(value.z) + "," + NodeUtils.FloatToShaderValue(value.w) + ")";
}
public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode)

20
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Implementation/NodeUtils.cs


using System;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
namespace UnityEditor.Graphing
{

char[] arr = input.ToCharArray();
arr = Array.FindAll<char>(arr, (c => (Char.IsLetterOrDigit(c))));
return new string(arr);
}
public static string FloatToShaderValue(float value)
{
if (Single.IsPositiveInfinity(value))
return "1.#INF";
else if (Single.IsNegativeInfinity(value))
return "-1.#INF";
else if (Single.IsNaN(value))
return "NAN";
else
{
decimal amount;
if( decimal.TryParse(value.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture, out amount) )
return amount.ToString();
else
return value.ToString();
}
}
}
}

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


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

}
};
private static void GenerateApplicationVertexInputs(ShaderGraphRequirements graphRequiements, ShaderGenerator vertexInputs)
{
vertexInputs.AddShaderChunk("struct GraphVertexInput", false);
vertexInputs.AddShaderChunk("{", false);
vertexInputs.Indent();
vertexInputs.AddShaderChunk("float4 vertex : POSITION;", false);
vertexInputs.AddShaderChunk("float3 normal : NORMAL;", false);
vertexInputs.AddShaderChunk("float4 tangent : TANGENT;", false);
if (graphRequiements.requiresVertexColor)
{
vertexInputs.AddShaderChunk("float4 color : COLOR;", false);
}
foreach (var channel in graphRequiements.requiresMeshUVs.Distinct())
vertexInputs.AddShaderChunk(string.Format("float4 texcoord{0} : TEXCOORD{0};", (int)channel), false);
vertexInputs.Deindent();
vertexInputs.AddShaderChunk("};", false);
}
private static string GetShaderPassFromTemplate(string template, PBRMasterNode masterNode, Pass pass, GenerationMode mode, SurfaceMaterialOptions materialOptions)
{
var builder = new ShaderStringBuilder();

modelRequiements.requiresBitangent |= NeededCoordinateSpace.World;
modelRequiements.requiresPosition |= NeededCoordinateSpace.World;
modelRequiements.requiresViewDir |= NeededCoordinateSpace.World;
modelRequiements.requiresMeshUVs.Add(UVChannel.uv1);
modelRequiements.requiresMeshUVs.Add(UVChannel.UV1);
GenerateApplicationVertexInputs(requirements.Union(modelRequiements), vertexInputs);
GraphUtil.GenerateApplicationVertexInputs(requirements.Union(modelRequiements), vertexInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresNormal, InterpolatorType.Normal, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresTangent, InterpolatorType.Tangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresBitangent, InterpolatorType.BiTangent, surfaceInputs);

var cullingVisitor = new ShaderGenerator();
var zTestVisitor = new ShaderGenerator();
var zWriteVisitor = new ShaderGenerator();
materialOptions.GetBlend(blendingVisitor);
materialOptions.GetCull(cullingVisitor);

if (masterNode.model == PBRMasterNode.Model.Specular)
defines.AddShaderChunk("#define _SPECULAR_SETUP 1", true);
switch (masterNode.alphaMode)
{
case PBRMasterNode.AlphaMode.AlphaBlend:
case PBRMasterNode.AlphaMode.AdditiveBlend:
defines.AddShaderChunk("#define _AlphaOut 1", true);
break;
}
defines.AddShaderChunk("#define _AlphaClip 1", true);
defines.AddShaderChunk("#define _AlphaClip 1", true);
var templateLocation = ShaderGenerator.GetTemplatePath(template);

resultPass = resultPass.Replace("${SurfaceInputs}", localSurfaceInputs.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceOutputRemap}", surfaceOutputRemap.GetShaderString(3));
resultPass = resultPass.Replace("${Tags}", string.Empty);
resultPass = resultPass.Replace("${Blending}", blendingVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${Culling}", cullingVisitor.GetShaderString(2));

subShader.Indent();
subShader.AddShaderChunk("Tags{ \"RenderPipeline\" = \"LightweightPipeline\"}", true);
var materialOptions = new SurfaceMaterialOptions();
switch (masterNode.alphaMode)
{
case PBRMasterNode.AlphaMode.Opaque:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.Zero;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.On;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Geometry;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Opaque;
break;
case PBRMasterNode.AlphaMode.AlphaBlend:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.SrcAlpha;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.OneMinusSrcAlpha;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
case PBRMasterNode.AlphaMode.AdditiveBlend:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
}
var materialOptions = MasterNode.GetMaterialOptionsFromAlphaMode(masterNode.alphaMode);
var tagsVisitor = new ShaderGenerator();
materialOptions.GetTags(tagsVisitor);
subShader.AddShaderChunk(tagsVisitor.GetShaderString(0), true);

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


PixelShaderSlots = new List<int>()
{
UnlitMasterNode.ColorSlotId,
UnlitMasterNode.AlphaSlotId
UnlitMasterNode.AlphaSlotId,
UnlitMasterNode.AlphaThresholdSlotId
}
};

public List<int> PixelShaderSlots;
}
private static string GetShaderPassFromTemplate(string template, UnlitMasterNode masterNode, Pass pass, GenerationMode mode)
private static string GetShaderPassFromTemplate(
string template,
UnlitMasterNode masterNode,
Pass pass,
GenerationMode mode,
SurfaceMaterialOptions materialOptions)
{
var builder = new ShaderStringBuilder();
builder.IncreaseIndent();

NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots);
var requirements = ShaderGraphRequirements.FromNodes(activeNodeList);
GraphUtil.GenerateApplicationVertexInputs(requirements, vertexInputs, 0, 8);
GraphUtil.GenerateApplicationVertexInputs(requirements, vertexInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresNormal, InterpolatorType.Normal, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresTangent, InterpolatorType.Tangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresBitangent, InterpolatorType.BiTangent, surfaceInputs);

graph.AddShaderChunk(surfaceVertexShader.GetShaderString(2), false);
graph.AddShaderChunk(surfaceDescriptionFunction.GetShaderString(2), false);
var tagsVisitor = new ShaderGenerator();
var materialOptions = new SurfaceMaterialOptions();
materialOptions.GetTags(tagsVisitor);
materialOptions.GetBlend(blendingVisitor);
materialOptions.GetCull(cullingVisitor);
materialOptions.GetDepthTest(zTestVisitor);

var surfaceOutputRemap = new ShaderGenerator();
var reqs = ShaderGraphRequirements.none;
reqs.requiresNormal |= NeededCoordinateSpace.World;
reqs.requiresTangent |= NeededCoordinateSpace.World;
reqs.requiresBitangent |= NeededCoordinateSpace.World;
reqs.requiresPosition |= NeededCoordinateSpace.World;
reqs.requiresViewDir |= NeededCoordinateSpace.World;
ShaderGenerator.GenerateStandardTransforms(
3,

CoordinateSpace.World);
ShaderGenerator defines = new ShaderGenerator();
if (masterNode.IsSlotConnected(UnlitMasterNode.AlphaThresholdSlotId))
defines.AddShaderChunk("#define _AlphaClip 1", true);
var templateLocation = ShaderGenerator.GetTemplatePath(template);
foreach (var slot in usedSlots)

resultPass = resultPass.Replace("${SurfaceInputs}", localSurfaceInputs.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceOutputRemap}", surfaceOutputRemap.GetShaderString(3));
resultPass = resultPass.Replace("${Tags}", tagsVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${Tags}", string.Empty);
resultPass = resultPass.Replace("${LOD}", "" + materialOptions.lod);
return resultPass;
}

subShader.Indent();
subShader.AddShaderChunk("Tags{ \"RenderType\" = \"Opaque\" \"RenderPipeline\" = \"LightweightPipeline\"}", true);
var materialOptions = MasterNode.GetMaterialOptionsFromAlphaMode(masterNode.alphaMode);
var tagsVisitor = new ShaderGenerator();
materialOptions.GetTags(tagsVisitor);
subShader.AddShaderChunk(tagsVisitor.GetShaderString(0), true);
mode),
mode,
materialOptions),
true);
subShader.Deindent();

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


namespace UnityEditor.ShaderGraph
{
public enum AlphaMode
{
Opaque,
AlphaBlend,
AdditiveBlend
}
[Serializable]
[Title("Master", "PBR")]
public class PBRMasterNode : MasterNode

Metallic
}
public enum AlphaMode
{
Opaque,
AlphaBlend,
AdditiveBlend
}
[SerializeField]
private Model m_Model = Model.Metallic;

public PBRMasterNode()
{
UpdateNodeAfterDeserialization();
}
public bool IsSlotConnected(int slotId)
{
var slot = FindSlot<MaterialSlot>(slotId);
return slot != null && owner.GetEdges(slot.slotReference).Any();
}
public sealed override void UpdateNodeAfterDeserialization()

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


using System.Collections.Generic;
using System.Linq;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
namespace UnityEditor.ShaderGraph

{
public const string ColorSlotName = "Color";
public const string AlphaSlotName = "Alpha";
public const string AlphaClipThresholdSlotName = "AlphaClipThreshold";
public const int AlphaThresholdSlotId = 8;
[SerializeField]
private AlphaMode m_AlphaMode;
[EnumControl("")]
public AlphaMode alphaMode
{
get { return m_AlphaMode; }
set
{
if (m_AlphaMode == value)
return;
m_AlphaMode = value;
Dirty(ModificationScope.Graph);
}
}
public UnlitMasterNode()
{

name = "Unlit Master";
AddSlot(new ColorRGBMaterialSlot(ColorSlotId, ColorSlotName, ColorSlotName, SlotType.Input, Color.grey, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1, 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

ColorSlotId,
AlphaSlotId
AlphaSlotId,
AlphaThresholdSlotId
});
}

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


public virtual void UpdateNodeAfterDeserialization()
{}
public bool IsSlotConnected(int slotId)
{
var slot = FindSlot<MaterialSlot>(slotId);
return slot != null && owner.GetEdges(slot.slotReference).Any();
}
}
}

1
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Blend/BlendMode.cs


Lighten,
LinearBurn,
LinearDodge,
LinearLight,
LinearLightAddSub,
Multiply,
Negation,

154
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Blend/BlendNode.cs


[SerializeField]
BlendMode m_BlendMode = BlendMode.Overlay;
[EnumControl("")]
[EnumControl("Mode")]
public BlendMode blendMode
{
get { return m_BlendMode; }

}
static string Unity_Blend_Burn(
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = 1.0 - (1.0 - B)/A;
Out = 1.0 - (1.0 - Blend)/Base;
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = min(B, A);
Out = min(Blend, Base);
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = abs(B - A);
Out = abs(Blend - Base);
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = B / (1.0 - A);
Out = Base / (1.0 - Blend);
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = A / (B + 0.000000000001);
Out = Base / (Blend + 0.000000000001);
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = B + A - (2.0 * B * A);
Out = Blend + Base - (2.0 * Blend * Base);
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
{precision}{slot2dimension} result1 = 1.0 - 2.0 * (1.0 - A) * (1.0 - B);
{precision}{slot2dimension} result2 = 2.0 * A * B;
{precision}{slot2dimension} zeroOrOne = step(A, 0.5);
{precision}{slot2dimension} result1 = 1.0 - 2.0 * (1.0 - Base) * (1.0 - Blend);
{precision}{slot2dimension} result2 = 2.0 * Base * Blend;
{precision}{slot2dimension} zeroOrOne = step(Blend, 0.5);
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = step(1 - A, B);
Out = step(1 - Base, Blend);
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = max(B, A);
Out = max(Blend, Base);
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = A + B - 1.0;
Out = Base + Blend - 1.0;
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = A + B;
Out = Base + Blend;
}";
}
static string Unity_Blend_LinearLight(
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
[Slot(2, Binding.None)] out DynamicDimensionVector Out)
{
return
@"
{
Out = Blend < 0.5 ? max(Base + (2 * Blend) - 1, 0) : min(Base + 2 * (Blend - 0.5), 1);
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = B + 2.0 * A - 1.0;
Out = Blend + 2.0 * Base - 1.0;
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = A * B;
Out = Base * Blend;
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = 1.0 - abs(1.0 - B - A);
Out = 1.0 - abs(1.0 - Blend - Base);
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = 1.0 - (1.0 - B) * (1.0 - A);
Out = 1.0 - (1.0 - Blend) * (1.0 - Base);
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
{precision}{slot2dimension} result1 = 1.0 - 2.0 * (1.0 - A) * (1.0 - B);
{precision}{slot2dimension} result2 = 2.0 * A * B;
{precision}{slot2dimension} zeroOrOne = step(B, 0.5);
{precision}{slot2dimension} result1 = 1.0 - 2.0 * (1.0 - Base) * (1.0 - Blend);
{precision}{slot2dimension} result2 = 2.0 * Base * Blend;
{precision}{slot2dimension} zeroOrOne = step(Base, 0.5);
Out = result2 * zeroOrOne + (1 - zeroOrOne) * result1;
}
";

[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
{precision}{slot2dimension} check = step (0.5, A);
{precision}{slot2dimension} result1 = check * max(2.0 * (A - 0.5), B);
Out = result1 + (1.0 - check) * min(2.0 * A, B);
{precision}{slot2dimension} check = step (0.5, Blend);
{precision}{slot2dimension} result1 = check * max(2.0 * (Base - 0.5), Blend);
Out = result1 + (1.0 - check) * min(2.0 * Base, Blend);
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
{precision}{slot2dimension} result1 = 2.0 * B * A + B * A - 2.0 * B * B * A;
{precision}{slot2dimension} result2 = 2.0 * sqrt(B) * A - sqrt(B) + 2.0 * B - 2.0 * B * A;
{precision}{slot2dimension} zeroOrOne = step(0.5, A);
{precision}{slot2dimension} result1 = 2.0 * Base * Blend + Base * Base * (1.0 - 2.0 * Blend);
{precision}{slot2dimension} result2 = sqrt(Base) * (2.0 * Blend - 1.0) + 2.0 * Base * (1.0 - Blend);
{precision}{slot2dimension} zeroOrOne = step(0.5, Blend);
Out = result2 * zeroOrOne + (1 - zeroOrOne) * result1;
}
";

[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
{precision}{slot2dimension} result1 = 1.0 - (1.0 - B) / (2.0 * A);
{precision}{slot2dimension} result2 = B / (2.0 * (1.0 - A));
{precision}{slot2dimension} zeroOrOne = step(0.5, A);
{precision}{slot2dimension} result1 = 1.0 - (1.0 - Blend) / (2.0 * Base);
{precision}{slot2dimension} result2 = Blend / (2.0 * (1.0 - Base));
{precision}{slot2dimension} zeroOrOne = step(0.5, Base);
Out = result2 * zeroOrOne + (1 - zeroOrOne) * result1;
}
";

[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None)] DynamicDimensionVector Base,
[Slot(1, Binding.None)] DynamicDimensionVector Blend,
Out = A - B;
Out = Base - Blend;
}
";
}

76
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Mask/ChannelMaskNode.cs


string GetFunctionName()
{
return string.Format("Unity_ChannelMask_{0}_{1}", channel, precision);
string channelSum = "None";
if (channelMask != 0)
{
bool red = (channelMask & 1) != 0;
bool green = (channelMask & 2) != 0;
bool blue = (channelMask & 4) != 0;
bool alpha = (channelMask & 8) != 0;
channelSum = string.Format("{0}{1}{2}{3}", red ? "Red" : "", green ? "Green" : "", blue ? "Blue" : "", alpha ? "Alpha" : "");
}
return string.Format("Unity_ChannelMask_{0}_{1}", channelSum, precision);
}
public sealed override void UpdateNodeAfterDeserialization()

RemoveSlotsNameNotMatching(new[] { InputSlotId, OutputSlotId });
}
public TextureChannel channel;
private TextureChannel m_Channel = TextureChannel.Red;
private int m_ChannelMask = -1;
[ChannelEnumControl("Channel")]
public TextureChannel channel
[ChannelEnumMaskControl("Channels")]
public int channelMask
get { return m_Channel; }
get { return m_ChannelMask; }
if (m_Channel == value)
if (m_ChannelMask == value)
m_Channel = value;
m_ChannelMask = value;
Dirty(ModificationScope.Graph);
}
}

int channelCount = SlotValueHelper.GetChannelCount(FindSlot<MaterialSlot>(InputSlotId).concreteValueType);
if ((int)channel >= channelCount)
channel = TextureChannel.Red;
if (channelMask >= 1 << channelCount)
channelMask = -1;
}
string GetFunctionPrototype(string argIn, string argOut)

public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode)
{
ValidateChannelCount();
int channelCount = SlotValueHelper.GetChannelCount(FindSlot<MaterialSlot>(InputSlotId).concreteValueType);
switch (channel)
if(channelMask == 0)
s.AppendLine("Out = 0;");
else if(channelMask == -1)
s.AppendLine("Out = In;");
else
case TextureChannel.Green:
s.AppendLine("Out = In.yyyy;");
break;
case TextureChannel.Blue:
s.AppendLine("Out = In.zzzz;");
break;
case TextureChannel.Alpha:
s.AppendLine("Out = In.wwww;");
break;
case TextureChannel.Red:
s.AppendLine("Out = In.xxxx;");
break;
default:
throw new ArgumentOutOfRangeException();
bool red = (channelMask & 1) != 0;
bool green = (channelMask & 2) != 0;
bool blue = (channelMask & 4) != 0;
bool alpha = (channelMask & 8) != 0;
switch (channelCount)
{
case 1:
s.AppendLine("Out = In.r;");
break;
case 2:
s.AppendLine(string.Format("Out = {0}2({1}, {2});", precision,
red ? "In.r": "0", green ? "In.g" : "0"));
break;
case 3:
s.AppendLine(string.Format("Out = {0}3({1}, {2}, {3});", precision,
red ? "In.r" : "0", green ? "In.g" : "0", blue ? "In.b" : "0"));
break;
case 4:
s.AppendLine(string.Format("Out = {0}4({1}, {2}, {3}, {4});", precision,
red ? "In.r" : "0", green ? "In.g" : "0", blue ? "In.b" : "0", alpha ? "In.a" : "0"));
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
});

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Normal/NormalCreateNode.cs


public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Texture2DInputMaterialSlot(TextureInputId, k_TextureInputName, k_TextureInputName));
AddSlot(new UVMaterialSlot(UVInputId, k_UVInputName, k_UVInputName, UVChannel.uv0));
AddSlot(new UVMaterialSlot(UVInputId, k_UVInputName, k_UVInputName, UVChannel.UV0));
AddSlot(new SamplerStateMaterialSlot(SamplerInputId, k_SamplerInputName, k_SamplerInputName, SlotType.Input));
AddSlot(new Vector1MaterialSlot(OffsetInputId, k_OffsetInputName, k_OffsetInputName, SlotType.Input, 0.5f));
AddSlot(new Vector1MaterialSlot(StrengthInputId, k_StrengthInputName, k_StrengthInputName, SlotType.Input, 8f));

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Normal/NormalStrengthNode.cs


return
@"
{
Out = {precision}3(In.rg * Strength, 1);
Out = {precision}3(In.rg * Strength, In.b);
}
";
}

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Channel/FlipNode.cs


FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType.ToString(precision));
using (sb.BlockScope())
{
sb.AppendLine("Out = abs(Flip - In);");
sb.AppendLine("Out = (Flip * -2 + 1) * In;");
}
visitor.AddShaderChunk(sb.ToString(), true);
}

FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType.ToString(precision));
using (s.BlockScope())
{
s.AppendLine("Out = abs(Flip - In);");
s.AppendLine("Out = (Flip * -2 + 1) * In;");
}
});
}

19
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/CodeFunctionNode.cs


foreach (var par in method.GetParameters())
{
var attribute = GetSlotAttribute(par);
var name = GraphUtil.ConvertCamelCase(par.Name, true);
s = new ColorRGBAMaterialSlot(attribute.slotId, par.Name, par.Name, SlotType.Input, attribute.defaultValue ?? Vector4.zero, hidden: attribute.hidden);
s = new ColorRGBAMaterialSlot(attribute.slotId, name, par.Name, SlotType.Input, attribute.defaultValue ?? Vector4.zero, hidden: attribute.hidden);
s = new ColorRGBAMaterialSlot(attribute.slotId, par.Name, par.Name, SlotType.Input, attribute.defaultValue ?? Vector4.zero, hidden: attribute.hidden);
s = new ColorRGBAMaterialSlot(attribute.slotId, name, par.Name, SlotType.Input, attribute.defaultValue ?? Vector4.zero, hidden: attribute.hidden);
s = new ColorRGBMaterialSlot(attribute.slotId, par.Name, par.Name, SlotType.Input, attribute.defaultValue ?? Vector4.zero, hidden: attribute.hidden);
s = new ColorRGBMaterialSlot(attribute.slotId, name, par.Name, SlotType.Input, attribute.defaultValue ?? Vector4.zero, hidden: attribute.hidden);
par.Name,
name,
s = CreateBoundSlot(attribute.binding, attribute.slotId, par.Name, par.Name, attribute.hidden);
s = CreateBoundSlot(attribute.binding, attribute.slotId, name, par.Name, attribute.hidden);
slots.Add(s);
m_Slots.Add(attribute);

case Binding.TangentSpacePosition:
return new PositionMaterialSlot(slotId, displayName, shaderOutputName, CoordinateSpace.Tangent);
case Binding.MeshUV0:
return new UVMaterialSlot(slotId, displayName, shaderOutputName, UVChannel.uv0);
return new UVMaterialSlot(slotId, displayName, shaderOutputName, UVChannel.UV0);
return new UVMaterialSlot(slotId, displayName, shaderOutputName, UVChannel.uv1);
return new UVMaterialSlot(slotId, displayName, shaderOutputName, UVChannel.UV1);
return new UVMaterialSlot(slotId, displayName, shaderOutputName, UVChannel.uv2);
return new UVMaterialSlot(slotId, displayName, shaderOutputName, UVChannel.UV2);
return new UVMaterialSlot(slotId, displayName, shaderOutputName, UVChannel.uv3);
return new UVMaterialSlot(slotId, displayName, shaderOutputName, UVChannel.UV3);
case Binding.ScreenPosition:
return new ScreenPositionMaterialSlot(slotId, displayName, shaderOutputName);
case Binding.ObjectSpaceViewDirection:

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Basic/TimeNode.cs


public class TimeNode : AbstractMaterialNode, IMayRequireTime
{
private const string kOutputSlotName = "Time";
private const string kOutputSlot1Name = "SinTime";
private const string kOutputSlot2Name = "CosTime";
private const string kOutputSlot3Name = "DeltaTime";
private const string kOutputSlot4Name = "SmoothDelta";
private const string kOutputSlot1Name = "Sine Time";
private const string kOutputSlot2Name = "Cosine Time";
private const string kOutputSlot3Name = "Delta Time";
private const string kOutputSlot4Name = "Smooth Delta";
public const int OutputSlotId = 0;
public const int OutputSlot1Id = 1;

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


if (generationMode.IsPreview())
return;
visitor.AddShaderChunk(precision + " " + GetVariableNameForNode() + " = " + m_Value + ";", true);
visitor.AddShaderChunk(precision + " " + GetVariableNameForNode() + " = " + NodeUtils.FloatToShaderValue(m_Value) + ";", true);
}
public override string GetVariableNameForSlot(int slotId)

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


if (generationMode.IsPreview())
return;
visitor.AddShaderChunk(precision + "2 " + GetVariableNameForNode() + " = " + precision + "2" + m_Value + ";", true);
visitor.AddShaderChunk(string.Format("{0}2 {1} = {0}2({2},{3});", precision, GetVariableNameForNode(), NodeUtils.FloatToShaderValue(m_Value.x), NodeUtils.FloatToShaderValue(m_Value.y)), true);
}
public override string GetVariableNameForSlot(int slotId)

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Basic/Vector3Node.cs


if (generationMode.IsPreview())
return;
visitor.AddShaderChunk(precision + "3 " + GetVariableNameForNode() + " = " + precision + "3" + m_Value + ";", true);
var s = string.Format("{0}3 {1} = {0}3({2},{3},{4});",
precision,
GetVariableNameForNode(),
NodeUtils.FloatToShaderValue(m_Value.x),
NodeUtils.FloatToShaderValue(m_Value.y),
NodeUtils.FloatToShaderValue(m_Value.z));
visitor.AddShaderChunk(s, true);
}
public override string GetVariableNameForSlot(int slotId)

9
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Basic/Vector4Node.cs


if (generationMode.IsPreview())
return;
visitor.AddShaderChunk(precision + "4 " + GetVariableNameForNode() + " = " + precision + "4" + m_Value + ";", true);
var s = string.Format("{0}4 {1} = {0}4({2},{3},{4},{5});",
precision,
GetVariableNameForNode(),
NodeUtils.FloatToShaderValue(m_Value.x),
NodeUtils.FloatToShaderValue(m_Value.y),
NodeUtils.FloatToShaderValue(m_Value.z),
NodeUtils.FloatToShaderValue(m_Value.w));
visitor.AddShaderChunk(s, true);
}
public override string GetVariableNameForSlot(int slotId)

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


[SerializeField]
private ScreenSpaceType m_ScreenSpaceType = ScreenSpaceType.Default;
[EnumControl("")]
[EnumControl("Mode")]
public ScreenSpaceType screenSpaceType
{
get { return m_ScreenSpaceType; }

switch (m_ScreenSpaceType)
{
case ScreenSpaceType.Raw:
visitor.AddShaderChunk(string.Format("{0}4 {1} = In.{2};", precision, GetVariableNameForSlot(kOutputSlotId),
visitor.AddShaderChunk(string.Format("{0}4 {1} = IN.{2};", precision, GetVariableNameForSlot(kOutputSlotId),
string.Format("float4((In.{0}.xy / In.{0}.w) * 2 - 1, 0, 0)", ShaderGeneratorNames.ScreenPosition)), true);
string.Format("float4((IN.{0}.xy / IN.{0}.w) * 2 - 1, 0, 0)", ShaderGeneratorNames.ScreenPosition)), true);
string.Format("float4((In.{0}.xy / In.{0}.w) * 2 - 1, 0, 0)", ShaderGeneratorNames.ScreenPosition)), true);
string.Format("float4((IN.{0}.xy / IN.{0}.w) * 2 - 1, 0, 0)", ShaderGeneratorNames.ScreenPosition)), true);
string.Format("float4(In.{0}.x * _ScreenParams.x / _ScreenParams.y, In.{0}.y, 0, 0)", ShaderGeneratorNames.ScreenPosition)), true);
string.Format("float4({0}.x * _ScreenParams.x / _ScreenParams.y, {0}.y, 0, 0)", GetVariableNameForSlot(kOutputSlotId))), true);
string.Format("float4(In.{0}.xy / In.{0}.w, 0, 0)", ShaderGeneratorNames.ScreenPosition)), 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/UVNode.cs


[SerializeField]
private UVChannel m_OutputChannel;
[EnumControl("")]
[EnumControl("Channel")]
public UVChannel uvChannel
{
get { return m_OutputChannel; }

23
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Scene/AmbientNode.cs


[Title("Input", "Scene", "Ambient")]
public class AmbientNode : AbstractMaterialNode
{
const string kOutputSlotName = "Color";
const string kOutputSlot1Name = "Sky";
const string kOutputSlot2Name = "Equator";
const string kOutputSlot3Name = "Ground";
const string kOutputSlotName = "Color/Sky";
const string kOutputSlot1Name = "Equator";
const string kOutputSlot2Name = "Ground";
public const int OutputSlot3Id = 3;
public AmbientNode()
{

public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Vector4MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero));
AddSlot(new Vector4MaterialSlot(OutputSlot1Id, kOutputSlot1Name, kOutputSlot1Name, SlotType.Output, Vector4.zero));
AddSlot(new Vector4MaterialSlot(OutputSlot2Id, kOutputSlot2Name, kOutputSlot2Name, SlotType.Output, Vector4.zero));
AddSlot(new Vector4MaterialSlot(OutputSlot3Id, kOutputSlot3Name, kOutputSlot3Name, SlotType.Output, Vector4.zero));
RemoveSlotsNameNotMatching(new[] { OutputSlotId, OutputSlot1Id, OutputSlot2Id, OutputSlot3Id });
AddSlot(new ColorRGBMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero));
AddSlot(new ColorRGBMaterialSlot(OutputSlot1Id, kOutputSlot1Name, kOutputSlot1Name, SlotType.Output, Vector4.zero));
AddSlot(new ColorRGBMaterialSlot(OutputSlot2Id, kOutputSlot2Name, kOutputSlot2Name, SlotType.Output, Vector4.zero));
RemoveSlotsNameNotMatching(new[] { OutputSlotId, OutputSlot1Id, OutputSlot2Id });
}
public override string GetVariableNameForSlot(int slotId)

case OutputSlot1Id:
return "unity_AmbientSky";
return "unity_AmbientEquator";
return "unity_AmbientEquator";
case OutputSlot3Id:
return "UNITY_LIGHTMODEL_AMBIENT";
return "unity_AmbientSky";
}
}
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Scene/CameraNode.cs


const string kOutputSlot2Name = "Orthographic";
const string kOutputSlot3Name = "Near Plane";
const string kOutputSlot4Name = "Far Plane";
const string kOutputSlot5Name = "Sign";
const string kOutputSlot5Name = "Z Buffer Sign";
const string kOutputSlot6Name = "Width";
const string kOutputSlot7Name = "Height";

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Scene/FogNode.cs


public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
var colorValue = GetSlotValue(OutputSlotId, generationMode);
var densityValue = GetSlotValue(OutputSlot1Id, generationMode);
visitor.AddShaderChunk(string.Format("{0}(IN.{1}, {2}, {3});", GetFunctionName(), CoordinateSpace.Object.ToVariableName(InterpolatorType.Position), colorValue, densityValue), false);
visitor.AddShaderChunk(string.Format("{0}(IN.{1}, {2}, {3});", GetFunctionName(),
CoordinateSpace.Object.ToVariableName(InterpolatorType.Position),
GetVariableNameForSlot(OutputSlotId), GetVariableNameForSlot(OutputSlot1Id)), false);
}
public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode)

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Scene/ReflectionProbeNode.cs


@"
{
{precision}3 reflectVec = reflect(-ViewDir, Normal);
Out = DecodeHDR(UNITY_SAMPLE_TEXCUBE_LOD(unity_SpecCube0, reflectVec, LOD), unity_SpecCube0_HDR);
Out = DecodeHDREnvironment(SAMPLE_TEXTURECUBE_LOD(unity_SpecCube0, samplerunity_SpecCube0, reflectVec, LOD), unity_SpecCube0_HDR);
}
";
}

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


const string kOutputSlotGName = "G";
const string kOutputSlotBName = "B";
const string kOutputSlotAName = "A";
const string kTextureInputName = "Tex";
const string kTextureInputName = "Texture";
const string kUVInputName = "UV";
const string kSamplerInputName = "Sampler";

AddSlot(new Vector1MaterialSlot(OutputSlotBId, kOutputSlotBName, kOutputSlotBName, SlotType.Output, 0));
AddSlot(new Vector1MaterialSlot(OutputSlotAId, kOutputSlotAName, kOutputSlotAName, SlotType.Output, 0));
AddSlot(new Texture2DInputMaterialSlot(TextureInputId, kTextureInputName, kTextureInputName));
AddSlot(new UVMaterialSlot(UVInput, kUVInputName, kUVInputName, UVChannel.uv0));
AddSlot(new UVMaterialSlot(UVInput, kUVInputName, kUVInputName, UVChannel.UV0));
AddSlot(new SamplerStateMaterialSlot(SamplerInput, kSamplerInputName, kSamplerInputName, SlotType.Input));
RemoveSlotsNameNotMatching(new[] { OutputSlotRGBAId, OutputSlotRId, OutputSlotGId, OutputSlotBId, OutputSlotAId, TextureInputId, UVInput, SamplerInput });
}

36
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/MasterNode.cs


}
public abstract string GetShader(GenerationMode mode, string name, out List<PropertyCollector.TextureInfo> configuredTextures);
public static SurfaceMaterialOptions GetMaterialOptionsFromAlphaMode(AlphaMode alphaMode)
{
var materialOptions = new SurfaceMaterialOptions();
switch (alphaMode)
{
case AlphaMode.Opaque:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.Zero;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.On;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Geometry;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Opaque;
break;
case AlphaMode.AlphaBlend:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.SrcAlpha;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.OneMinusSrcAlpha;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
case AlphaMode.AdditiveBlend:
materialOptions.srcBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.dstBlend = SurfaceMaterialOptions.BlendMode.One;
materialOptions.cullMode = SurfaceMaterialOptions.CullMode.Back;
materialOptions.zTest = SurfaceMaterialOptions.ZTest.LEqual;
materialOptions.zWrite = SurfaceMaterialOptions.ZWrite.Off;
materialOptions.renderQueue = SurfaceMaterialOptions.RenderQueue.Transparent;
materialOptions.renderType = SurfaceMaterialOptions.RenderType.Transparent;
break;
}
return materialOptions;
}
}
}

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Advanced/LogNode.cs


}
static string Unity_Log(
[Slot(0, Binding.None)] DynamicDimensionVector In,
[Slot(0, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector In,
[Slot(1, Binding.None)] out DynamicDimensionVector Out)
{
return

}
static string Unity_Log2(
[Slot(0, Binding.None)] DynamicDimensionVector In,
[Slot(0, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector In,
[Slot(1, Binding.None)] out DynamicDimensionVector Out)
{
return

}
static string Unity_Log10(
[Slot(0, Binding.None)] DynamicDimensionVector In,
[Slot(0, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector In,
[Slot(1, Binding.None)] out DynamicDimensionVector Out)
{
return

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Advanced/ModuloNode.cs


}
static string Unity_Modulo(
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector A,
[Slot(1, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector B,
[Slot(2, Binding.None)] out DynamicDimensionVector Out)
{
return

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Advanced/PosterizeNode.cs


}
static string Unity_Posterize(
[Slot(0, Binding.None)] DynamicDimensionVector In,
[Slot(1, Binding.None)] DynamicDimensionVector Steps,
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector In,
[Slot(1, Binding.None, 4, 4, 4, 4)] DynamicDimensionVector Steps,
[Slot(2, Binding.None)] out DynamicDimensionVector Out)
{
return

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Advanced/ReciprocalNode.cs


}
static string Unity_Reciprocal(
[Slot(0, Binding.None)] DynamicDimensionVector In,
[Slot(0, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector In,
[Slot(1, Binding.None)] out DynamicDimensionVector Out)
{
return

}
static string Unity_Reciprocal_Fast(
[Slot(0, Binding.None)] DynamicDimensionVector In,
[Slot(0, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector In,
[Slot(1, Binding.None)] out DynamicDimensionVector Out)
{
return

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Advanced/ReciprocalSquareRootNode.cs


}
static string Unity_Rsqrt(
[Slot(0, Binding.None)] DynamicDimensionVector In,
[Slot(0, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector In,
[Slot(1, Binding.None)] out DynamicDimensionVector Out)
{
return

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Basic/DivideNode.cs


}
static string Unity_Divide(
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector A,
[Slot(1, Binding.None, 2, 2, 2, 2)] DynamicDimensionVector B,
[Slot(2, Binding.None)] out DynamicDimensionVector Out)
{
return @"

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Basic/MultiplyNode.cs


}
static string Unity_Multiply(
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector A,
[Slot(1, Binding.None, 2, 2, 2, 2)] DynamicDimensionVector B,
[Slot(2, Binding.None)] out DynamicDimensionVector Out)
{
return

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Basic/PowerNode.cs


}
static string Unity_Power(
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector A,
[Slot(1, Binding.None, 2, 2, 2, 2)] DynamicDimensionVector B,
[Slot(2, Binding.None)] out DynamicDimensionVector Out)
{
return

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Basic/SubtractNode.cs


}
static string Unity_Subtract(
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector A,
[Slot(1, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector B,
[Slot(2, Binding.None)] out DynamicDimensionVector Out)
{
return

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Interpolation/InverseLerpNode.cs


}
static string Unity_InverseLerp(
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(2, Binding.None)] DynamicDimensionVector T,
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector A,
[Slot(1, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector B,
[Slot(2, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector T,
[Slot(3, Binding.None)] out DynamicDimensionVector Out)
{
return

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Interpolation/LerpNode.cs


}
static string Unity_Lerp(
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(2, Binding.None)] DynamicDimensionVector T,
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector A,
[Slot(1, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector B,
[Slot(2, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector T,
[Slot(3, Binding.None)] out DynamicDimensionVector Out)
{
return

6
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Interpolation/SmoothstepNode.cs


}
static string Unity_Smoothstep(
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(2, Binding.None)] DynamicDimensionVector T,
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector A,
[Slot(1, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector B,
[Slot(2, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector T,
[Slot(3, Binding.None)] out DynamicDimensionVector Out)
{
return

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Range/MinimumNode.cs


}
static string Unity_Minimum(
[Slot(0, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector A,
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector A,
[Slot(1, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector B,
[Slot(2, Binding.None)] out DynamicDimensionVector Out)
{

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Range/OneMinusNode.cs


}
static string Unity_OneMinus(
[Slot(0, Binding.None)] DynamicDimensionVector In,
[Slot(0, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector In,
[Slot(1, Binding.None)] out DynamicDimensionVector Out)
{
return

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Range/RemapNode.cs


}
static string Unity_Remap(
[Slot(0, Binding.None)] DynamicDimensionVector In,
[Slot(1, Binding.None, 0, 1, 0, 0)] Vector2 InMinMax,
[Slot(0, Binding.None, -1, -1, -1, -1)] DynamicDimensionVector In,
[Slot(1, Binding.None, -1, 1, 0, 0)] Vector2 InMinMax,
[Slot(2, Binding.None, 0, 1, 0, 0)] Vector2 OutMinMax,
[Slot(3, Binding.None)] out DynamicDimensionVector Out)
{

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Round/StepNode.cs


}
static string Unity_Step(
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector A,
[Slot(1, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector B,
[Slot(2, Binding.None)] out DynamicDimensionVector Out)
{
return

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Trigonometry/ArccosineNode.cs


}
static string Unity_Arccosine(
[Slot(0, Binding.None)] DynamicDimensionVector In,
[Slot(0, Binding.None, 1, 1, 1, 1)] DynamicDimensionVector In,
[Slot(1, Binding.None)] out DynamicDimensionVector Out)
{
return

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Vector/CrossProductNode.cs


}
static string Unity_CrossProduct(
[Slot(0, Binding.None)] Vector3 A,
[Slot(1, Binding.None)] Vector3 B,
[Slot(0, Binding.None, 0, 0, 0, 0)] Vector3 A,
[Slot(1, Binding.None, 0, 1, 0, 0)] Vector3 B,
[Slot(2, Binding.None)] out Vector3 Out)
{
Out = Vector3.zero;

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Vector/DotProductNode.cs


}
static string Unity_DotProduct(
[Slot(0, Binding.None)] Vector3 A,
[Slot(1, Binding.None)] Vector3 B,
[Slot(0, Binding.None, 0, 0, 0, 0)] Vector3 A,
[Slot(1, Binding.None, 0, 1, 0, 0)] Vector3 B,
[Slot(2, Binding.None)] out Vector1 Out)
{
return

9
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Vector/FresnelEffectNode.cs


name = "Fresnel Effect";
}
public override PreviewMode previewMode
{
get { return PreviewMode.Preview3D; }
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_FresnelEffect", BindingFlags.Static | BindingFlags.NonPublic);

[Slot(0, Binding.None)] Vector3 Normal,
[Slot(1, Binding.None)] Vector3 ViewDir,
[Slot(0, Binding.WorldSpaceNormal)] Vector3 Normal,
[Slot(1, Binding.WorldSpaceViewDirection)] Vector3 ViewDir,
[Slot(2, Binding.None, 1, 1, 1, 1)] Vector1 Power,
[Slot(3, Binding.None)] out Vector1 Out)
{

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Vector/ProjectionNode.cs


}
static string Unity_Projection(
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector A,
[Slot(1, Binding.None, 0, 1, 0, 0)] DynamicDimensionVector B,
[Slot(2, Binding.None)] out DynamicDimensionVector Out)
{
return

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Vector/ReflectionNode.cs


}
static string Unity_Reflection(
[Slot(0, Binding.None)] DynamicDimensionVector In,
[Slot(1, Binding.None)] DynamicDimensionVector Normal,
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector In,
[Slot(1, Binding.None, 0, 1, 0, 0)] DynamicDimensionVector Normal,
[Slot(2, Binding.None)] out DynamicDimensionVector Out)
{

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Vector/RejectionNode.cs


}
static string Unity_Rejection(
[Slot(0, Binding.None)] DynamicDimensionVector A,
[Slot(1, Binding.None)] DynamicDimensionVector B,
[Slot(0, Binding.None, 0, 0, 0, 0)] DynamicDimensionVector A,
[Slot(1, Binding.None, 0, 1, 0, 0)] DynamicDimensionVector B,
[Slot(2, Binding.None)] out DynamicDimensionVector Out)
{
return

162
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/UV/FlipbookNode.cs


using System.Reflection;
using UnityEngine;
using System;
using System.Collections.Generic;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
public class FlipbookNode : CodeFunctionNode
public class FlipbookNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IMayRequireMeshUV
UpdateNodeAfterDeserialization();
protected override MethodInfo GetFunctionToConvert()
const int UVSlotId = 0;
const int WidthSlotId = 1;
const int HeightSlotId = 2;
const int TileSlotId = 3;
const int OutputSlotId = 4;
const string kUVSlotName = "UV";
const string kWidthSlotName = "Width";
const string kHeightSlotName = "Height";
const string kTileSlotName = "Tile";
const string kOutputSlotName = "Out";
public override bool hasPreview
return GetType().GetMethod("Unity_Flipbook", BindingFlags.Static | BindingFlags.NonPublic);
get { return true; }
static string Unity_Flipbook(
[Slot(0, Binding.MeshUV0)] Vector2 UV,
[Slot(1, Binding.None, 1, 1, 1, 1)] Vector1 Width,
[Slot(2, Binding.None, 1, 1, 1, 1)] Vector1 Height,
[Slot(3, Binding.None)] Vector1 Tile,
[Slot(4, Binding.None)] out Vector2 Out)
string GetFunctionName()
{
return "Unity_Flipbook_" + precision;
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new UVMaterialSlot(UVSlotId, kUVSlotName, kUVSlotName, UVChannel.UV0));
AddSlot(new Vector1MaterialSlot(WidthSlotId, kWidthSlotName, kWidthSlotName, SlotType.Input, 1));
AddSlot(new Vector1MaterialSlot(HeightSlotId, kHeightSlotName, kHeightSlotName, SlotType.Input, 1));
AddSlot(new Vector1MaterialSlot(TileSlotId, kTileSlotName, kTileSlotName, SlotType.Input, 0));
AddSlot(new Vector2MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector2.zero));
RemoveSlotsNameNotMatching(new[] { UVSlotId, WidthSlotId, HeightSlotId, TileSlotId, OutputSlotId });
}
[SerializeField]
private bool m_InvertX = false;
[ToggleControl("Invert X")]
public Toggle invertX
Out = Vector2.zero;
get { return new Toggle(m_InvertX); }
set
{
if (m_InvertX == value.isOn)
return;
m_InvertX = value.isOn;
Dirty(ModificationScope.Node);
}
}
return
@"
{
{precision}2 tileCount = {precision}2(1.0, 1.0) / {precision}2(Width, Height);
{precision} tileY = floor(Tile * tileCount.x);
{precision} tileX = Tile - Width * tileY;
Out = (UV + {precision}2(tileX, tileY)) * tileCount;
}
";
[SerializeField]
private bool m_InvertY = true;
[ToggleControl("Invert Y")]
public Toggle invertY
{
get { return new Toggle(m_InvertY); }
set
{
if (m_InvertY == value.isOn)
return;
m_InvertY = value.isOn;
Dirty(ModificationScope.Node);
}
}
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
var sb = new ShaderStringBuilder();
var uvValue = GetSlotValue(UVSlotId, generationMode);
var widthValue = GetSlotValue(WidthSlotId, generationMode);
var heightValue = GetSlotValue(HeightSlotId, generationMode);
var tileValue = GetSlotValue(TileSlotId, generationMode);
var outputValue = GetSlotValue(OutputSlotId, generationMode);
sb.AppendLine("{0} {1};", NodeUtils.ConvertConcreteSlotValueTypeToString(precision, FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType), GetVariableNameForSlot(OutputSlotId));
if (!generationMode.IsPreview())
{
sb.AppendLine("{0}2 _{1}_Invert = {0}2 ({2}, {3});", precision, GetVariableNameForNode(), invertX.isOn ? 1 : 0, invertY.isOn ? 1 : 0);
}
sb.AppendLine("{0}({1}, {2}, {3}, {4}, _{5}_Invert, {6});", GetFunctionName(), uvValue, widthValue, heightValue, tileValue, GetVariableNameForNode(), outputValue);
visitor.AddShaderChunk(sb.ToString(), false);
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
{
base.CollectPreviewMaterialProperties(properties);
properties.Add(new PreviewProperty(PropertyType.Vector2)
{
name = string.Format("_{0}_Invert", GetVariableNameForNode()),
vector4Value = new Vector2(invertX.isOn ? 1 : 0, invertY.isOn ? 1 : 0)
});
}
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
{
if (!generationMode.IsPreview())
return;
base.CollectShaderProperties(properties, generationMode);
properties.AddShaderProperty(new Vector2ShaderProperty()
{
overrideReferenceName = string.Format("_{0}_Invert", GetVariableNameForNode()),
generatePropertyBlock = false
});
}
public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode)
{
registry.ProvideFunction(GetFunctionName(), s =>
{
s.AppendLine("void {0} ({1} UV, {2} Width, {3} Height, {4} Tile, {5}2 Invert, out {6} Out)",
GetFunctionName(),
FindInputSlot<MaterialSlot>(UVSlotId).concreteValueType.ToString(precision),
FindInputSlot<MaterialSlot>(WidthSlotId).concreteValueType.ToString(precision),
FindInputSlot<MaterialSlot>(HeightSlotId).concreteValueType.ToString(precision),
FindInputSlot<MaterialSlot>(TileSlotId).concreteValueType.ToString(precision),
precision,
FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType.ToString(precision));
using (s.BlockScope())
{
s.AppendLine("Tile = fmod(Tile, Width*Height);");
s.AppendLine("{0}2 tileCount = {0}2(1.0, 1.0) / {0}2(Width, Height);", precision);
s.AppendLine("{0} tileY = abs(Invert.y * Height - (floor(Tile * tileCount.x) + Invert.y * 1));", precision);
s.AppendLine("{0} tileX = abs(Invert.x * Width - ((Tile - Width * floor(Tile * tileCount.x)) + Invert.x * 1));", precision);
s.AppendLine("Out = (UV + {0}2(tileX, tileY)) * tileCount;", precision);
}
});
}
public bool RequiresMeshUV(UVChannel channel)
{
s_TempSlots.Clear();
GetInputSlots(s_TempSlots);
foreach (var slot in s_TempSlots)
{
if (slot.RequiresMeshUV(channel))
return true;
}
return false;
}
}
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/UV/TwirlNode.cs


static string Unity_Twirl(
[Slot(0, Binding.MeshUV0)] Vector2 UV,
[Slot(1, Binding.None, 0.5f, 0.5f, 0.5f, 0.5f)] Vector2 Center,
[Slot(2, Binding.None, 0f, 0f, 0f, 0f)] Vector1 Strength,
[Slot(2, Binding.None, 10f, 0f, 0f, 0f)] Vector1 Strength,
[Slot(3, Binding.None)] Vector2 Offset,
[Slot(4, Binding.None)] out Vector2 Out)
{

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


using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Graphing;

{
static class GraphUtil
{
internal static void GenerateApplicationVertexInputs(ShaderGraphRequirements graphRequiements, ShaderGenerator vertexInputs, int vertexInputStartIndex, int maxVertexInputs)
internal static string ConvertCamelCase(string text, bool preserveAcronyms)
int vertexInputIndex = vertexInputStartIndex;
if (string.IsNullOrEmpty(text))
return string.Empty;
StringBuilder newText = new StringBuilder(text.Length * 2);
newText.Append(text[0]);
for (int i = 1; i < text.Length; i++)
{
if (char.IsUpper(text[i]))
if ((text[i - 1] != ' ' && !char.IsUpper(text[i - 1])) ||
(preserveAcronyms && char.IsUpper(text[i - 1]) &&
i < text.Length - 1 && !char.IsUpper(text[i + 1])))
newText.Append(' ');
newText.Append(text[i]);
}
return newText.ToString();
}
internal static void GenerateApplicationVertexInputs(ShaderGraphRequirements graphRequiements, ShaderGenerator vertexInputs)
{
vertexInputs.AddShaderChunk("struct GraphVertexInput", false);
vertexInputs.AddShaderChunk("{", false);
vertexInputs.Indent();

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

}
var requirements = ShaderGraphRequirements.FromNodes(activeNodeList);
GenerateApplicationVertexInputs(requirements, vertexInputs, 0, 8);
GenerateApplicationVertexInputs(requirements, vertexInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresNormal, InterpolatorType.Normal, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresTangent, InterpolatorType.Tangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresBitangent, InterpolatorType.BiTangent, surfaceInputs);

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 ""CoreRP/ShaderLibrary/UnityInstancing.hlsl""");
finalBuilder.AppendLine(@"#include ""CoreRP/ShaderLibrary/EntityLighting.hlsl""");
finalBuilder.AppendLine(@"#include ""ShaderGraphLibrary/Functions.hlsl""");
finalBuilder.AppendLines(shaderProperties.GetPropertiesDeclaration(0));
finalBuilder.AppendLines(surfaceInputs.GetShaderString(0));

var foundEdges = graph.GetEdges(input.slotReference).ToArray();
if (foundEdges.Any())
{
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), masterNode.GetSlotValue(input.id, mode)), true);
}
else
{

else if (masterNode.hasPreview)
{
foreach (var slot in masterNode.GetOutputSlots<MaterialSlot>())
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.GetSlotValue(slot.id, mode)), true);
}
}

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


private const string kErrorString = @"ERROR!";
public static string AdaptNodeOutput(AbstractMaterialNode node, int outputSlotId, ConcreteSlotValueType convertToType, bool textureSampleUVHack = false)
public static string AdaptNodeOutput(AbstractMaterialNode node, int outputSlotId, ConcreteSlotValueType convertToType)
{
var outputSlot = node.FindOutputSlot<MaterialSlot>(outputSlotId);

if (combinedRequierments.requiresScreenPosition)
{
interpolators.AddShaderChunk(string.Format("float4 {0} : TEXCOORD{1};", ShaderGeneratorNames.ScreenPosition, interpolatorIndex), false);
vertexShader.AddShaderChunk(string.Format("o.{0} = ComputeScreenPos(UnityObjectToClipPos(v.vertex));", ShaderGeneratorNames.ScreenPosition), false);
vertexShader.AddShaderChunk(string.Format("o.{0} = ComputeScreenPos(mul(GetWorldToHClipMatrix(), mul(GetObjectToWorldMatrix(), v.vertex)), _ProjectionParams.x);", ShaderGeneratorNames.ScreenPosition), false);
pixelShader.AddShaderChunk(string.Format("float4 {0} = IN.{0};", ShaderGeneratorNames.ScreenPosition), false);
interpolatorIndex++;
}

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


namespace UnityEditor.ShaderGraph {
public enum UVChannel
{
uv0 = 0,
uv1 = 1,
uv2 = 2,
uv3 = 3,
UV0 = 0,
UV1 = 1,
UV2 = 2,
UV3 = 3,
}
}

90
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ChannelMixerControl.cs


Slider m_GreenSlider;
Slider m_BlueSlider;
FloatField m_RedInputField;
FloatField m_GreenInputField;
FloatField m_BlueInputField;
float m_Minimum;
float m_Maximum;
bool m_Initialized;

if (!string.IsNullOrEmpty(label))
Add(new Label(label));
var buttonPanel = new VisualElement { name = "buttonPanel" };
Add(outputButtonRed);
outputButtonRed.Add(new Label("R"));
buttonPanel.Add(outputButtonRed);
Add(outputButtonGreen);
outputButtonGreen.Add(new Label("G"));
buttonPanel.Add(outputButtonGreen);
Add(outputButtonBlue);
outputButtonBlue.Add(new Label("B"));
buttonPanel.Add(outputButtonBlue);
Add(new Label("Red"));
Add(buttonPanel);
var redSliderPanel = new VisualElement { name = "sliderPanel" };
redSliderPanel.Add(new Label("R"));
Add(m_RedSlider);
redSliderPanel.Add(m_RedSlider);
m_RedInputField = new FloatField { value = m_ChannelMixer.outRed.x };
m_RedInputField.RegisterCallback<ChangeEvent<double>, int>(OnChangeInputField, 0);
redSliderPanel.Add(m_RedInputField);
Add(redSliderPanel);
Add(new Label("Green"));
var greenSliderPanel = new VisualElement { name = "sliderPanel" };
greenSliderPanel.Add(new Label("G"));
Add(m_GreenSlider);
greenSliderPanel.Add(m_GreenSlider);
m_GreenInputField = new FloatField { value = m_ChannelMixer.outRed.y };
m_GreenInputField.RegisterCallback<ChangeEvent<double>, int>(OnChangeInputField, 1);
greenSliderPanel.Add(m_GreenInputField);
Add(greenSliderPanel);
Add(new Label("Blue"));
var blueSliderPanel = new VisualElement { name = "sliderPanel" };
blueSliderPanel.Add(new Label("B"));
Add(m_BlueSlider);
blueSliderPanel.Add(m_BlueSlider);
m_BlueInputField = new FloatField { value = m_ChannelMixer.outRed.z };
m_BlueInputField.RegisterCallback<ChangeEvent<double>, int>(OnChangeInputField, 2);
blueSliderPanel.Add(m_BlueInputField);
Add(blueSliderPanel);
m_Initialized = true;
ResetSliders();

m_ChannelMixer.outRed[inChannel] = value;
break;
}
switch(inChannel)
{
case 1:
m_GreenInputField.value = value;
break;
case 2:
m_BlueInputField.value = value;
break;
default:
m_RedInputField.value = value;
break;
}
}
void OnChangeInputField(ChangeEvent<double> evt, int inChannel)
{
if (!m_Initialized)
return;
var value = Mathf.Max(Mathf.Min((float)evt.newValue, m_Maximum), m_Minimum);
m_Node.owner.owner.RegisterCompleteObjectUndo("Input Field Change");
switch (m_OutChannel)
{
case 1:
m_ChannelMixer.outGreen[inChannel] = value;
break;
case 2:
m_ChannelMixer.outBlue[inChannel] = value;
break;
default:
m_ChannelMixer.outRed[inChannel] = value;
break;
}
switch(inChannel)
{
case 1:
m_GreenSlider.value = value;
break;
case 2:
m_BlueSlider.value = value;
break;
default:
m_RedSlider.value = value;
break;
}
m_PropertyInfo.SetValue(m_Node, m_ChannelMixer, null);
Dirty(ChangeType.Repaint);
}
void OnClickButton(int outChannel)

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ColorControl.cs


switch(colorMode)
{
case ColorMode.HDR:
colorField = new ColorField { value = (Color)m_PropertyInfo.GetValue(m_Node, null), hdr = true };
colorField = new ColorField { value = (Color)m_PropertyInfo.GetValue(m_Node, null), hdr = true, showEyeDropper = false };
colorField = new ColorField { value = (Color)m_PropertyInfo.GetValue(m_Node, null) };
colorField = new ColorField { value = (Color)m_PropertyInfo.GetValue(m_Node, null), showEyeDropper = false };
break;
}
colorField.OnValueChanged(OnChange);

51
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ToggleControl.cs


using System;
using System.Reflection;
using UnityEditor.Graphing;
using UnityEditor.Experimental.UIElements;
using UnityEditor.Graphing;
using UnityEngine.Experimental.UIElements.StyleSheets;
using UnityEditor.ShaderGraph;
namespace UnityEditor.ShaderGraph.Drawing.Controls
{

public class ToggleControlView : VisualElement, INodeModificationListener
{
GUIContent m_Label;
IMGUIContainer m_Container;
UnityEngine.Experimental.UIElements.Toggle m_Toggle;
public ToggleControlView(string label, AbstractMaterialNode node, PropertyInfo propertyInfo)
{

throw new ArgumentException("Property must be a Toggle.", "propertyInfo");
m_Label = new GUIContent(label ?? ObjectNames.NicifyVariableName(propertyInfo.Name));
m_Container = new IMGUIContainer(OnGUIHandler);
Add(m_Container);
label = label ?? ObjectNames.NicifyVariableName(propertyInfo.Name);
var value = (Toggle)m_PropertyInfo.GetValue(m_Node, null);
var panel = new VisualElement { name = "togglePanel" };
if (!string.IsNullOrEmpty(label))
panel.Add(new Label(label));
Action changedToggle = () => { OnChangeToggle(); };
m_Toggle = new UnityEngine.Experimental.UIElements.Toggle(changedToggle);
m_Toggle.SetEnabled(value.isEnabled);
m_Toggle.on = value.isOn;
panel.Add(m_Toggle);
Add(panel);
var value = (Toggle)m_PropertyInfo.GetValue(m_Node, null);
m_Toggle.SetEnabled(value.isEnabled);
m_Container.Dirty(ChangeType.Repaint);
{
Dirty(ChangeType.Repaint);
}
void OnGUIHandler()
void OnChangeToggle()
m_Node.owner.owner.RegisterCompleteObjectUndo("Toggle Change");
using (var changeCheckScope = new EditorGUI.ChangeCheckScope())
{
m_Container.SetEnabled(value.isEnabled);
bool isOn = EditorGUILayout.Toggle(m_Label, value.isOn);
value = new Toggle(isOn, value.isEnabled);
if (changeCheckScope.changed)
{
m_Node.owner.owner.RegisterCompleteObjectUndo("Change " + m_Node.name);
m_PropertyInfo.SetValue(m_Node, value, null);
}
}
value.isOn = !value.isOn;
m_PropertyInfo.SetValue(m_Node, value, null);
Dirty(ChangeType.Repaint);
}
}
}

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/EdgeConnectorListener.cs


namespace UnityEditor.ShaderGraph.Drawing
{
public class EdgeConnectorListener : IEdgeConnectorListener
class EdgeConnectorListener : IEdgeConnectorListener
{
readonly AbstractMaterialGraph m_Graph;
readonly SearchWindowProvider m_SearchWindowProvider;

public void OnDropOutsidePort(Edge edge, Vector2 position)
{
var draggedPort = (edge.output != null ? edge.output.edgeConnector.edgeDragHelper.draggedPort : null) ?? (edge.input != null ? edge.input.edgeConnector.edgeDragHelper.draggedPort : null);
m_SearchWindowProvider.connectedPort = draggedPort;
m_SearchWindowProvider.connectedPort = (ShaderPort) draggedPort;
var leftSlot = edge.output.userData as ISlot;
var rightSlot = edge.input.userData as ISlot;
var leftSlot = edge.output.GetSlot();
var rightSlot = edge.input.GetSlot();
if (leftSlot != null && rightSlot != null)
{
m_Graph.owner.RegisterCompleteObjectUndo("Connect Edge");

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


[NonSerialized]
bool m_HasError;
[NonSerialized]
public bool forceRedrawPreviews = false;
GraphEditorView m_GraphEditorView;
GraphEditorView graphEditorView

m_GraphEditorView.RemoveFromHierarchy();
m_GraphEditorView.Dispose();
}
m_GraphEditorView = value;
if (m_GraphEditorView != null)
{

graphEditorView = new GraphEditorView(this, materialGraph, asset.name) { persistenceKey = selectedGuid };
}
if (forceRedrawPreviews)
{
// Redraw all previews
foreach (INode node in m_GraphObject.graph.GetNodes<INode>())
node.Dirty(ModificationScope.Node);
forceRedrawPreviews = false;
}
graphEditorView.HandleGraphChanges();
graphObject.graph.ClearChanges();
}

Undo.ClearUndo(graphObject);
DestroyImmediate(graphObject);
}
graphEditorView = null;
}

var inputSlotRef = new SlotReference(remappedInputNodeGuid, inputSlot.slotId);
subGraph.Connect(outputSlotRef, inputSlotRef);
}
// one edge needs to go to outside world
else if (outputSlotExistsInSubgraph)
{

var graph = graphObject.graph as IShaderGraph;
if (graph == null)
return;
List<PropertyCollector.TextureInfo> configuredTextures;
graph.GetShader(Path.GetFileNameWithoutExtension(path), GenerationMode.ForReals, out configuredTextures);
var shaderImporter = AssetImporter.GetAtPath(path) as ShaderGraphImporter;
if (shaderImporter == null)

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


// Render 2D previews
m_SceneResources.camera.transform.position = -Vector3.forward * 2;
m_SceneResources.camera.transform.rotation = Quaternion.identity;
m_SceneResources.camera.orthographicSize = 1;
m_SceneResources.camera.orthographicSize = 0.5f;
m_SceneResources.camera.orthographic = true;
foreach (var renderData in m_RenderList2D)

m_PreviewPropertyBlock.SetFloat(m_OutputIdName, renderData.shaderData.node.tempId.index);
if (m_PreviewMaterial.shader != renderData.shaderData.shader)
m_PreviewMaterial.shader = renderData.shaderData.shader;
m_SceneResources.camera.targetTexture = renderData.renderTexture;
RenderTexture.active = renderData.renderTexture;
//Temp workaround for alpha previews...
var temp = RenderTexture.GetTemporary(renderData.renderTexture.descriptor);
RenderTexture.active = temp;
Graphics.Blit(Texture2D.whiteTexture, renderData.renderTexture, m_SceneResources.checkerboardMaterial);
Graphics.Blit(Texture2D.whiteTexture, temp, m_SceneResources.checkerboardMaterial);
m_SceneResources.camera.targetTexture = temp;
Graphics.DrawMesh(mesh, transform, m_PreviewMaterial, 1, m_SceneResources.camera, 0, m_PreviewPropertyBlock, ShadowCastingMode.Off, false, null, false);
var previousUseSRP = Unsupported.useScriptableRenderPipeline;

Graphics.Blit(temp, renderData.renderTexture, m_SceneResources.blitNoAlphaMaterial);
RenderTexture.ReleaseTemporary(temp);
RenderTexture.active = previousRenderTexure;
renderData.texture = renderData.renderTexture;
}

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/SearchWindowProvider.cs


namespace UnityEditor.ShaderGraph.Drawing
{
public class SearchWindowProvider : ScriptableObject, ISearchWindowProvider
class SearchWindowProvider : ScriptableObject, ISearchWindowProvider
public Port connectedPort { get; set; }
public ShaderPort connectedPort { get; set; }
public bool nodeNeedsRepositioning { get; set; }
public SlotReference targetSlotReference { get; private set; }
public Vector2 targetPosition { get; private set; }

int GetFirstCompatibleSlotId(AbstractMaterialNode node)
{
var connectedSlot = (MaterialSlot)connectedPort.userData;
var connectedSlot = connectedPort.slot;
m_Slots.Clear();
node.GetSlots(m_Slots);
foreach (var slot in m_Slots)

if (connectedPort != null)
{
var connectedSlot = (MaterialSlot)connectedPort.userData;
var connectedSlot = connectedPort.slot;
var connectedSlotReference = connectedSlot.owner.GetSlotReference(connectedSlot.id);
var compatibleSlotReference = node.GetSlotReference(nodeEntry.compatibleSlotId);

35
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/GraphEditorView.cs


{
MaterialGraphView m_GraphView;
GraphInspectorView m_GraphInspectorView;
private EditorWindow m_EditorWindow;
AbstractMaterialGraph m_Graph;
PreviewManager m_PreviewManager;

{
m_Graph = graph;
AddStyleSheetPath("Styles/MaterialGraph");
m_EditorWindow = editorWindow;
previewManager = new PreviewManager(graph);
var content = new VisualElement { name = "content" };

m_GraphInspectorView.AddManipulator(new Draggable(OnMouseDrag, true));
m_GraphView.RegisterCallback<PostLayoutEvent>(OnPostLayout);
m_GraphInspectorView.RegisterCallback<PostLayoutEvent>(OnPostLayout);
m_GraphView.RegisterCallback<KeyDownEvent>(OnSpaceDown);
m_GraphView.Add(m_GraphInspectorView);

m_GraphInspectorView.layout = inspectorViewRect;
}
void OnSpaceDown(KeyDownEvent evt)
{
if( evt.keyCode == KeyCode.Space)
{
if (graphView.nodeCreationRequest == null)
return;
Vector2 referencePosition;
referencePosition = evt.imguiEvent.mousePosition;
Vector2 screenPoint = m_EditorWindow.position.position + referencePosition;
graphView.nodeCreationRequest(new NodeCreationContext() { screenMousePosition = screenPoint });
}
}
void OnMouseDrag(Vector2 mouseDelta)
{
Vector2 normalizedDelta = mouseDelta / 2f;

{
foreach (var edge in graphViewChange.edgesToCreate)
{
var leftSlot = edge.output.userData as ISlot;
var rightSlot = edge.input.userData as ISlot;
var leftSlot = edge.output.GetSlot();
var rightSlot = edge.input.GetSlot();
if (leftSlot != null && rightSlot != null)
{
m_Graph.owner.RegisterCompleteObjectUndo("Connect Edge");

var port = element as ShaderPort;
if (port == null)
continue;
var slot = (MaterialSlot)port.userData;
if (slot.slotReference.Equals(m_SearchWindowProvider.targetSlotReference))
if (port.slot.slotReference.Equals(m_SearchWindowProvider.targetSlotReference))
{
port.RegisterCallback<PostLayoutEvent>(RepositionNode);
return;

var sourceNodeView = m_GraphView.nodes.ToList().OfType<MaterialNodeView>().FirstOrDefault(x => x.node == sourceNode);
if (sourceNodeView != null)
{
var sourceAnchor = sourceNodeView.outputContainer.Children().OfType<Port>().FirstOrDefault(x => x.userData is ISlot && (x.userData as ISlot).Equals(sourceSlot));
var sourceAnchor = sourceNodeView.outputContainer.Children().OfType<ShaderPort>().FirstOrDefault(x => x.slot.Equals(sourceSlot));
var targetAnchor = targetNodeView.inputContainer.Children().OfType<Port>().FirstOrDefault(x => x.userData is ISlot && (x.userData as ISlot).Equals(targetSlot));
var targetAnchor = targetNodeView.inputContainer.Children().OfType<ShaderPort>().FirstOrDefault(x => x.slot.Equals(targetSlot));
var edgeView = new Edge
{

{
foreach (var edgeView in anchorView.connections.OfType<Edge>())
{
var targetSlot = (MaterialSlot)edgeView.input.userData;
var targetSlot = edgeView.input.GetSlot();
if (targetSlot.valueType == SlotValueType.Dynamic)
{
var connectedNodeView = edgeView.input.node as MaterialNodeView;

}
foreach (var anchorView in nodeView.inputContainer.Children().OfType<Port>())
{
var targetSlot = (MaterialSlot)anchorView.userData;
var targetSlot = anchorView.GetSlot();
if (targetSlot.valueType != SlotValueType.Dynamic)
continue;
foreach (var edgeView in anchorView.connections.OfType<Edge>())

4
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/MaterialGraphView.cs


public override List<Port> GetCompatiblePorts(Port startAnchor, NodeAdapter nodeAdapter)
{
var compatibleAnchors = new List<Port>();
var startSlot = startAnchor.userData as MaterialSlot;
var startSlot = startAnchor.GetSlot();
if (startSlot == null)
return compatibleAnchors;

foreach (var candidateAnchor in ports.ToList())
{
var candidateSlot = candidateAnchor.userData as MaterialSlot;
var candidateSlot = candidateAnchor.GetSlot();
if (!startSlot.IsCompatibleWith(candidateSlot))
continue;

101
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/MaterialNodeView.cs


name = "controls"
};
extensionContainer.Add(m_ControlsContainer);
m_ControlsDivider = new VisualElement {name = "divider"};
m_ControlsDivider = new VisualElement { name = "divider" };
m_ControlsDivider.AddToClassList("horizontal");
if (node.hasPreview)

m_PreviewRenderData.onPreviewChanged += UpdatePreviewTexture;
UpdatePreviewTexture();
var collapsePreviewButton = new VisualElement { name = "collapse"};
var collapsePreviewButton = new VisualElement { name = "collapse" };
{
node.owner.owner.RegisterCompleteObjectUndo("Collapse Preview");
UpdatePreviewExpandedState(false);
}));
{
node.owner.owner.RegisterCompleteObjectUndo("Collapse Preview");
UpdatePreviewExpandedState(false);
}));
var expandPreviewButton = new VisualElement { name = "expand"};
expandPreviewButton.Add(new VisualElement { name = "icon"});
var expandPreviewButton = new VisualElement { name = "expand" };
expandPreviewButton.Add(new VisualElement { name = "icon" });
{
node.owner.owner.RegisterCompleteObjectUndo("Expand Preview");
UpdatePreviewExpandedState(true);
}));
{
node.owner.owner.RegisterCompleteObjectUndo("Expand Preview");
UpdatePreviewExpandedState(true);
}));
m_PreviewContainer.Add(expandPreviewButton);
}

m_ControlViews = new List<VisualElement>();
foreach (var propertyInfo in node.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
foreach (IControlAttribute attribute in propertyInfo.GetCustomAttributes(typeof(IControlAttribute), false))
m_ControlViews.Add(attribute.InstantiateControl(node, propertyInfo));
foreach (IControlAttribute attribute in propertyInfo.GetCustomAttributes(typeof(IControlAttribute), false))
m_ControlViews.Add(attribute.InstantiateControl(node, propertyInfo));
m_Attachers = new List<Attacher>(node.GetInputSlots<MaterialSlot>().Count());
AddSlots(node.GetSlots<MaterialSlot>());

UpdatePreviewExpandedState(node.previewExpanded);
base.expanded = node.drawState.expanded;
var anchorsToRemove = inputContainer.Children().ToList();
foreach (var anchorElement in anchorsToRemove)
var inputPorts = inputContainer.Children().OfType<ShaderPort>().ToList();
foreach (var port in inputPorts)
inputContainer.Remove(anchorElement);
var attacher = m_Attachers.FirstOrDefault(a => a.target == anchorElement);
if (attacher != null)
var currentSlot = port.slot;
var newSlot = slots.FirstOrDefault(s => s.id == currentSlot.id);
if (newSlot == null)
{
// Slot doesn't exist anymore, remove it
inputContainer.Remove(port);
// We also need to remove the attacher along with the element it's attaching
var attacher = m_Attachers.FirstOrDefault(a => a.target == port);
if (attacher != null)
{
attacher.Detach();
attacher.element.parent.Remove(attacher.element);
m_Attachers.Remove(attacher);
}
}
else
attacher.Detach();
attacher.element.parent.Remove(attacher.element);
m_Attachers.Remove(attacher);
port.slot = newSlot;
slots.Remove(newSlot);
anchorsToRemove = outputContainer.Children().ToList();
foreach (var ve in anchorsToRemove)
outputContainer.Remove(ve);
foreach (var port in inputContainer.Union(outputContainer).OfType<Port>())
var outputPorts = outputContainer.Children().OfType<ShaderPort>().ToList();
foreach (var port in outputPorts)
var slot = (MaterialSlot)port.userData;
port.portName = slot.displayName;
var currentSlot = port.slot;
var newSlot = slots.FirstOrDefault(s => s.id == currentSlot.id);
if (newSlot == null)
{
outputContainer.Remove(port);
}
else
{
port.slot = newSlot;
slots.Remove(newSlot);
}
slots.Clear();
slots.AddRange(node.GetSlots<MaterialSlot>());
inputContainer.Sort((x, y) => slots.IndexOf(x.userData as MaterialSlot) - slots.IndexOf(y.userData as MaterialSlot));
inputContainer.Sort((x, y) => slots.IndexOf(((ShaderPort)x).slot) - slots.IndexOf(((ShaderPort)y).slot));
outputContainer.Sort((x, y) => slots.IndexOf(x.userData as MaterialSlot) - slots.IndexOf(y.userData as MaterialSlot));
outputContainer.Sort((x, y) => slots.IndexOf(((ShaderPort)x).slot) - slots.IndexOf(((ShaderPort)y).slot));
}
UpdateControls();

if (slot.hidden)
continue;
var port = ShaderPort.Create(Orientation.Horizontal, slot.isInputSlot ? Direction.Input : Direction.Output, null, m_ConnectorListener);
port.portName = slot.displayName;
port.userData = slot;
port.visualClass = slot.concreteValueType.ToClassName();
var port = ShaderPort.Create(slot, m_ConnectorListener);
if (slot.isOutputSlot)
outputContainer.Add(port);
else

void UpdateSlotAttachers()
{
foreach (var port in inputContainer.OfType<Port>())
foreach (var port in inputContainer.OfType<ShaderPort>())
var portInputView = new PortInputView((MaterialSlot)port.userData);
var portInputView = new PortInputView(port.slot);
Add(portInputView);
mainContainer.BringToFront();
m_Attachers.Add(new Attacher(portInputView, port, SpriteAlignment.LeftCenter) { distance = -8f });

{
foreach (var attacher in m_Attachers)
{
var slot = (MaterialSlot)attacher.target.userData;
var slot = ((ShaderPort)attacher.target).slot;
attacher.element.visible = expanded && !node.owner.GetEdges(node.GetSlotReference(slot.id)).Any();
}
}

foreach (var anchor in inputContainer.Concat(outputContainer).OfType<Port>())
foreach (var anchor in inputContainer.Concat(outputContainer).OfType<ShaderPort>())
var slot = (MaterialSlot)anchor.userData;
var slot = anchor.slot;
anchor.portName = slot.displayName;
anchor.visualClass = slot.concreteValueType.ToClassName();
}

46
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/PreviewSceneResources.cs


public class PreviewSceneResources : IDisposable
{
readonly Scene m_Scene;
static Mesh s_Quad;
Material m_BlitNoAlphaMaterial;
static readonly Mesh[] s_Meshes = { null, null, null, null, null };
static readonly GUIContent[] s_MeshIcons = { null, null, null, null, null };

light1.color = new Color(.4f, .4f, .45f, 0f) * .7f;
m_CheckerboardMaterial = new Material(Shader.Find("Hidden/Checkerboard"));
m_BlitNoAlphaMaterial = new Material(Shader.Find("Hidden/BlitNoAlpha"));
blitNoAlphaMaterial.hideFlags = HideFlags.HideAndDontSave;
if (s_Meshes[0] == null)
{

Mesh quadMesh = Resources.GetBuiltinResource(typeof(Mesh), "Quad.fbx") as Mesh;
s_Meshes[4] = quadMesh;
}
if (s_Quad == null)
{
var vertices = new[]
{
new Vector3(-1f, -1f, 0f),
new Vector3(1f, 1f, 0f),
new Vector3(1f, -1f, 0f),
new Vector3(-1f, 1f, 0f)
};
var uvs = new[]
{
new Vector2(0f, 0f),
new Vector2(1f, 1f),
new Vector2(1f, 0f),
new Vector2(0f, 1f)
};
var indices = new[] { 0, 1, 2, 1, 0, 3 };
s_Quad = new Mesh
{
vertices = vertices,
uv = uvs,
triangles = indices
};
s_Quad.RecalculateNormals();
s_Quad.RecalculateBounds();
}
}
public Mesh sphere

public Mesh quad
{
get { return s_Quad; }
get { return s_Meshes[4]; }
}
public Material blitNoAlphaMaterial
{
get { return m_BlitNoAlphaMaterial; }
}
public Camera camera

{
UnityEngine.Object.DestroyImmediate(checkerboardMaterial, true);
m_CheckerboardMaterial = null;
}
if (blitNoAlphaMaterial != null)
{
UnityEngine.Object.DestroyImmediate(blitNoAlphaMaterial, true);
m_BlitNoAlphaMaterial = null;
}
EditorSceneManager.ClosePreviewScene(m_Scene);

34
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/ShaderPort.cs


ShaderPort(Orientation portOrientation, Direction portDirection, Type type)
: base(portOrientation, portDirection, type) { }
public static Port Create(Orientation orientation, Direction direction, Type type, IEdgeConnectorListener connectorListener)
MaterialSlot m_Slot;
public static Port Create(MaterialSlot slot, IEdgeConnectorListener connectorListener)
var port = new ShaderPort(orientation, direction, type)
var port = new ShaderPort(Orientation.Horizontal, slot.isInputSlot ? Direction.Input : Direction.Output, null)
port.slot = slot;
port.portName = slot.displayName;
port.visualClass = slot.concreteValueType.ToClassName();
public VisualElement connectorBox
public MaterialSlot slot
get { return m_ConnectorBox; }
get { return m_Slot; }
set
{
if (ReferenceEquals(value, m_Slot))
return;
if (value == null)
throw new NullReferenceException();
if (m_Slot != null && value.isInputSlot != m_Slot.isInputSlot)
throw new ArgumentException("Cannot change direction of already created port");
m_Slot = value;
portName = slot.displayName;
visualClass = slot.concreteValueType.ToClassName();
}
}
}
static class ShaderPortExtensions
{
public static MaterialSlot GetSlot(this Port port)
{
var shaderPort = port as ShaderPort;
return shaderPort != null ? shaderPort.slot : null;
}
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/Slots/ColorRGBSlotControlView.cs


public ColorRGBSlotControlView(ColorRGBMaterialSlot slot)
{
m_Slot = slot;
var colorField = new ColorField { value = new Color(slot.value.x, slot.value.y, slot.value.z, 0), showAlpha = false };
var colorField = new ColorField { value = new Color(slot.value.x, slot.value.y, slot.value.z, 0),
showEyeDropper = false, showAlpha = false };
colorField.OnValueChanged(OnValueChanged);
Add(colorField);
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/Slots/ColorSlotControlView.cs


public ColorRGBASlotControlView(ColorRGBAMaterialSlot slot)
{
m_Slot = slot;
var colorField = new ColorField { value = slot.value };
var colorField = new ColorField { value = slot.value, showEyeDropper = false };
colorField.OnValueChanged(OnValueChanged);
Add(colorField);
}

16
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Importers/ShaderGraphImporter.cs


using System.Text;
using UnityEditor;
using UnityEditor.Experimental.AssetImporters;
using UnityEditor.Experimental.UIElements;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing;
[ScriptedImporter(1, ShaderGraphImporter.ShaderGraphExtension)]
[ScriptedImporter(4, ShaderGraphImporter.ShaderGraphExtension)]
public class ShaderGraphImporter : ScriptedImporter
{
public const string ShaderGraphExtension = "shadergraph";

var text = GetShaderText<MaterialGraph>(ctx.assetPath, out configuredTextures);
if (text == null)
text = errorShader;
var name = Path.GetFileNameWithoutExtension(ctx.assetPath);
string shaderName = string.Format("graphs/{0}", name);
text = text.Replace("Hidden/GraphErrorShader2", shaderName);
var shader = ShaderUtil.CreateShaderAsset(text);

static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
MaterialGraphEditWindow[] windows = Resources.FindObjectsOfTypeAll<MaterialGraphEditWindow>();
foreach (var matGraphEditWindow in windows)
{
matGraphEditWindow.forceRedrawPreviews = true;
}
}
}

108
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Resources/Styles/MaterialGraph.uss


}
MaterialGraphView {
background-color: rgb(20, 21, 21);
background-color: #202020;
}
MaterialNodeView.graphElement.node.MaterialNode {

width: 100;
}
CubemapSlotControlView {
flex-direction: row;
align-items: center;
}
CubemapSlotControlView > ObjectField {
margin-top: 0;
margin-bottom: 0;
margin-left: 0;
margin-right: 0;
width: 100;
}
MultiFloatSlotControlView {
flex-direction: row;
align-items: center;

}
ColorRGBASlotControlView > ColorField {
width: 50;
width: 41;
margin-left: 0;
margin-right: 0;
}
ColorRGBSlotControlView {

ColorRGBSlotControlView > ColorField {
width: 50;
width: 41;
margin-left: 0;
margin-right: 0;
}
.edge.fromMatrix4, .edge.fromMatrix3, .edge.fromMatrix2 {

flex-grow: 1;
}
ToggleControlView > #togglePanel {
flex-direction: row;
flex-grow: 1;
}
ToggleControlView > #togglePanel > Label {
flex-grow: 1;
padding-left: 0;
padding-right: 0;
padding-top: 0;
padding-bottom: 0;
margin-left: 8;
margin-right: 8;
margin-top: 4;
margin-bottom: 4;
}
ToggleControlView > #togglePanel > Toggle {
margin-left: 8;
margin-right: 8;
margin-top: 4;
margin-bottom: 4;
align-self: center;
}
ObjectControlView {
flex-direction: row;
}

padding-bottom: 0;
}
ChannelMixerControlView {
padding-left: 8;
padding-right: 8;
padding-top: 4;
padding-bottom: 4;
}
ChannelMixerControlView > Label {
margin-left: 0;
margin-right: 0;
cursor: slide-arrow;
}
ChannelMixerControlView > #buttonPanel {
flex-direction: row;
flex-grow: 1;
margin-bottom: 6;
}
ChannelMixerControlView > #buttonPanel > Button {
flex-grow: 1;
margin-left: 0;
margin-right: 0;
align-items: center;
}
ChannelMixerControlView > #buttonPanel > Button > Label {
flex-grow: 1;
margin-left: 0;
margin-right: 0;
margin-top: 0;
margin-bottom: 0;
padding-left: 0;
padding-right: 0;
padding-top: 0;
padding-bottom: 0;
}
ChannelMixerControlView > #sliderPanel {
flex-direction: row;
flex-grow: 1;
}
ChannelMixerControlView > #sliderPanel > Label {
margin-left: 0;
margin-right: 0;
min-width: 20;
}
ChannelMixerControlView > #sliderPanel > Slider {
flex-grow: 1;
margin-left: 0;
margin-right: 0;
}
ChannelMixerControlView > #sliderPanel > FloatField {
margin-left: 4;
margin-right: 2;
min-width: 30;
max-width: 30;
}
/* TEMP STUFF THAT SHOULD ACTUALLY STAY IN GRAPHVIEW */

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


Pass
{
Tags{"LightMode" = "ShadowCaster"}
Pass
{
Tags{"LightMode" = "ShadowCaster"}
ZWrite On ZTest LEqual
ZWrite On ZTest LEqual
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
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma target 2.0
#include "LWRP/Shaders/LightweightPassShadow.hlsl"
ENDHLSL
}
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
Pass
{
Tags{"LightMode" = "DepthOnly"}
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
ZWrite On
ColorMask 0
#include "LWRP/ShaderLibrary/LightweightPassShadow.hlsl"
ENDHLSL
}
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
Pass
{
Tags{"LightMode" = "DepthOnly"}
#include "LWRP/Shaders/LightweightShaderLibrary/Core.hlsl"
ZWrite On
ColorMask 0
float4 vert(float4 pos : POSITION) : SV_POSITION
{
return TransformObjectToHClip(pos.xyz);
}
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
half4 frag() : SV_TARGET
{
return 0;
}
ENDHLSL
}
#include "LWRP/ShaderLibrary/Core.hlsl"
// This pass it not used during regular rendering, only for lightmap baking.
Pass
{
Tags{"LightMode" = "Meta"}
float4 vert(float4 pos : POSITION) : SV_POSITION
{
return TransformObjectToHClip(pos.xyz);
}
Cull Off
half4 frag() : SV_TARGET
{
return 0;
}
ENDHLSL
}
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
// This pass it not used during regular rendering, only for lightmap baking.
Pass
{
Tags{"LightMode" = "Meta"}
#pragma vertex LightweightVertexMeta
#pragma fragment LightweightFragmentMeta
Cull Off
#pragma shader_feature _EMISSION
#pragma shader_feature _METALLICSPECGLOSSMAP
#pragma shader_feature _ _SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A
#pragma shader_feature EDITOR_VISUALIZATION
HLSLPROGRAM
// Required to compile gles 2.0 with standard srp library
#pragma prefer_hlslcc gles
#pragma shader_feature _SPECGLOSSMAP
#pragma vertex LightweightVertexMeta
#pragma fragment LightweightFragmentMeta
#include "LWRP/Shaders/LightweightPassMeta.hlsl"
ENDHLSL
}
#pragma shader_feature _SPECULAR_SETUP
#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/ShaderLibrary/LightweightPassMeta.hlsl"
ENDHLSL
}

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


#pragma multi_compile _ _ADDITIONAL_LIGHTS
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile _ _MIXED_LIGHTING_SUBTRACTIVE
#pragma multi_compile _ FOG_LINEAR FOG_EXP2
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DIRLIGHTMAP_COMBINED
#pragma multi_compile_fog
#pragma multi_compile _ DIRLIGHTMAP_COMBINED LIGHTMAP_ON
//--------------------------------------
// GPU Instancing
#pragma multi_compile_instancing
// LW doesn't support dynamic GI. So we save 30% shader variants if we assume
// LIGHTMAP_ON when DIRLIGHTMAP_COMBINED is set
#ifdef DIRLIGHTMAP_COMBINED
#define LIGHTMAP_ON
#endif
#pragma vertex vert
#pragma fragment frag

#include "LWRP/Shaders/LightweightShaderLibrary/Core.hlsl"
#include "LWRP/Shaders/LightweightShaderLibrary/Lighting.hlsl"
#include "LWRP/ShaderLibrary/Core.hlsl"
#include "LWRP/ShaderLibrary/Lighting.hlsl"
#include "CoreRP/ShaderLibrary/UnityInstancing.hlsl"
#include "ShaderGraphLibrary/Functions.hlsl"
${Graph}

float4 clipPos : SV_POSITION;
float4 lightmapUVOrVertexSH : TEXCOORD0;
float4 clipPos : SV_POSITION;
float4 lightmapUVOrVertexSH : TEXCOORD0;
float4 shadowCoord : TEXCOORD2;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
GraphVertexOutput vert (GraphVertexInput v)

GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
${VertexShader}
float3 lwWNormal = TransformObjectToWorldNormal(v.normal);

// 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_LIGHTMAP_UV(v.texcoord1, unity_LightmapST, o.lightmapUVOrVertexSH);
OUTPUT_SH(lwWNormal, o.lightmapUVOrVertexSH);
half3 vertexLight = VertexLighting(lwWorldPos, lwWNormal);

#if defined(_SHADOWS_ENABLED) && !defined(_SHADOWS_CASCADE)
o.shadowCoord = ComputeShadowCoord(lwWorldPos);
#else
o.shadowCoord = float4(0, 0, 0, 0);
#endif
return o;
}

UNITY_SETUP_INSTANCE_ID(IN);
${LocalPixelShader}
SurfaceInputs surfaceInput = (SurfaceInputs)0;

float3 Albedo = float3(0.5, 0.5, 0.5);
float3 Specular = float3(0, 0, 0);
float Metallic = 0;
float Metallic = 1;
float3 Normal = float3(0, 0, 1);
float3 Emission = 0;
float Smoothness = 0.5;

${SurfaceOutputRemap}
#if _NORMALMAP
half3 normalWS = TangentToWorldNormal(Normal, WorldSpaceTangent, WorldSpaceBiTangent, WorldSpaceNormal);
InputData inputData;
inputData.positionWS = WorldSpacePosition;
#ifdef _NORMALMAP
inputData.normalWS = TangentToWorldNormal(Normal, WorldSpaceTangent, WorldSpaceBiTangent, WorldSpaceNormal);
#else
inputData.normalWS = normalize(WorldSpaceNormal);
#endif
#ifdef SHADER_API_MOBILE
// viewDirection should be normalized here, but we avoid doing it as it's close enough and we save some ALU.
inputData.viewDirectionWS = WorldSpaceViewDirection;
half3 normalWS = normalize(WorldSpaceNormal);
inputData.viewDirectionWS = normalize(WorldSpaceViewDirection);
half3 indirectDiffuse = SampleGI(IN.lightmapUVOrVertexSH, normalWS);
#ifdef _SHADOWS_ENABLED
inputData.shadowCoord = IN.shadowCoord;
#else
inputData.shadowCoord = float4(0, 0, 0, 0);
#endif
half4 color = LightweightFragmentPBR(
WorldSpacePosition,
normalWS,
WorldSpaceViewDirection,
indirectDiffuse,
IN.fogFactorAndVertexLight.yzw,
Albedo,
Metallic,
Specular,
Smoothness,
Occlusion,
Emission,
Alpha);
inputData.fogCoord = IN.fogFactorAndVertexLight.x;
inputData.vertexLighting = IN.fogFactorAndVertexLight.yzw;
inputData.bakedGI = SampleGI(IN.lightmapUVOrVertexSH, inputData.normalWS);
// Computes fog factor per-vertex
ApplyFog(color.rgb, IN.fogFactorAndVertexLight.x);
half4 color = LightweightFragmentPBR(
inputData,
Albedo,
Metallic,
Specular,
Smoothness,
Occlusion,
Emission,
Alpha);
#if _AlphaOut
color.a = Alpha;
#else
color.a = 1;
#endif
// Computes fog factor per-vertex
ApplyFog(color.rgb, IN.fogFactorAndVertexLight.x);
#if _AlphaClip
clip(Alpha - AlphaClipThreshold);

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


${ZTest}
${ZWrite}
HLSLPROGRAM
HLSLPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma shader_feature _SAMPLE_GI
#pragma shader_feature _ _ALPHATEST_ON _ALPHABLEND_ON
#pragma multi_compile_instancing
#include "LWRP/Shaders/LightweightShaderLibrary/Core.hlsl"
#include "LWRP/Shaders/LightweightShaderLibrary/Lighting.hlsl"
#include "LWRP/ShaderLibrary/Core.hlsl"
#include "LWRP/ShaderLibrary/Lighting.hlsl"
#include "LWRP/ShaderLibrary/InputSurface.hlsl"
#include "ShaderGraphLibrary/Functions.hlsl"
${Defines}

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

GraphVertexOutput o;
GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_TRANSFER_INSTANCE_ID(v, o);
o.position = TransformObjectToHClip(v.vertex.xyz);
${VertexShader}
return o;

{
UNITY_SETUP_INSTANCE_ID(IN);
SurfaceInputs surfaceInput;
SurfaceInputs surfaceInput = (SurfaceInputs)0;
float3 Color = 0;
float Alpha = 0;
float3 Color = float3(0.5, 0.5, 0.5);
float Alpha = 1;
float AlphaClipThreshold = 0;
#if _AlphaClip
clip(Alpha - AlphaClipThreshold);
#endif
return half4(Color, Alpha);
}
ENDHLSL

2
MaterialGraphProject/Assets/UnityShaderEditor/LICENSE


Unity Companion License (“License”)
Software Copyright © 2017 Unity Technologies ApS
Software Copyright © 2018 Unity Technologies ApS
Unity Technologies ApS (“Unity”) grants to you a worldwide, non-exclusive,
no-charge, and royalty-free copyright license to reproduce, prepare derivative

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


#endif
}
float4 ComputeScreenPos (float4 pos, float projectionSign)
{
float4 o = pos * 0.5f;
o.xy = float2(o.x, o.y * projectionSign) + o.w;
o.zw = pos.zw;
return o;
}
#endif // UNITY_SHADER_GRAPH_INCLUDED

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


// This contain occlusion factor from 0 to 1 for dynamic objects (no SH here)
float4 unity_ProbesOcclusion;
// HDR environment map decode instructions
half4 unity_SpecCube0_HDR;
CBUFFER_END
#if defined(USING_STEREO_MATRICES)

SAMPLER(samplerunity_DynamicLightmap);
TEXTURE2D(unity_DynamicDirectionality);
// Default reflection probe
TEXTURECUBE(unity_SpecCube0);
SAMPLER(samplerunity_SpecCube0);
// We can have shadowMask only if we have lightmap, so no sampler
TEXTURE2D(unity_ShadowMask);

2
MaterialGraphProject/Assets/UnityShaderEditor/package.json


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

2
MaterialGraphProject/ProjectSettings/ProjectVersion.txt


m_EditorVersion: 2018.1.0b1
m_EditorVersion: 2018.1.0b4

2
MaterialGraphProject/UnityPackageManager/manifest.json


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

25
README.md


# Shader graph
# Shader Graph
![alt text](https://forum.unity.com/proxy.php?image=https%3A%2F%2Flh5.googleusercontent.com%2FUhB18UehZFk8jMo_2V3GW-hD2wARAcQWu6FGzcUvTByHNc51w_mLZBvB6Re5GcTHJQlPHOtzi14wUPvi_yUgWTAp3-HZU463JmxL9NSjJS5yALBSAj1Bdk8yL8zXkRVe-0crKz5F&hash=49458e7088a5be61b288167af65b6faf "Shader Graph")
A Shader Graph enables you to build shaders visually. Instead of hand writing code you create and connect nodes in a graph network. The graph framework gives instant feedback on the changes, and it’s simple enough that new users can become involved in shader creation.
### Disclaimer
This repository is under active development. Everything is subject to change.
Unity branch: `graphics/shadergraph`
## Instructions
**Requires Unity 2018.1 Beta**
*BEFORE COMMITTING:* Run `hg format` on the repository. To run `hg format` inside of a Git repository (like we are doing here) do the following:
```
> cd <location of ShaderGraph repository>
> perl ~/unity-meta/Tools/Format/format.pl .
warning: Not in a .hg repo (.repoconfig and other dependencies will not work)
warning: using last format version as no .repoconfig file was found.
(No files needed formatting; 316 total files were examined)
```
* Download the beta [here](https://unity3d.com/unity/beta)
* Clone branch `master`
* Open contained folder `MaterialGraphProject` as a Unity Project
* Quickstart guide can be found [here](https://forum.unity.com/threads/feedback-wanted-shader-graph.511960/)

189
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/InvertColorsNode.cs


using System;
using System.Collections.Generic;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Title("Artistic", "Adjustment", "Invert Colors")]
public class InvertColorsNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction
{
public InvertColorsNode()
{
name = "Invert Colors";
UpdateNodeAfterDeserialization();
}
const int InputSlotId = 0;
const int OutputSlotId = 1;
const string kInputSlotName = "In";
const string kOutputSlotName = "Out";
public override bool hasPreview
{
get { return true; }
}
string GetFunctionName()
{
return "Unity_InvertColors_" + NodeUtils.ConvertConcreteSlotValueTypeToString(precision, FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType);
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new DynamicVectorMaterialSlot(InputSlotId, kInputSlotName, kInputSlotName, SlotType.Input, Vector4.zero));
AddSlot(new DynamicVectorMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero));
RemoveSlotsNameNotMatching(new[] { InputSlotId, OutputSlotId });
}
int channelCount { get { return SlotValueHelper.GetChannelCount(FindSlot<MaterialSlot>(InputSlotId).concreteValueType); } }
[SerializeField]
private bool m_RedChannel;
[ToggleControl("Red")]
public Toggle redChannel
{
get { return new Toggle(m_RedChannel, channelCount > 0); }
set
{
if (m_RedChannel == value.isOn)
return;
m_RedChannel = value.isOn;
Dirty(ModificationScope.Node);
}
}
[SerializeField]
private bool m_GreenChannel;
[ToggleControl("Green")]
public Toggle greenChannel
{
get { return new Toggle(m_GreenChannel, channelCount > 1); }
set
{
if (m_GreenChannel == value.isOn)
return;
m_GreenChannel = value.isOn;
Dirty(ModificationScope.Node);
}
}
[SerializeField]
private bool m_BlueChannel;
[ToggleControl("Blue")]
public Toggle blueChannel
{
get { return new Toggle(m_BlueChannel, channelCount > 2); }
set
{
if (m_BlueChannel == value.isOn)
return;
m_BlueChannel = value.isOn;
Dirty(ModificationScope.Node);
}
}
private bool m_AlphaChannel;
[ToggleControl("Alpha")]
public Toggle alphaChannel
{
get { return new Toggle(m_AlphaChannel, channelCount > 3); }
set
{
if (m_AlphaChannel == value.isOn)
return;
m_AlphaChannel = value.isOn;
Dirty(ModificationScope.Node);
}
}
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
var sb = new ShaderStringBuilder();
var inputValue = GetSlotValue(InputSlotId, generationMode);
var outputValue = GetSlotValue(OutputSlotId, generationMode);
sb.AppendLine("{0} {1};", FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType.ToString(precision), GetVariableNameForSlot(OutputSlotId));
if (!generationMode.IsPreview())
{
sb.AppendLine("{0} _{1}_InvertColors = {0} ({2}",
FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType.ToString(precision),
GetVariableNameForNode(),
Convert.ToInt32(m_RedChannel));
if (channelCount > 1)
sb.Append(", {0}", Convert.ToInt32(m_GreenChannel));
if (channelCount > 2)
sb.Append(", {0}", Convert.ToInt32(m_BlueChannel));
if (channelCount > 3)
sb.Append(", {0}", Convert.ToInt32(m_AlphaChannel));
sb.Append(");");
}
sb.AppendLine("{0}({1}, _{2}_InvertColors, {3});", GetFunctionName(), inputValue, GetVariableNameForNode(), outputValue);
visitor.AddShaderChunk(sb.ToString(), false);
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
{
base.CollectPreviewMaterialProperties(properties);
properties.Add(new PreviewProperty(PropertyType.Vector4)
{
name = string.Format("_{0}_InvertColors", GetVariableNameForNode()),
vector4Value = new Vector4(Convert.ToInt32(m_RedChannel), Convert.ToInt32(m_GreenChannel), Convert.ToInt32(m_BlueChannel), Convert.ToInt32(m_AlphaChannel)),
});
}
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
{
if (!generationMode.IsPreview())
return;
base.CollectShaderProperties(properties, generationMode);
properties.AddShaderProperty(new Vector4ShaderProperty
{
overrideReferenceName = string.Format("_{0}_InvertColors", GetVariableNameForNode()),
generatePropertyBlock = false
});
}
public void GenerateNodeFunction(ShaderGenerator visitor, GenerationMode generationMode)
{
var sb = new ShaderStringBuilder();
sb.AppendLine("void {0}({1} In, {2} InvertColors, out {3} Out)",
GetFunctionName(),
FindInputSlot<MaterialSlot>(InputSlotId).concreteValueType.ToString(precision),
FindInputSlot<MaterialSlot>(InputSlotId).concreteValueType.ToString(precision),
FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType.ToString(precision));
using (sb.BlockScope())
{
sb.AppendLine("Out = abs(InvertColors - In);");
}
visitor.AddShaderChunk(sb.ToString(), true);
}
public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode)
{
registry.ProvideFunction(GetFunctionName(), s =>
{
s.AppendLine("void {0}({1} In, {2} InvertColors, out {3} Out)",
GetFunctionName(),
FindInputSlot<MaterialSlot>(InputSlotId).concreteValueType.ToString(precision),
FindInputSlot<MaterialSlot>(InputSlotId).concreteValueType.ToString(precision),
FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType.ToString(precision));
using (s.BlockScope())
{
s.AppendLine("Out = abs(InvertColors - In);");
}
});
}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/InvertColorsNode.cs.meta


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

78
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ChannelEnumMaskControl.cs


using System;
using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEngine.Experimental.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Controls
{
[AttributeUsage(AttributeTargets.Property)]
public class ChannelEnumMaskControlAttribute : Attribute, IControlAttribute
{
string m_Label;
int m_SlotId;
public ChannelEnumMaskControlAttribute(string label = null, int slotId = 0)
{
m_Label = label;
m_SlotId = slotId;
}
public VisualElement InstantiateControl(AbstractMaterialNode node, PropertyInfo propertyInfo)
{
return new ChannelEnumMaskControlView(m_Label, m_SlotId, node, propertyInfo);
}
}
public class ChannelEnumMaskControlView : VisualElement, INodeModificationListener
{
GUIContent m_Label;
AbstractMaterialNode m_Node;
PropertyInfo m_PropertyInfo;
IMGUIContainer m_Container;
int m_SlotId;
public ChannelEnumMaskControlView(string label, int slotId, AbstractMaterialNode node, PropertyInfo propertyInfo)
{
m_Node = node;
m_PropertyInfo = propertyInfo;
m_SlotId = slotId;
//if (!propertyInfo.PropertyType.IsEnum)
//throw new ArgumentException("Property must be an enum.", "propertyInfo");
m_Label = new GUIContent(label ?? ObjectNames.NicifyVariableName(propertyInfo.Name));
m_Container = new IMGUIContainer(OnGUIHandler);
Add(m_Container);
}
void OnGUIHandler()
{
UpdatePopup();
}
public void OnNodeModified(ModificationScope scope)
{
if (scope == ModificationScope.Graph)
m_Container.Dirty(ChangeType.Repaint);
}
private void UpdatePopup()
{
var value = (int)m_PropertyInfo.GetValue(m_Node, null);
using (var changeCheckScope = new EditorGUI.ChangeCheckScope())
{
int channelCount = SlotValueHelper.GetChannelCount(m_Node.FindSlot<MaterialSlot>(m_SlotId).concreteValueType);
string[] enumEntryNames = Enum.GetNames(typeof(TextureChannel));
string[] popupEntries = new string[channelCount];
for (int i = 0; i < popupEntries.Length; i++)
popupEntries[i] = enumEntryNames[i];
value = EditorGUILayout.MaskField(m_Label, value, popupEntries);
if (changeCheckScope.changed)
{
m_Node.owner.owner.RegisterCompleteObjectUndo("Change " + m_Node.name);
m_PropertyInfo.SetValue(m_Node, value, null);
}
}
}
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ChannelEnumMaskControl.cs.meta


fileFormatVersion: 2
guid: c32d860c6f767f14fa889dffac527bc5
timeCreated: 1507817885

51
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Resources/Shaders/BlitNoAlpha.shader


Shader "Hidden/BlitNoAlpha"
{
Properties
{
_MainTex ("Texture", any) = "" {}
}
SubShader {
Pass {
ZTest Always Cull Off ZWrite Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
UNITY_DECLARE_SCREENSPACE_TEXTURE(_MainTex);
uniform float4 _MainTex_ST;
struct appdata_t {
float4 vertex : POSITION;
float2 texcoord : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct v2f {
float4 vertex : SV_POSITION;
float2 texcoord : TEXCOORD0;
UNITY_VERTEX_OUTPUT_STEREO
};
v2f vert (appdata_t v)
{
v2f o;
UNITY_SETUP_INSTANCE_ID(v);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.vertex = UnityObjectToClipPos(v.vertex);
o.texcoord = TRANSFORM_TEX(v.texcoord.xy, _MainTex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(i);
return half4(UNITY_SAMPLE_SCREENSPACE_TEXTURE(_MainTex, i.texcoord).xyz, 1.0);
}
ENDCG
}
}
Fallback Off
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Resources/Shaders/BlitNoAlpha.shader.meta


fileFormatVersion: 2
guid: 50b406436c6214c49aaaa6011b71dde8
timeCreated: 1502007198
licenseType: Pro
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:
正在加载...
取消
保存