浏览代码

Merge branch 'master' into node-input-scene

/main
Tim Cooper 7 年前
当前提交
54ac74c0
共有 148 个文件被更改,包括 3237 次插入883 次删除
  1. 1
      .gitignore
  2. 50
      MaterialGraphProject/Assets/Beachball.ShaderGraph
  3. 6
      MaterialGraphProject/Assets/Beachball.mat
  4. 21
      MaterialGraphProject/Assets/NewNodes/Editor/Keep/HeightToNormalNode.cs
  5. 2
      MaterialGraphProject/Assets/NewNodes/Editor/Kill/CheckerboardNode.cs
  6. 332
      MaterialGraphProject/Assets/PartyPreview.ShaderGraph
  7. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/AssetCallbacks/CreateShaderGraph.cs
  8. 83
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/AbstractMaterialGraph.cs
  9. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/ColorShaderProperty.cs
  10. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/DynamicVectorMaterialSlot.cs
  11. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/FloatShaderProperty.cs
  12. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialGraph.cs
  13. 10
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/MaterialSlot.cs
  14. 1
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/TextureShaderProperty.cs
  15. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/Vector2ShaderProperty.cs
  16. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/Vector3ShaderProperty.cs
  17. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/Vector4ShaderProperty.cs
  18. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/AbstractMaterialNode.cs
  19. 17
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/ContrastNode.cs
  20. 7
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Channel/SplitNode.cs
  21. 254
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Channel/SwizzleNode.cs
  22. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/CodeFunctionNode.cs
  23. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/IMasterNode.cs
  24. 35
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Geometry/ScreenPositionNode.cs
  25. 13
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/Texture2DAssetNode.cs
  26. 46
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/Texture2DNode.cs
  27. 13
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/MasterNode.cs
  28. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Math/Advanced/LengthNode.cs
  29. 31
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Procedural/CheckerboardNode.cs
  30. 7
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/PropertyNode.cs
  31. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/SlotValue.cs
  32. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/AbstractSubGraphNode.cs
  33. 13
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/LayeredShaderGraph.cs
  34. 48
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/SurfaceMaterialOptions.cs
  35. 27
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Util/ShaderGenerator.cs
  36. 20
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/EnumControl.cs
  37. 7
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/VectorControl.cs
  38. 51
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/GraphInspectorView.cs
  39. 20
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/ShaderPropertyView.cs
  40. 7
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/StandardNodeEditorView.cs
  41. 42
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Manipulators/GraphDropTarget.cs
  42. 80
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/MaterialGraphEditWindow.cs
  43. 193
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/PreviewManager.cs
  44. 18
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/GraphEditorView.cs
  45. 66
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/MaterialNodeView.cs
  46. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/PortInputView.cs
  47. 5
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/Slots/MultiFloatSlotControlView.cs
  48. 22
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Importers/ShaderGraphImporterEditor.cs
  49. 126
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Resources/Styles/MaterialGraph.uss
  50. 108
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightUnlitPass.template
  51. 8
      MaterialGraphProject/Assets/graphs_PartyPreview.mat
  52. 15
      MaterialGraphProject/ProjectSettings/EditorSettings.asset
  53. 2
      MaterialGraphProject/ProjectSettings/GraphicsSettings.asset
  54. 2
      MaterialGraphProject/ProjectSettings/ProjectVersion.txt
  55. 5
      MaterialGraphProject/UnityPackageManager/manifest.json
  56. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/LightWeightShaderPaths.cs.meta
  57. 46
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/SerializableGraph/Implementation/NodeUtils.cs
  58. 33
      MaterialGraphProject/Assets/LightweightAsset.asset
  59. 8
      MaterialGraphProject/Assets/LightweightAsset.asset.meta
  60. 4
      MaterialGraphProject/Assets/UnityShaderEditor/.npmignore
  61. 79
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/CubemapInputMaterialSlot.cs
  62. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/CubemapInputMaterialSlot.cs.meta
  63. 31
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/CubemapMaterialSlot.cs
  64. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/CubemapMaterialSlot.cs.meta
  65. 66
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/CubemapShaderProperty.cs
  66. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/CubemapShaderProperty.cs.meta
  67. 40
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/SerializableCubemap.cs
  68. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/SerializableCubemap.cs.meta
  69. 282
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs
  70. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs.meta
  71. 208
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightUnlitSubShader.cs
  72. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightUnlitSubShader.cs.meta
  73. 165
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/PBRMasterNode.cs
  74. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/PBRMasterNode.cs.meta
  75. 79
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/UnlitMasterNode.cs
  76. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/UnlitMasterNode.cs.meta
  77. 166
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/ChannelMixerNode.cs
  78. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/ChannelMixerNode.cs.meta
  79. 38
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/ReplaceColorNode.cs
  80. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/ReplaceColorNode.cs.meta
  81. 71
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/WhiteBalanceNode.cs
  82. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/WhiteBalanceNode.cs.meta
  83. 8
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Mask.meta
  84. 188
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Channel/FlipNode.cs
  85. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Channel/FlipNode.cs.meta
  86. 78
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/CubemapAssetNode.cs
  87. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/CubemapAssetNode.cs.meta
  88. 81
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/CubemapNode.cs
  89. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/CubemapNode.cs.meta
  90. 79
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ChannelEnumControl.cs
  91. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ChannelEnumControl.cs.meta
  92. 141
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ChannelMixerControl.cs
  93. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ChannelMixerControl.cs.meta
  94. 55
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/CubemapControl.cs
  95. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/CubemapControl.cs.meta
  96. 86
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ToggleControl.cs
  97. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ToggleControl.cs.meta
  98. 35
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/Slots/CubemapSlotControlView.cs
  99. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/Slots/CubemapSlotControlView.cs.meta

1
.gitignore


MaterialGraphProject/Assets/_MingWai/New Custom Texture.asset.meta
MaterialGraphProject/Packages/*
MaterialGraphProject/GeneratedShader.shader
MaterialGraphProject/UberShader.shader
!MaterialGraphProject/Packages/manifest.json

50
MaterialGraphProject/Assets/Beachball.ShaderGraph
文件差异内容过多而无法显示
查看文件

6
MaterialGraphProject/Assets/Beachball.mat


disabledShaderPasses: []
m_SavedProperties:
serializedVersion: 3
m_TexEnvs: []
m_TexEnvs:
- _Texture2D_A24EBBFA_Tex:
m_Texture: {fileID: 2800000, guid: e017404169662f041a969b0a924cc2ed, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
m_Floats: []
m_Colors: []

21
MaterialGraphProject/Assets/NewNodes/Editor/Keep/HeightToNormalNode.cs


using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using UnityEngine;
using UnityEditor.Graphing;

public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Texture2DMaterialSlot(TextureInput, TextureInputName, TextureInputName, SlotType.Input));
AddSlot(new Vector2MaterialSlot(TexCoordInput, TexCoordInputName, TexCoordInputName, SlotType.Input, Vector2.zero));
AddSlot(new UVMaterialSlot(TexCoordInput, TexCoordInputName, TexCoordInputName, UVChannel.uv0));
AddSlot(new Vector1MaterialSlot(TexOffsetInput, TexOffsetInputName, TexOffsetInputName, SlotType.Input, 0.005f));
AddSlot(new Vector1MaterialSlot(StrengthInput, StrengthInputName, StrengthInputName, SlotType.Input, 8f));
AddSlot(new Vector3MaterialSlot(NormalOutput, NormalOutputName, NormalOutputName, SlotType.Output, Vector3.zero));

{
var textureInput = GetSlotValue(TextureInput, generationMode);
var texCoordInput = RequiresMeshUV(UVChannel.uv0)
? string.Format("{0}.xy", UVChannel.uv0.GetUVName())
: GetSlotValue(TexCoordInput, generationMode);
var texCoordInput = GetSlotValue(TexCoordInput, generationMode);
var texOffsetInput = GetSlotValue(TexOffsetInput, generationMode);
var strengthInput = GetSlotValue(StrengthInput, generationMode);
var normalOutput = GetVariableNameForSlot(NormalOutput);

public bool RequiresMeshUV(UVChannel channel)
{
if (channel != UVChannel.uv0)
foreach (var slot in GetInputSlots<MaterialSlot>().OfType<IMayRequireMeshUV>())
return false;
if (slot.RequiresMeshUV(channel))
return true;
var uvSlot = FindInputSlot<MaterialSlot>(TexCoordInput);
if (uvSlot == null)
return true;
var edges = owner.GetEdges(uvSlot.slotReference).ToList();
return edges.Count == 0;
return false;
}
}
}

2
MaterialGraphProject/Assets/NewNodes/Editor/Kill/CheckerboardNode.cs


/*
using System.Reflection;
using UnityEngine;

}
}
}
*/

332
MaterialGraphProject/Assets/PartyPreview.ShaderGraph
文件差异内容过多而无法显示
查看文件

5
MaterialGraphProject/Assets/UnityShaderEditor/Editor/AssetCallbacks/CreateShaderGraph.cs


using System.IO;
using UnityEditor.ProjectWindowCallback;
using UnityEditor.ShaderGraph;
namespace UnityEditor.ShaderGraph
{

public override void Action(int instanceId, string pathName, string resourceFile)
{
var graph = new ShaderGraph.MaterialGraph();
graph.AddNode(new LightweightMetallicMasterNode());
var graph = new MaterialGraph();
graph.AddNode(new PBRMasterNode());
File.WriteAllText(pathName, EditorJsonUtility.ToJson(graph));
AssetDatabase.Refresh();
}

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


void RemoveShaderPropertyNoValidate(Guid guid)
{
var propertyNodes = GetNodes<PropertyNode>().Where(x => x.propertyGuid == guid).ToList();
foreach (var propNode in propertyNodes)
ReplacePropertyNodeWithConcreteNode(propNode);
if (m_Properties.RemoveAll(x => x.guid == guid) > 0)
m_RemovedProperties.Add(guid);
}

var createdNode = new ColorNode();
createdNode.color = ((ColorShaderProperty) property).value;
slotId = ColorNode.OutputSlotId;
node = createdNode;
}
else if (property is TextureShaderProperty)
{
var createdNode = new Texture2DAssetNode();
createdNode.texture = ((TextureShaderProperty) property).value.texture;
slotId = Texture2DAssetNode.OutputSlotId;
node = createdNode;
}
else if (property is CubemapShaderProperty)
{
var createdNode = new CubemapAssetNode();
createdNode.cubemap = ((CubemapShaderProperty) property).value.cubemap;
slotId = CubemapAssetNode.OutputSlotId;
node = createdNode;
}

base.OnAfterDeserialize();
}
protected static ShaderGraphRequirements GetRequirements(List<INode> nodes)
internal static ShaderGraphRequirements GetRequirements(List<INode> nodes)
{
NeededCoordinateSpace requiresNormal = nodes.OfType<IMayRequireNormal>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresNormal());
NeededCoordinateSpace requiresBitangent = nodes.OfType<IMayRequireBitangent>().Aggregate(NeededCoordinateSpace.None, (mask, node) => mask | node.RequiresBitangent());

FloatShaderProperty outputIdProperty;
return GetShader(node, GenerationMode.Preview, string.Format("hidden/preview/{0}", node.GetVariableNameForNode()), out configuredTextures, out previewMode, out outputIdProperty);
}
public string GetUberPreviewShader(Dictionary<Guid, int> ids, out FloatShaderProperty outputIdProperty)
{
List<PropertyCollector.TextureInfo> configuredTextures;

protected static void GenerateSurfaceDescriptionStruct(ShaderGenerator surfaceDescriptionStruct, List<MaterialSlot> slots, bool isMaster)
internal static void GenerateSurfaceDescriptionStruct(ShaderGenerator surfaceDescriptionStruct, List<MaterialSlot> slots, bool isMaster)
{
surfaceDescriptionStruct.AddShaderChunk("struct SurfaceDescription{", false);
surfaceDescriptionStruct.Indent();

{
if (slot.isInputSlot)
surfaceDescriptionStruct.AddShaderChunk(string.Format("{0} {1};", AbstractMaterialNode.ConvertConcreteSlotValueTypeToString(AbstractMaterialNode.OutputPrecision.@float, slot.concreteValueType), slot.shaderOutputName), false);
else
surfaceDescriptionStruct.AddShaderChunk(string.Format("{0} {1};", AbstractMaterialNode.ConvertConcreteSlotValueTypeToString(AbstractMaterialNode.OutputPrecision.@float, slot.concreteValueType), ((AbstractMaterialNode) slot.owner).GetVariableNameForSlot(slot.id)), false);
}
surfaceDescriptionStruct.AddShaderChunk(string.Format("{0} {1};", AbstractMaterialNode.ConvertConcreteSlotValueTypeToString(AbstractMaterialNode.OutputPrecision.@float, slot.concreteValueType), AbstractMaterialNode.GetHLSLSafeName(slot.shaderOutputName)), false);
surfaceDescriptionStruct.AddShaderChunk("};", false);
surfaceDescriptionStruct.AddShaderChunk("void ScaleSurfaceDescription(inout SurfaceDescription surface, float scale){", false);
surfaceDescriptionStruct.Indent();
foreach (var slot in slots)
{
if (slot.isInputSlot)
surfaceDescriptionStruct.AddShaderChunk(string.Format("surface.{0} = scale * surface.{0};", slot.shaderOutputName), false);
else
surfaceDescriptionStruct.AddShaderChunk(string.Format("surface.{0} = scale * surface.{0};", ((AbstractMaterialNode) slot.owner).GetVariableNameForSlot(slot.id)), false);
}
surfaceDescriptionStruct.Deindent();
surfaceDescriptionStruct.AddShaderChunk("};", false);
surfaceDescriptionStruct.AddShaderChunk("void AddSurfaceDescription(inout SurfaceDescription base, in SurfaceDescription add){", false);
surfaceDescriptionStruct.Indent();
foreach (var slot in slots)
{
if (slot.isInputSlot)
surfaceDescriptionStruct.AddShaderChunk(string.Format("base.{0} = base.{0} + add.{0};", slot.shaderOutputName), false);
else
surfaceDescriptionStruct.AddShaderChunk(string.Format("base.{0} = base.{0} + add.{0};", ((AbstractMaterialNode) slot.owner).GetVariableNameForSlot(slot.id)), false);
}
}
else
{

surfaceDescriptionStruct.AddShaderChunk("};", false);
}
protected static void GenerateSurfaceDescription(
internal static void GenerateSurfaceDescription(
List<INode> activeNodeList,
AbstractMaterialNode masterNode,
AbstractMaterialGraph graph,

string functionName = "PopulateSurfaceData",
string surfaceDescriptionName = "SurfaceDescription",
FloatShaderProperty outputIdProperty = null,
Dictionary<Guid, int> ids = null)
Dictionary<Guid, int> ids = null,
IEnumerable<MaterialSlot> slots = null)
{
if (graph == null)
return;

{
if (masterNode is IMasterNode)
{
foreach (var input in masterNode.GetInputSlots<MaterialSlot>())
var usedSlots = slots ?? masterNode.GetInputSlots<MaterialSlot>();
foreach (var input in usedSlots)
{
var foundEdges = graph.GetEdges(input.slotReference).ToArray();
if (foundEdges.Any())

surfaceDescriptionFunction.AddShaderChunk(string.Format("surface.{0} = {1};", input.shaderOutputName, fromNode.GetVariableNameForSlot(outputRef.slotId)), true);
surfaceDescriptionFunction.AddShaderChunk(string.Format("surface.{0} = {1};", AbstractMaterialNode.GetHLSLSafeName(input.shaderOutputName), fromNode.GetVariableNameForSlot(outputRef.slotId)), true);
surfaceDescriptionFunction.AddShaderChunk(string.Format("surface.{0} = {1};", input.shaderOutputName, input.GetDefaultValue(mode)), true);
surfaceDescriptionFunction.AddShaderChunk(string.Format("surface.{0} = {1};", AbstractMaterialNode.GetHLSLSafeName(input.shaderOutputName), input.GetDefaultValue(mode)), true);
}
}
}

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

};
if (isUber)
shaderProperties.AddShaderProperty(outputIdProperty);
GenerateSurfaceDescription(
activeNodeList,
node,

finalShader.AddShaderChunk(surfaceDescriptionFunction.GetShaderString(2), false);
finalShader.AddShaderChunk("ENDCG", false);
var masterNode = node as IMasterNode;
if (node != null && masterNode != null)
{
var subShaders = masterNode.GetSubshader(requirements, null);
foreach (var ss in subShaders)
finalShader.AddShaderChunk(ss, false);
}
else
{
finalShader.AddShaderChunk(ShaderGenerator.GetPreviewSubShader(node, requirements), false);
}
finalShader.AddShaderChunk(ShaderGenerator.GetPreviewSubShader(node, requirements), false);
ListPool<INode>.Release(activeNodeList);
finalShader.Deindent();

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


}
}
public ColorShaderProperty()
{
displayName = "Color";
}
public override PropertyType propertyType
{
get { return PropertyType.Color; }

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


protected override string ConcreteSlotValueAsVariable(AbstractMaterialNode.OutputPrecision precision)
{
return precision + "4 (" + value.x + "," + value.y + "," + value.z + "," + value.w + ")";
var channelCount = (int)SlotValueHelper.GetChannelCount(concreteValueType);
var values = value.x.ToString();
if (channelCount == 1)
return values;
for (var i = 1; i < channelCount; i++)
values += ", " + value[i];
return string.Format("{0}{1}({2})", precision, channelCount, values);
}
public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode)

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


[Serializable]
public class FloatShaderProperty : AbstractShaderProperty<float>
{
public FloatShaderProperty()
{
displayName = "Float";
}
public override PropertyType propertyType
{
get { return PropertyType.Float; }

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


public string GetShader(string name, GenerationMode mode, out List<PropertyCollector.TextureInfo> configuredTextures)
{
PreviewMode pmode;
FloatShaderProperty outputIdProperty;
return base.GetShader(masterNode as AbstractMaterialNode, mode, name, out configuredTextures, out pmode, out outputIdProperty);
return masterNode.GetShader(mode, name, out configuredTextures);
}
public void LoadedFromDisk()

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


return "(SS)";
case ConcreteSlotValueType.Texture2D:
return "(T)";
case ConcreteSlotValueType.Cubemap:
return "(C)";
default:
return "(E)";
}

return slotType == SlotType.Input
? new Texture2DInputMaterialSlot(slotId, displayName, shaderOutputName, shaderStage, hidden)
: new Texture2DMaterialSlot(slotId, displayName, shaderOutputName, slotType, shaderStage, hidden);
case SlotValueType.Cubemap:
return slotType == SlotType.Input
? new CubemapInputMaterialSlot(slotId, displayName, shaderOutputName, shaderStage, hidden)
: new CubemapMaterialSlot(slotId, displayName, shaderOutputName, slotType, shaderStage, hidden);
case SlotValueType.Dynamic:
return new DynamicVectorMaterialSlot(slotId, displayName, shaderOutputName, slotType, defaultValue, shaderStage, hidden);
case SlotValueType.Vector4:

return inputType == SlotValueType.Matrix2;
case SlotValueType.Texture2D:
return inputType == SlotValueType.Texture2D;
case SlotValueType.Cubemap:
return inputType == SlotValueType.Cubemap;
case SlotValueType.Dynamic:
case SlotValueType.Vector4:
return inputType == SlotValueType.Vector4

{
case ConcreteSlotValueType.Texture2D:
return PropertyType.Texture;
case ConcreteSlotValueType.Cubemap:
return PropertyType.Cubemap;
case ConcreteSlotValueType.Vector1:
return PropertyType.Float;
case ConcreteSlotValueType.Vector2:

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


public TextureShaderProperty()
{
value = new SerializableTexture();
displayName = "Texture";
}
public override PropertyType propertyType

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


[Serializable]
public class Vector2ShaderProperty : VectorShaderProperty
{
public Vector2ShaderProperty()
{
displayName = "Vector2";
}
public override PropertyType propertyType
{
get { return PropertyType.Vector2; }

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


[Serializable]
public class Vector3ShaderProperty : VectorShaderProperty
{
public Vector3ShaderProperty()
{
displayName = "Vector3";
}
public override PropertyType propertyType
{
get { return PropertyType.Vector3; }

5
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/Vector4ShaderProperty.cs


[Serializable]
public class Vector4ShaderProperty : VectorShaderProperty
{
public Vector4ShaderProperty()
{
displayName = "Vector4";
}
public override PropertyType propertyType
{
get { return PropertyType.Vector4; }

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


return p + "4";
case ConcreteSlotValueType.Texture2D:
return "Texture2D";
case ConcreteSlotValueType.Cubemap:
return "Cubemap";
case ConcreteSlotValueType.Matrix2:
return "Matrix2x2";
case ConcreteSlotValueType.Matrix3:

17
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/ContrastNode.cs


namespace UnityEditor.ShaderGraph
{
[Title("Art/Adjustments/Contrast")]
[Title("Artistic/Adjustment/Contrast")]
public class ContrastNode : CodeFunctionNode
{
public ContrastNode()

}
static string Unity_Contrast(
[Slot(0, Binding.None)] Vector3 input,
[Slot(1, Binding.None)] Vector1 contrast,
[Slot(2, Binding.None)] Vector1 midPoint,
[Slot(3, Binding.None)] out Vector3 result)
[Slot(0, Binding.None)] Vector3 In,
[Slot(1, Binding.None, 1, 1, 1, 1)] Vector1 Contrast,
[Slot(2, Binding.None)] out Vector3 Out)
result = Vector2.zero;
Out = Vector2.zero;
// Contrast (reacts better when applied in log)
// Optimal range: [0.0, 2.0]]
// From PostProcessing
result = (input - midPoint) * contrast + midPoint;
{precision} midpoint = pow(0.5, 2.2);
Out = (In - midpoint) * Contrast + midpoint;
}";
}
}

7
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Channel/SplitNode.cs


AddSlot(new Vector1MaterialSlot(OutputSlotGId, kOutputSlotGName, kOutputSlotGName, SlotType.Output, 0));
AddSlot(new Vector1MaterialSlot(OutputSlotBId, kOutputSlotBName, kOutputSlotBName, SlotType.Output, 0));
AddSlot(new Vector1MaterialSlot(OutputSlotAId, kOutputSlotAName, kOutputSlotAName, SlotType.Output, 0));
RemoveSlotsNameNotMatching(s_ValidSlots);
RemoveSlotsNameNotMatching(new int[] { InputSlotId, OutputSlotRId, OutputSlotGId, OutputSlotBId, OutputSlotAId });
static int[] s_ValidSlots = { InputSlotId, OutputSlotRId, OutputSlotGId, OutputSlotBId, OutputSlotAId };
NodeUtils.SlotConfigurationExceptionIfBadConfiguration(this, new[] { InputSlotId }, new[] { OutputSlotRId, OutputSlotGId, OutputSlotBId });
var inputValue = GetSlotValue(InputSlotId, generationMode);
var inputSlot = FindInputSlot<MaterialSlot>(InputSlotId);

for (var i = 0; i < 4; i++)
{
var outputValue = i >= numInputChannels ? "1.0" : string.Format("{0}[{1}]", inputValue, i);
var outputFormat = numInputChannels == 1 ? inputValue : string.Format("{0}[{1}]", inputValue, i);
var outputValue = i >= numInputChannels ? "0" : outputFormat;
visitor.AddShaderChunk(string.Format("{0} {1} = {2};", precision, GetVariableNameForSlot(s_OutputSlots[i]), outputValue), true);
}
}

254
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Channel/SwizzleNode.cs


using UnityEditor.Graphing;
using System.Linq;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
/* [Title("Channel/Swizzle")]
public class SwizzleNode : Function1Input
{
public enum SwizzleChannel
{
R = 0,
G = 1,
B = 2,
A = 3,
}
[Title("Channel/Swizzle")]
public class SwizzleNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction
{
public SwizzleNode()
{
name = "Swizzle";
UpdateNodeAfterDeserialization();
}
[SerializeField]
private SwizzleChannel[] m_SwizzleChannels = new SwizzleChannel[4] { SwizzleChannel.R, SwizzleChannel.G, SwizzleChannel.B, SwizzleChannel.A };
const int InputSlotId = 0;
const int OutputSlotId = 1;
const string kInputSlotName = "In";
const string kOutputSlotName = "Out";
public SwizzleChannel[] swizzleChannels
{
get { return m_SwizzleChannels; }
set
{
if (m_SwizzleChannels == value)
return;
public override bool hasPreview
{
get { return true; }
}
m_SwizzleChannels = value;
if (onModified != null)
{
onModified(this, ModificationScope.Graph);
}
}
}
string GetFunctionName()
{
return "Unity_Swizzle_" + precision + "_" + GuidEncoder.Encode(guid);
}
public SwizzleNode()
{
name = "Swizzle";
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new DynamicVectorMaterialSlot(InputSlotId, kInputSlotName, kInputSlotName, SlotType.Input, Vector4.zero));
AddSlot(new Vector4MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero));
RemoveSlotsNameNotMatching(new[] { InputSlotId, OutputSlotId });
}
protected override string GetFunctionName()
{
return "";
}
static Dictionary<TextureChannel, string> m_ComponentList = new Dictionary<TextureChannel, string>
{
{TextureChannel.Red, ".r" },
{TextureChannel.Green, ".g" },
{TextureChannel.Blue, ".b" },
{TextureChannel.Alpha, ".a" },
};
protected override string GetFunctionCallBody(string inputValue)
{
string[] channelNames = { "r", "g", "b", "a" };
var inputSlot = FindInputSlot<MaterialSlot>(InputSlotId);
var outputSlot = FindOutputSlot<MaterialSlot>(OutputSlotId);
[SerializeField]
private TextureChannel m_RedChannel;
if (inputSlot == null)
return "1.0";
if (outputSlot == null)
return "1.0";
[ChannelEnumControl("Red Out")]
public TextureChannel redChannel
{
get { return m_RedChannel; }
set
{
if (m_RedChannel == value)
return;
int numInputChannels = (int)SlotValueHelper.GetChannelCount(inputSlot.concreteValueType);
int numOutputChannels = (int)SlotValueHelper.GetChannelCount(outputSlot.concreteValueType);
m_RedChannel = value;
if (onModified != null)
{
onModified(this, ModificationScope.Graph);
}
}
}
//int numInputChannels = (int)inputSlot.concreteValueType;
int numOutputChannels = (int)outputSlot.concreteValueType;
if (owner.GetEdges(inputSlot.slotReference).ToList().Count() == 0)
numInputChannels = 0;
if (owner.GetEdges(outputSlot.slotReference).ToList().Count() == 0)
numOutputChannels = 0;
[SerializeField]
private TextureChannel m_GreenChannel;
if (numOutputChannels == 0)
{
return "1.0";
}
[ChannelEnumControl("Green Out")]
public TextureChannel greenChannel
{
get { return m_GreenChannel; }
set
{
if (m_GreenChannel == value)
return;
string outputString = precision + "4(";
//float4(1.0,1.0,1.0,1.0)
if (numInputChannels == 0)
{
outputString += "1.0, 1.0, 1.0, 1.0).";
}
else
{
//float4(arg1.
outputString += inputValue + ".";
m_GreenChannel = value;
if (onModified != null)
{
onModified(this, ModificationScope.Graph);
}
}
}
[SerializeField]
private TextureChannel m_BlueChannel;
[ChannelEnumControl("Blue Out")]
public TextureChannel blueChannel
{
get { return m_BlueChannel; }
set
{
if (m_BlueChannel == value)
return;
m_BlueChannel = value;
if (onModified != null)
{
onModified(this, ModificationScope.Graph);
}
}
}
[SerializeField]
private TextureChannel m_AlphaChannel;
[ChannelEnumControl("Alpha Out")]
public TextureChannel alphaChannel
{
get { return m_AlphaChannel; }
set
{
if (m_AlphaChannel == value)
return;
m_AlphaChannel = value;
if (onModified != null)
{
onModified(this, ModificationScope.Graph);
}
}
}
void ValidateChannelCount()
{
int channelCount = (int)SlotValueHelper.GetChannelCount(FindInputSlot<MaterialSlot>(InputSlotId).concreteValueType);
if ((int)redChannel >= channelCount)
redChannel = TextureChannel.Red;
if ((int)greenChannel >= channelCount)
greenChannel = TextureChannel.Red;
if ((int)blueChannel >= channelCount)
blueChannel = TextureChannel.Red;
if ((int)alphaChannel >= channelCount)
alphaChannel = TextureChannel.Red;
}
string GetFunctionPrototype(string inArg, string outArg)
{
return string.Format("void {0} ({1} {2}, out {3} {4})", GetFunctionName(),
ConvertConcreteSlotValueTypeToString(precision, FindInputSlot<MaterialSlot>(InputSlotId).concreteValueType), inArg,
ConvertConcreteSlotValueTypeToString(precision, FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType), outArg);
}
//float4(arg1.xy
int i = 0;
for (; i < numInputChannels; ++i)
{
int channel = (int)m_SwizzleChannels[i];
outputString += channelNames[channel];
}
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
ValidateChannelCount();
string inputValue = GetSlotValue(InputSlotId, generationMode);
string outputValue = GetSlotValue(OutputSlotId, generationMode);
visitor.AddShaderChunk(string.Format("{0} {1};", ConvertConcreteSlotValueTypeToString(precision, FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType), GetVariableNameForSlot(OutputSlotId)), true);
visitor.AddShaderChunk(GetFunctionCallBody(inputValue, outputValue), true);
}
string GetFunctionCallBody(string inputValue, string outputValue)
{
return GetFunctionName() + " (" + inputValue + ", " + outputValue + ");";
}
public void GenerateNodeFunction(ShaderGenerator visitor, GenerationMode generationMode)
{
ValidateChannelCount();
var outputString = new ShaderGenerator();
outputString.AddShaderChunk(GetFunctionPrototype("In", "Out"), true);
outputString.AddShaderChunk("{", true);
outputString.Indent();
outputString.AddShaderChunk(string.Format("Out = {0} ({1}, {2}, {3}, {4});",
ConvertConcreteSlotValueTypeToString(precision, FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType),
kInputSlotName + m_ComponentList[m_RedChannel],
kInputSlotName + m_ComponentList[m_GreenChannel],
kInputSlotName + m_ComponentList[m_BlueChannel],
kInputSlotName + m_ComponentList[m_AlphaChannel]), true);
//float4(arg1.xy, 1.0, 1.0)
for (; i < 4; i++)
{
outputString += ", 1.0";
}
outputString += ").";
}
outputString.Deindent();
outputString.AddShaderChunk("}", true);
//float4(arg1.xy, 1.0, 1.0).rg
for (int j = 0; j < numOutputChannels; ++j)
{
outputString += channelNames[j];
}
return outputString;
}
}*/
}
visitor.AddShaderChunk(outputString.GetShaderString(0), true);
}
}
}

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


{
return SlotValueType.Texture2D;
}
if (t == typeof(Cubemap))
{
return SlotValueType.Cubemap;
}
if (t == typeof(SamplerState))
{
return SlotValueType.SamplerState;

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/IMasterNode.cs


public interface IMasterNode
{
SurfaceMaterialOptions options { get; }
IEnumerable<string> GetSubshader(ShaderGraphRequirements graphRequirements, MasterRemapGraph remapper);
string GetShader(GenerationMode mode, string name, out List<PropertyCollector.TextureInfo> configuredTextures);
}
}

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


public enum ScreenSpaceType
{
Default,
Raw,
Center,
Tiled
};

}
}
string GetCurrentType()
{
return System.Enum.GetName(typeof(ScreenSpaceType), m_ScreenSpaceType);
}
private const int kOutputSlot1Id = 0;
private const string kOutputSlot1Name = "Out";
private const int kOutputSlotId = 0;
private const string kOutputSlotName = "Out";
public override bool hasPreview { get { return true; } }
public override PreviewMode previewMode

public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Vector2MaterialSlot(kOutputSlot1Id, kOutputSlot1Name, kOutputSlot1Name, SlotType.Output, Vector2.zero));
RemoveSlotsNameNotMatching(new[] { kOutputSlot1Id });
}
public override string GetVariableNameForSlot(int slotId)
{
return ShaderGeneratorNames.ScreenPosition;
AddSlot(new Vector4MaterialSlot(kOutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero));
RemoveSlotsNameNotMatching(new[] { kOutputSlotId });
}
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)

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

13
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/Texture2DAssetNode.cs


namespace UnityEditor.ShaderGraph
{
[Title("Input/Texture/Texture 2D Asset")]
public class Texture2DAssetNode : AbstractMaterialNode
public class Texture2DAssetNode : AbstractMaterialNode, IPropertyFromNode
{
public const int OutputSlotId = 0;

m_Texture = texture
});
}
public IShaderProperty AsShaderProperty()
{
var prop = new TextureShaderProperty();
prop.value = m_Texture;
if (texture != null)
prop.displayName = texture.name;
return prop;
}
public int outputSlotId { get { return OutputSlotId; } }
}
}

46
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/Texture2DNode.cs


using System.Linq;
using System.Reflection;
using UnityEditor.ShaderGraph.Drawing.Controls;
public enum TextureType
{
Default,
Normal
};
[Title("Input/Texture/Texture 2D")]
public class Texture2DNode : AbstractMaterialNode, IGeneratesBodyCode, IMayRequireMeshUV
{

UpdateNodeAfterDeserialization();
}
[SerializeField]
private TextureType m_TextureType = TextureType.Default;
[EnumControl("Type")]
public TextureType textureType
{
get { return m_TextureType; }
set
{
if (m_TextureType == value)
return;
m_TextureType = value;
if (onModified != null)
{
onModified(this, ModificationScope.Graph);
}
}
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Vector4MaterialSlot(OutputSlotRGBAId, kOutputSlotRGBAName, kOutputSlotRGBAName, SlotType.Output, Vector4.zero));

}
visitor.AddShaderChunk(result, true);
if (textureType == TextureType.Normal)
visitor.AddShaderChunk(string.Format("{0}.rgb = UnpackNormal({0});", GetVariableNameForSlot(OutputSlotRGBAId)), true);
visitor.AddShaderChunk(string.Format("{0} {1} = {2}.r;", precision, GetVariableNameForSlot(OutputSlotRId), GetVariableNameForSlot(OutputSlotRGBAId)), true);
visitor.AddShaderChunk(string.Format("{0} {1} = {2}.g;", precision, GetVariableNameForSlot(OutputSlotGId), GetVariableNameForSlot(OutputSlotRGBAId)), true);
visitor.AddShaderChunk(string.Format("{0} {1} = {2}.b;", precision, GetVariableNameForSlot(OutputSlotBId), GetVariableNameForSlot(OutputSlotRGBAId)), true);

public bool RequiresMeshUV(UVChannel channel)
{
var uvSlot = FindInputSlot<MaterialSlot>(UVInput) as UVMaterialSlot;
if (uvSlot == null)
return false;
if (uvSlot.isConnected)
return false;
return uvSlot.RequiresMeshUV(channel);
foreach (var slot in GetInputSlots<MaterialSlot>().OfType<IMayRequireMeshUV>())
{
if (slot.RequiresMeshUV(channel))
return true;
}
return false;
}
}
}

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


[SerializeField]
protected SurfaceMaterialOptions m_MaterialOptions = new SurfaceMaterialOptions();
public MasterNode()
{
name = "MasterNode";
UpdateNodeAfterDeserialization();
}
public override bool hasPreview
{
get { return true; }

get { return PreviewMode.Preview3D; }
}
public virtual ShaderGraphRequirements GetNodeSpecificRequirements()
{
return ShaderGraphRequirements.none;
}
public SurfaceMaterialOptions options
{
get { return m_MaterialOptions; }

public abstract IEnumerable<string> GetSubshader(ShaderGraphRequirements graphRequirements, MasterRemapGraph remapper);
public abstract string GetShader(GenerationMode mode, string name, out List<PropertyCollector.TextureInfo> configuredTextures);
}
}

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


static string Unity_Length(
[Slot(0, Binding.None)] DynamicDimensionVector In,
[Slot(1, Binding.None)] out DynamicDimensionVector Out)
[Slot(1, Binding.None)] out Vector1 Out)
{
return
@"

31
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Procedural/CheckerboardNode.cs


namespace UnityEditor.ShaderGraph
{
[Title("Procedural/Checkerboard")]
public class AACheckerboardNode : CodeFunctionNode
public class CheckerboardNode : CodeFunctionNode
public AACheckerboardNode()
public CheckerboardNode()
return GetType().GetMethod("Unity_AACheckerboard", BindingFlags.Static | BindingFlags.NonPublic);
return GetType().GetMethod("Unity_Checkerboard", BindingFlags.Static | BindingFlags.NonPublic);
static string Unity_AACheckerboard(
static string Unity_Checkerboard(
[Slot(1, Binding.None, 0.2f, 0.2f, 0.2f, 0.2f)] Vector4 ColorA,
[Slot(2, Binding.None, 0.7f, 0.7f, 0.7f, 0.7f)] Vector4 ColorB,
[Slot(1, Binding.None, 0.2f, 0.2f, 0.2f, 1f)] Color ColorA,
[Slot(2, Binding.None, 0.7f, 0.7f, 0.7f, 1f)] Color ColorB,
[Slot(3, Binding.None, 1f, 1f, 1f, 1f)] Vector2 Frequency,
[Slot(4, Binding.None)] out Vector4 Out)
{

{
float4 derivatives = float4(ddx(UV), ddy(UV));
float2 duv_length = sqrt(float2(dot(derivatives.xz, derivatives.xz), dot(derivatives.yw, derivatives.yw)));
float width = 0.5f;
float2 distance3 = 2.0f * abs(frac(UV.xy * Frequency) - 0.5f) - width;
float2 scale = 0.5 / duv_length.xy;
float2 blend_out = saturate(scale / 3);
float2 vector_alpha = clamp(distance3 * scale.xy * blend_out.xy, -1.0f, 1.0f);
float alpha = saturate(0.5f + 0.5f * vector_alpha.x * vector_alpha.y);
Out= lerp(ColorA, ColorB, alpha.xxxx);
UV = UV + 0.25 / Frequency;
{precision}4 derivatives = {precision}4(ddx(UV), ddy(UV));
{precision}2 duv_length = sqrt({precision}2(dot(derivatives.xz, derivatives.xz), dot(derivatives.yw, derivatives.yw)));
{precision} width = 0.5;
{precision}2 distance3 = 2.0 * abs(frac((UV.xy + 0.5) * Frequency) - 0.5) - width;
{precision}2 scale = 0.5 / duv_length.xy;
{precision}2 blend_out = saturate(scale / 3);
{precision}2 vector_alpha = clamp(distance3 * scale.xy * blend_out.xy, -1.0, 1.0);
{precision} alpha = saturate(vector_alpha.x * vector_alpha.y);
Out = lerp(ColorA, ColorB, alpha.xxxx);
}";
}
}

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


AddSlot(new Texture2DMaterialSlot(OutputSlotId, "T", "T", SlotType.Output));
RemoveSlotsNameNotMatching(new[] {OutputSlotId});
}
else if (property is CubemapShaderProperty)
{
AddSlot(new CubemapMaterialSlot(OutputSlotId, "C", "C", SlotType.Output));
RemoveSlotsNameNotMatching(new[] { OutputSlotId });
}
}
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)

var graph = owner as AbstractMaterialGraph;
var property = graph.properties.FirstOrDefault(x => x.guid == propertyGuid);
if (!(property is TextureShaderProperty))
if (!(property is TextureShaderProperty) && !(property is CubemapShaderProperty))
return base.GetVariableNameForSlot(slotId);
return property.referenceName;

3
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/SlotValue.cs


Matrix3,
Matrix2,
Texture2D,
Cubemap,
Dynamic,
Vector4,
Vector3,

Matrix3,
Matrix2,
Texture2D,
Cubemap,
Vector4,
Vector3,
Vector2,

"typeMatrix",
"typeMatrix",
"typeTexture2D",
"typeCubemap",
"typeFloat4",
"typeFloat3",
"typeFloat2",

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


case PropertyType.Texture:
slotType = SlotValueType.Texture2D;
break;
case PropertyType.Cubemap:
slotType = SlotValueType.Cubemap;
break;
case PropertyType.Float:
slotType = SlotValueType.Vector1;
break;

var tProp = prop as TextureShaderProperty;
if (tSlot != null && tProp != null)
tSlot.texture = tProp.value.texture;
}
// copy default for cubemap for niceness
else if (slotType == SlotValueType.Cubemap && propType == PropertyType.Cubemap)
{
var tSlot = slot as CubemapInputMaterialSlot;
var tProp = prop as CubemapShaderProperty;
if (tSlot != null && tProp != null)
tSlot.cubemap = tProp.value.cubemap;
}
AddSlot(slot);
validNames.Add(id);

13
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/LayeredShaderGraph.cs


var masterNode = baseGraph.masterNode;
GenerateSurfaceDescriptionStruct(surfaceDescriptionStruct, ((AbstractMaterialNode) masterNode).GetInputSlots<MaterialSlot>().ToList(), true);
foreach (var layer in layerMap)
/* foreach (var layer in layerMap)
{
activeNodes.Clear();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodes, layer.Value.masterNode as AbstractMaterialNode);

requirements,
mode,
LayerToFunctionName(layer.Key));
}
}*/
surfaceDescriptionStruct.AddShaderChunk("struct WeightsSurfaceDescription{", false);
surfaceDescriptionStruct.Indent();

activeNodes.Clear();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodes, outputNode);
GenerateSurfaceDescription(
/*GenerateSurfaceDescription(
activeNodes,
outputNode,
this,

mode,
"PopulateWeightsGraph",
"WeightsSurfaceDescription");
*/
string functionName = "PopulateSurfaceData";
string surfaceDescriptionName = "SurfaceDescription";

if (masterNode != null)
{
var subShaders = masterNode.GetSubshader(requirements, null);
foreach (var ss in subShaders)
finalShader.AddShaderChunk(ss, false);
//var subShaders = masterNode.GetSubshader(requirements, null);
// foreach (var ss in subShaders)
// finalShader.AddShaderChunk(ss, false);
}
finalShader.Deindent();

48
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SurfaceModel/SurfaceMaterialOptions.cs


private RenderType m_RenderType = RenderType.Opaque;
[SerializeField]
private bool m_ShadowPass;
[SerializeField]
private bool m_FullForwardShadows;
[SerializeField]
private bool m_NoAmbient;
[SerializeField]
private bool m_NoVertexLights;
[SerializeField]
private bool m_NoLightmaps;
[SerializeField]
private bool m_NoDirLightmap;
[SerializeField]
private bool m_NoForwardAdd;
[SerializeField]
private bool m_ApproxView;
[SerializeField]
private bool m_HalfAsView;
[SerializeField]
[SerializeField]
private bool m_Expanded;
public void Init()
{

zWrite = ZWrite.On;
renderQueue = RenderQueue.Geometry;
renderType = RenderType.Opaque;
shadowPass = false;
fullForwardShadows = false;
noAmbient = false;
noVertexLights = false;
noLightmaps = false;
noDirLightmap = false;
noForwardAdd = false;
approxView = false;
halfAsView = false;
lod = 200;
}

public ZWrite zWrite { get { return m_ZWrite; } set { m_ZWrite = value; } }
public RenderQueue renderQueue { get { return m_RenderQueue; } set { m_RenderQueue = value; } }
public RenderType renderType { get { return m_RenderType; } set { m_RenderType = value; } }
public bool shadowPass { get { return m_ShadowPass; } set { m_ShadowPass = value; } }
public bool fullForwardShadows { get { return m_FullForwardShadows; } set { m_FullForwardShadows = value; } }
public bool noAmbient { get { return m_NoAmbient; } set { m_NoAmbient = value; } }
public bool noVertexLights { get { return m_NoVertexLights; } set { m_NoVertexLights = value; } }
public bool noLightmaps { get { return m_NoLightmaps; } set { m_NoLightmaps = value; } }
public bool noDirLightmap { get { return m_NoDirLightmap; } set { m_NoDirLightmap = value; } }
public bool noForwardAdd { get { return m_NoForwardAdd; } set { m_NoForwardAdd = value; } }
public bool approxView { get { return m_ApproxView; } set { m_ApproxView = value; } }
public bool halfAsView { get { return m_HalfAsView; } set { m_HalfAsView = value; } }
public int lod { get { return m_LOD; } set { m_LOD = value; } }
}
}

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


result = Path.Combine(result, path[i]);
result = Path.Combine(result, templateName);
return result;
if (File.Exists(result))
return result;
//todo: fix this up... quick hack for working
// in a package
var path2 = new List<string>
{
"Packages",
"com.unity.shadergraph",
"Editor",
"Templates"
};
string result2 = path2[0];
for (int i = 1; i < path2.Count; i++)
result2 = Path.Combine(result2, path2[i]);
result2 = Path.Combine(result2, templateName);
result2 = Path.GetFullPath(result2);
if (File.Exists(result2))
return result2;
return string.Empty;
}
private const string kErrorString = @"ERROR!";

20
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/EnumControl.cs


using System;
using System.Reflection;
using UnityEditor.Experimental.UIElements;
using UnityEngine;
using UnityEngine.Experimental.UIElements;

public class EnumControlView : VisualElement
{
GUIContent m_Label;
AbstractMaterialNode m_Node;
PropertyInfo m_PropertyInfo;

m_PropertyInfo = propertyInfo;
if (!propertyInfo.PropertyType.IsEnum)
throw new ArgumentException("Property must be an enum.", "propertyInfo");
m_Label = new GUIContent(label ?? ObjectNames.NicifyVariableName(propertyInfo.Name));
Add(new IMGUIContainer(OnGUIHandler));
Add(new Label(label ?? ObjectNames.NicifyVariableName(propertyInfo.Name)));
var enumField = new EnumField((Enum) m_PropertyInfo.GetValue(m_Node, null));
enumField.OnValueChanged(OnValueChanged);
Add(enumField);
void OnGUIHandler()
void OnValueChanged(ChangeEvent<Enum> evt)
using (var changeCheckScope = new EditorGUI.ChangeCheckScope())
if (!evt.newValue.Equals(value))
value = EditorGUILayout.EnumPopup(m_Label, value);
if (changeCheckScope.changed)
{
m_Node.owner.owner.RegisterCompleteObjectUndo("Change " + m_Node.name);
m_PropertyInfo.SetValue(m_Node, value, null);
}
m_Node.owner.owner.RegisterCompleteObjectUndo("Change " + m_Node.name);
m_PropertyInfo.SetValue(m_Node, evt.newValue, null);
}
}
}

7
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/VectorControl.cs


void AddField(int index, string subLabel)
{
Add(new Label(subLabel));
var label = new Label(subLabel);
Add(label);
var dragger = new FieldMouseDragger<double>(doubleField);
dragger.SetDragZone(label);
doubleField.RegisterCallback<MouseDownEvent>(Repaint);
doubleField.RegisterCallback<MouseMoveEvent>(Repaint);
doubleField.OnValueChanged(evt =>

SetValue(value);
m_UndoGroup = -1;
Dirty(ChangeType.Repaint);
});
doubleField.RegisterCallback<InputEvent>(evt =>
{

var value = GetValue();
value[index] = newValue;
SetValue(value);
Dirty(ChangeType.Repaint);
});
doubleField.RegisterCallback<KeyDownEvent>(evt =>
{

51
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/GraphInspectorView.cs


using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph;
using UnityEngine.AI;
namespace UnityEditor.ShaderGraph.Drawing.Inspector
{

PreviewTextureView m_PreviewTextureView;
AbstractMaterialGraph m_Graph;
PreviewManager m_PreviewManager;
PreviewData m_PreviewHandle;
PreviewRenderData m_PreviewRenderHandle;
List<INode> m_SelectedNodes;

persistenceKey = "GraphInspector";
m_Graph = graph;
m_PreviewManager = previewManager;
m_SelectedNodes = new List<INode>();
AddStyleSheetPath("Styles/MaterialGraph");

}
Add(bottomContainer);
masterNode = graph.GetNodes<MasterNode>().FirstOrDefault();
m_PreviewRenderHandle = previewManager.masterRenderData;
m_PreviewRenderHandle.onPreviewChanged += OnPreviewChanged;
foreach (var property in m_Graph.properties)
m_PropertyItems.Add(new ShaderPropertyView(m_Graph, property));

MasterNode masterNode
{
get { return m_MasterNode; }
set
{
if (value == m_MasterNode)
return;
if (m_MasterNode != null)
m_PreviewHandle.onPreviewChanged -= OnPreviewChanged;
m_PreviewHandle = null;
m_MasterNode = value;
if (m_MasterNode != null)
{
m_PreviewHandle = m_PreviewManager.GetPreview(m_MasterNode);
m_PreviewHandle.onPreviewChanged += OnPreviewChanged;
}
}
get { return m_PreviewRenderHandle.shaderData.node as MasterNode; }
}
void OnAddProperty()

gm.AddItem(new GUIContent("Vector4"), false, () => AddProperty(new Vector4ShaderProperty()));
gm.AddItem(new GUIContent("Color"), false, () => AddProperty(new ColorShaderProperty()));
gm.AddItem(new GUIContent("Texture"), false, () => AddProperty(new TextureShaderProperty()));
gm.AddItem(new GUIContent("Cubemap"), false, () => AddProperty(new CubemapShaderProperty()));
gm.ShowAsContext();
}

void OnPreviewChanged()
{
m_PreviewTextureView.image = m_PreviewHandle.texture ?? Texture2D.blackTexture;
m_PreviewTextureView.image = m_PreviewRenderHandle.texture ?? Texture2D.blackTexture;
m_PreviewTextureView.Dirty(ChangeType.Repaint);
}

{
m_PreviewHandle.mesh = null;
m_PreviewRenderHandle.mesh = null;
m_PersistentMasterNodePreviewMesh.mesh = null;
}

{
m_PreviewHandle.mesh = changedMesh;
m_PreviewRenderHandle.mesh = changedMesh;
m_PersistentMasterNodePreviewMesh.mesh = changedMesh;
}

foreach (var layer in layerGraph.addedLayers)
m_LayerItems.Add(new ShaderLayerView(layerGraph, layer));
}
if (masterNode != null)
{
if (m_Graph.removedNodes.Contains(masterNode))
masterNode = null;
}
if (masterNode == null)
{
var addedMasterNode = m_Graph.addedNodes.OfType<MasterNode>().FirstOrDefault();
if (addedMasterNode != null)
masterNode = addedMasterNode;
}
if (m_PreviewHandle != null)
if (m_PreviewRenderHandle != null)
m_PreviewHandle.onPreviewChanged -= OnPreviewChanged;
m_PreviewHandle = null;
m_PreviewRenderHandle.onPreviewChanged -= OnPreviewChanged;
m_PreviewRenderHandle = null;
}
}
}

20
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/ShaderPropertyView.cs


using System;
using UnityEditor.Experimental.UIElements;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEditor.ShaderGraph;
using Object = UnityEngine.Object;
namespace UnityEditor.ShaderGraph.Drawing.Inspector

objectField.OnValueChanged(OnTextureChanged);
Add(objectField);
}
else if (property is CubemapShaderProperty)
{
var fProp = (CubemapShaderProperty)property;
var objectField = new ObjectField { name = "value", objectType = typeof(Cubemap), value = fProp.value.cubemap };
objectField.OnValueChanged(OnCubemapChanged);
Add(objectField);
}
Add(new Button(OnClickRemove) { name = "remove", text = "Remove" });
}

if (newValue != fProp.value.texture)
{
fProp.value.texture = newValue;
NotifyNodes();
}
}
void OnCubemapChanged(ChangeEvent<Object> evt)
{
var fProp = (CubemapShaderProperty)property;
var newValue = (Cubemap)evt.newValue;
if (newValue != fProp.value.cubemap)
{
fProp.value.cubemap = newValue;
NotifyNodes();
}
}

7
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Inspector/StandardNodeEditorView.cs


using System.Linq;
using UnityEditor.Graphing.Util;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph.Drawing.Inspector
{

42
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Manipulators/GraphDropTarget.cs


using System.Linq;
using UnityEngine;
using UnityEngine;
using UnityEditor.ShaderGraph;
namespace UnityEditor.ShaderGraph.Drawing
{

bool ValidateObject(Object obj)
{
return EditorUtility.IsPersistent(obj)
&& (obj is Texture2D || obj is MaterialSubGraphAsset);
&& (obj is Texture2D || obj is Cubemap || obj is MaterialSubGraphAsset);
}
void CreateNode(Object obj, Vector2 nodePosition)

{
m_Graph.owner.RegisterCompleteObjectUndo("Drag Texture");
var property = new TextureShaderProperty { displayName = texture2D.name, value = { texture = texture2D } };
bool isNormalMap = false;
if (EditorUtility.IsPersistent(texture2D)
&& !string.IsNullOrEmpty(AssetDatabase.GetAssetPath(texture2D)))
{
var importer = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(texture2D)) as TextureImporter;
if (importer != null)
isNormalMap = importer.textureType == TextureImporterType.NormalMap;
}
var node = new Texture2DNode();
if (isNormalMap)
node.textureType = TextureType.Normal;
var drawState = node.drawState;
drawState.position = new Rect(nodePosition, drawState.position.size);
node.drawState = drawState;
m_Graph.AddNode(node);
var inputslot = node.FindSlot<Texture2DInputMaterialSlot>(Texture2DNode.TextureInputId);
if (inputslot != null)
inputslot.texture = texture2D;
}
var cubemap = obj as Cubemap;
if (cubemap != null)
{
m_Graph.owner.RegisterCompleteObjectUndo("Drag Cubemap");
var property = new CubemapShaderProperty { displayName = cubemap.name, value = { cubemap = cubemap } };
var node = new PropertyNode();
var node = new CubemapNode();
node.propertyGuid = property.guid;
var inputslot = node.FindSlot<CubemapInputMaterialSlot>(CubemapNode.CubemapInputId);
if (inputslot != null)
inputslot.cubemap = cubemap;
}
var subGraphAsset = obj as MaterialSubGraphAsset;

Object draggedObject = null;
foreach (var obj in objects)
{
Debug.Log(obj.GetType().Name);
if (ValidateObject(obj))
{
draggedObject = obj;

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


m_GraphEditorView.onConvertToSubgraphClick += ToSubGraph;
m_GraphEditorView.onShowInProjectClick += PingAsset;
this.GetRootVisualContainer().Add(graphEditorView);
this.GetRootVisualContainer().parent.clippingOptions = VisualElement.ClippingOptions.ClipContents;
}
}
}

void Update()
{
if (graphObject == null && selectedGuid != null)
{
var guid = selectedGuid;
selectedGuid = null;
ChangeSelection(guid);
}
{
Close();
}
var materialGraph = graphObject.graph as AbstractMaterialGraph;
if (materialGraph == null)
return;

graphEditorView = new GraphEditorView(materialGraph, asset.name) {persistenceKey = AssetDatabase.AssetPathToGUID(AssetDatabase.GUIDToAssetPath(selectedGuid))};
graphEditorView = new GraphEditorView(materialGraph, asset.name) { persistenceKey = AssetDatabase.AssetPathToGUID(AssetDatabase.GUIDToAssetPath(selectedGuid)) };
graphEditorView.previewManager.HandleGraphChanges();
graphEditorView.previewManager.RenderPreviews();
graphEditorView.inspectorView.HandleGraphChanges();
graphObject.graph.ClearChanges();
}

if (path.Length == 0)
return;
graphObject.RegisterCompleteObjectUndo("Convert To Subgraph");
Vector2 middle = Vector2.zero;
var bounds = Rect.MinMaxRect(float.PositiveInfinity, float.PositiveInfinity, float.NegativeInfinity, float.NegativeInfinity);
middle += node.drawState.position.center;
var center = node.drawState.position.center;
bounds = Rect.MinMaxRect(
Mathf.Min(bounds.xMin, center.x),
Mathf.Min(bounds.yMin, center.y),
Mathf.Max(bounds.xMax, center.x),
Mathf.Max(bounds.yMax, center.y));
middle /= nodes.Length;
var middle = bounds.center;
bounds.center = Vector2.zero;
var copyPasteGraph = new CopyPasteGraph(
graphView.selection.OfType<MaterialNodeView>().Where(x => !(x.node is PropertyNode)).Select(x => x.node as INode),

return;
var subGraph = new SubGraph();
subGraph.AddNode(new SubGraphOutputNode());
var subGraphOutputNode = new SubGraphOutputNode();
{
var drawState = subGraphOutputNode.drawState;
drawState.position = new Rect(new Vector2(bounds.xMax + 200f, 0f), drawState.position.size);
subGraphOutputNode.drawState = drawState;
}
subGraph.AddNode(subGraphOutputNode);
var nodeGuidMap = new Dictionary<Guid, Guid>();
foreach (var node in deserialized.GetNodes<INode>())

nodeGuidMap[oldGuid] = newGuid;
var drawState = node.drawState;
drawState.position = new Rect(drawState.position.position - middle, drawState.position.size);
node.drawState = drawState;
subGraph.AddNode(node);
}

var uniqueIncomingEdges = externalOutputSlots.GroupBy(
edge => edge.outputSlot,
edge => edge,
(key, edges) => new {slotRef = key, edges = edges.ToList()});
(key, edges) => new { slotRef = key, edges = edges.ToList() });
var externalInputNeedingConnection = new List<KeyValuePair<IEdge, IShaderProperty>>();
foreach (var group in uniqueIncomingEdges)

case ConcreteSlotValueType.Texture2D:
prop = new TextureShaderProperty();
break;
case ConcreteSlotValueType.Cubemap:
prop = new CubemapShaderProperty();
break;
case ConcreteSlotValueType.Vector4:
prop = new Vector4ShaderProperty();
break;

{
subGraph.AddShaderProperty(prop);
var propNode = new PropertyNode();
{
var drawState = propNode.drawState;
drawState.position = new Rect(new Vector2(bounds.xMin - 300f, 0f), drawState.position.size);
propNode.drawState = drawState;
}
subGraph.AddNode(propNode);
propNode.propertyGuid = prop.guid;

var uniqueOutgoingEdges = externalInputSlots.GroupBy(
edge => edge.inputSlot,
edge => edge,
(key, edges) => new {slot = key, edges = edges.ToList()});
(key, edges) => new { slot = key, edges = edges.ToList() });
var externalOutputsNeedingConnection = new List<KeyValuePair<IEdge, IEdge>>();
foreach (var group in uniqueOutgoingEdges)

var subGraphNode = new SubGraphNode();
var ds = subGraphNode.drawState;
ds.position = new Rect(middle, Vector2.one);
ds.position = new Rect(middle - new Vector2(100f, 150f), Vector2.zero);
subGraphNode.drawState = ds;
graphObject.graph.AddNode(subGraphNode);
subGraphNode.subGraphAsset = loadedSubGraph;

}
}
public void ChangeSelection(string newSelectionGuid, Type graphType)
public void ChangeSelection(string newSelectionGuid)
{
var asset = AssetDatabase.LoadAssetAtPath<Object>(AssetDatabase.GUIDToAssetPath(newSelectionGuid));
if (asset == null)

if (selectedGuid == newSelectionGuid)
return;
var path = AssetDatabase.GetAssetPath(asset);
var extension = Path.GetExtension(path);
Type graphType;
switch (extension)
{
case ".ShaderGraph":
graphType = typeof(MaterialGraph);
break;
case ".LayeredShaderGraph":
graphType = typeof(LayeredShaderGraph);
break;
case ".ShaderSubGraph":
graphType = typeof(SubGraph);
break;
case ".ShaderRemapGraph":
graphType = typeof(MasterRemapGraph);
break;
default:
return;
}
var path = AssetDatabase.GetAssetPath(asset);
var textGraph = File.ReadAllText(path, Encoding.UTF8);
graphObject = CreateInstance<SerializableGraphObject>();
graphObject.hideFlags = HideFlags.HideAndDontSave;

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


public class PreviewManager : IDisposable
{
AbstractMaterialGraph m_Graph;
Dictionary<Guid, PreviewData> m_Previews = new Dictionary<Guid, PreviewData>();
Dictionary<Guid, PreviewRenderData> m_RenderDatas = new Dictionary<Guid, PreviewRenderData>();
Dictionary<Guid, PreviewShaderData> m_ShaderDatas = new Dictionary<Guid, PreviewShaderData>();
PreviewRenderData m_MasterRenderData;
HashSet<Guid> m_DirtyPreviews = new HashSet<Guid>();
HashSet<Guid> m_DirtyShaders = new HashSet<Guid>();
HashSet<Guid> m_TimeDependentPreviews = new HashSet<Guid>();

public PreviewRate previewRate { get; set; }
public PreviewRenderData masterRenderData
{
get { return m_MasterRenderData; }
}
public PreviewManager(AbstractMaterialGraph graph)
{
m_Graph = graph;

m_UberShader = ShaderUtil.CreateShaderAsset(k_EmptyShader);
m_UberShader.hideFlags = HideFlags.HideAndDontSave;
m_UberShaderIds = new Dictionary<Guid, int>();
m_MasterRenderData = new PreviewRenderData
{
renderTexture = new RenderTexture(400, 400, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default) { hideFlags = HideFlags.HideAndDontSave }
};
public PreviewData GetPreview(INode node)
public PreviewRenderData GetPreview(INode node)
return m_Previews[node.guid];
return m_RenderDatas[node.guid];
var previewData = new PreviewData
PreviewShaderData shaderData;
if (!m_ShaderDatas.TryGetValue(node.guid, out shaderData))
{
shaderData = new PreviewShaderData
{
node = node
};
m_ShaderDatas[node.guid] = shaderData;
}
var previewData = new PreviewRenderData
node = node,
renderTexture = new RenderTexture(256, 256, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default) { hideFlags = HideFlags.HideAndDontSave }
shaderData = shaderData,
renderTexture = new RenderTexture(200, 200, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default) { hideFlags = HideFlags.HideAndDontSave }
if (m_Previews.ContainsKey(node.guid))
if (m_RenderDatas.ContainsKey(node.guid))
m_Previews.Add(node.guid, previewData);
m_RenderDatas.Add(node.guid, previewData);
var masterNode = node as IMasterNode;
if (masterRenderData.shaderData == null && masterNode != null)
{
masterRenderData.shaderData = shaderData;
}
m_Previews.Remove(node.guid);
m_RenderDatas.Remove(node.guid);
if (masterRenderData.shaderData != null && masterRenderData.shaderData.node == node)
masterRenderData.shaderData = m_ShaderDatas.Values.FirstOrDefault(x => x.node is IMasterNode);
}
void OnNodeModified(INode node, ModificationScope scope)

m_DirtyShaders.Add(edge.inputSlot.nodeGuid);
}
List<PreviewData> m_RenderList2D = new List<PreviewData>();
List<PreviewData> m_RenderList3D = new List<PreviewData>();
List<PreviewRenderData> m_RenderList2D = new List<PreviewRenderData>();
List<PreviewRenderData> m_RenderList3D = new List<PreviewRenderData>();
HashSet<Guid> m_NodesWith3DPreview = new HashSet<Guid>();
public void RenderPreviews()

foreach (var node in uberNodes)
{
PreviewData previewData;
if (!m_Previews.TryGetValue(node.guid, out previewData))
PreviewShaderData shaderData;
if (!m_ShaderDatas.TryGetValue(node.guid, out shaderData))
previewData.previewMode = m_NodesWith3DPreview.Contains(node.guid) ? PreviewMode.Preview3D : PreviewMode.Preview2D;
previewData.shader = m_UberShader;
shaderData.previewMode = m_NodesWith3DPreview.Contains(node.guid) ? PreviewMode.Preview3D : PreviewMode.Preview2D;
shaderData.shader = m_UberShader;
}
i++;
EditorUtility.DisplayProgressBar("Shader Graph", string.Format("Compiling preview shaders ({0}/{1})", i, count), 0f);

foreach (var nodeGuid in m_DirtyPreviews)
{
PreviewData previewData;
if (!m_Previews.TryGetValue(nodeGuid, out previewData))
PreviewRenderData renderData;
if (!m_RenderDatas.TryGetValue(nodeGuid, out renderData))
if (previewData.shader == null)
if (renderData.shaderData.shader == null)
previewData.texture = null;
renderData.texture = null;
if (MaterialGraphAsset.ShaderHasError(previewData.shader))
if (MaterialGraphAsset.ShaderHasError(renderData.shaderData.shader))
previewData.texture = m_ErrorTexture;
renderData.texture = m_ErrorTexture;
if (previewData.previewMode == PreviewMode.Preview2D)
m_RenderList2D.Add(previewData);
if (renderData.shaderData.previewMode == PreviewMode.Preview2D)
m_RenderList2D.Add(renderData);
m_RenderList3D.Add(previewData);
m_RenderList3D.Add(renderData);
if (masterRenderData.shaderData != null && m_DirtyPreviews.Contains(masterRenderData.shaderData.node.guid))
m_RenderList3D.Add(masterRenderData);
var time = Time.realtimeSinceStartup;
EditorUtility.SetCameraAnimateMaterialsTime(m_SceneResources.camera, time);

m_SceneResources.camera.transform.rotation = Quaternion.identity;
m_SceneResources.camera.orthographicSize = 1;
m_SceneResources.camera.orthographic = true;
foreach (var previewData in m_RenderList2D)
foreach (var renderData in m_RenderList2D)
if (m_UberShaderIds.TryGetValue(previewData.node.guid, out outputId))
if (m_UberShaderIds.TryGetValue(renderData.shaderData.node.guid, out outputId))
m_PreviewMaterial.shader = previewData.shader;
m_SceneResources.camera.targetTexture = previewData.renderTexture;
m_PreviewMaterial.shader = renderData.shaderData.shader;
m_SceneResources.camera.targetTexture = renderData.renderTexture;
RenderTexture.active = previewData.renderTexture;
RenderTexture.active = renderData.renderTexture;
Graphics.Blit(Texture2D.whiteTexture, previewData.renderTexture, m_SceneResources.checkerboardMaterial);
Graphics.Blit(Texture2D.whiteTexture, renderData.renderTexture, m_SceneResources.checkerboardMaterial);
Graphics.DrawMesh(m_SceneResources.quad, Matrix4x4.identity, m_PreviewMaterial, 1, m_SceneResources.camera, 0, m_PreviewPropertyBlock, ShadowCastingMode.Off, false, null, false);
var previousUseSRP = Unsupported.useScriptableRenderPipeline;
Unsupported.useScriptableRenderPipeline = false;

previewData.texture = previewData.renderTexture;
renderData.texture = renderData.renderTexture;
m_RenderList2D.Clear();
// Render 3D previews
m_SceneResources.camera.transform.position = -Vector3.forward * 5;

{
int outputId;
if (m_UberShaderIds.TryGetValue(previewData.node.guid, out outputId))
if (m_UberShaderIds.TryGetValue(previewData.shaderData.node.guid, out outputId))
m_PreviewMaterial.shader = previewData.shader;
m_PreviewMaterial.shader = previewData.shaderData.shader;
m_SceneResources.camera.targetTexture = previewData.renderTexture;
var previousRenderTexure = RenderTexture.active;
RenderTexture.active = previewData.renderTexture;

Graphics.DrawMesh(mesh, Matrix4x4.TRS(-mesh.bounds.center, Quaternion.identity, Vector3.one), m_PreviewMaterial, 1, m_SceneResources.camera, 0, m_PreviewPropertyBlock, ShadowCastingMode.Off, false, null, false);
var previousUseSRP = Unsupported.useScriptableRenderPipeline;
Unsupported.useScriptableRenderPipeline = previewData.node is IMasterNode;
Unsupported.useScriptableRenderPipeline = previewData.shaderData.node is IMasterNode;
m_RenderList3D.Clear();
foreach (var nodeGuid in m_DirtyPreviews)
foreach (var previewRenderData in m_RenderList2D.Union(m_RenderList3D))
PreviewData previewData;
if (!m_Previews.TryGetValue(nodeGuid, out previewData))
continue;
if (previewData.onPreviewChanged != null)
previewData.onPreviewChanged();
if (previewRenderData.onPreviewChanged != null)
previewRenderData.onPreviewChanged();
m_RenderList2D.Clear();
m_RenderList3D.Clear();
m_DirtyPreviews.Clear();
}

if (node == null)
return;
PreviewData previewData;
if (!m_Previews.TryGetValue(nodeGuid, out previewData))
PreviewShaderData shaderData;
if (!m_ShaderDatas.TryGetValue(nodeGuid, out shaderData))
previewData.previewMode = m_NodesWith3DPreview.Contains(nodeGuid) ? PreviewMode.Preview3D : PreviewMode.Preview2D;
shaderData.previewMode = m_NodesWith3DPreview.Contains(nodeGuid) ? PreviewMode.Preview3D : PreviewMode.Preview2D;
previewData.shaderString = null;
shaderData.shaderString = null;
previewData.shaderString = m_Graph.GetPreviewShader(node, out mode);
if (node is IMasterNode)
{
List<PropertyCollector.TextureInfo> configuredTextures;
shaderData.shaderString = ((IMasterNode)node).GetShader(GenerationMode.Preview, node.name, out configuredTextures);
}
else
shaderData.shaderString = m_Graph.GetPreviewShader(node, out mode);
File.WriteAllText(Application.dataPath + "/../GeneratedShader.shader", (previewData.shaderString ?? "null").Replace("UnityEngine.MaterialGraph", "Generated"));
File.WriteAllText(Application.dataPath + "/../GeneratedShader.shader", (shaderData.shaderString ?? "null").Replace("UnityEngine.MaterialGraph", "Generated"));
if (string.IsNullOrEmpty(previewData.shaderString))
if (string.IsNullOrEmpty(shaderData.shaderString))
if (previewData.shader != null)
Object.DestroyImmediate(previewData.shader, true);
previewData.shader = null;
if (shaderData.shader != null)
Object.DestroyImmediate(shaderData.shader, true);
shaderData.shader = null;
if (previewData.shader != null && MaterialGraphAsset.ShaderHasError(previewData.shader))
if (shaderData.shader != null && MaterialGraphAsset.ShaderHasError(shaderData.shader))
ShaderUtil.ClearShaderErrors(previewData.shader);
Object.DestroyImmediate(previewData.shader, true);
previewData.shader = null;
ShaderUtil.ClearShaderErrors(shaderData.shader);
Object.DestroyImmediate(shaderData.shader, true);
shaderData.shader = null;
if (previewData.shader == null)
if (shaderData.shader == null)
previewData.shader = ShaderUtil.CreateShaderAsset(previewData.shaderString);
previewData.shader.hideFlags = HideFlags.HideAndDontSave;
shaderData.shader = ShaderUtil.CreateShaderAsset(shaderData.shaderString);
shaderData.shader.hideFlags = HideFlags.HideAndDontSave;
ShaderUtil.ClearShaderErrors(previewData.shader);
ShaderUtil.UpdateShaderAsset(previewData.shader, previewData.shaderString);
ShaderUtil.ClearShaderErrors(shaderData.shader);
ShaderUtil.UpdateShaderAsset(shaderData.shader, shaderData.shaderString);
var message = "RecreateShader: " + node.GetVariableNameForNode() + Environment.NewLine + previewData.shaderString;
if (MaterialGraphAsset.ShaderHasError(previewData.shader))
var message = "RecreateShader: " + node.GetVariableNameForNode() + Environment.NewLine + shaderData.shaderString;
if (MaterialGraphAsset.ShaderHasError(shaderData.shader))
void DestroyPreview(Guid nodeGuid, PreviewData previewData)
void DestroyPreview(Guid nodeGuid, PreviewRenderData previewRenderData)
if (m_Previews.Remove(nodeGuid))
if (m_RenderDatas.Remove(nodeGuid))
if (previewData.shader != null)
Object.DestroyImmediate(previewData.shader, true);
if (previewData.renderTexture != null)
Object.DestroyImmediate(previewData.renderTexture, true);
if (previewRenderData.shaderData.shader != null)
Object.DestroyImmediate(previewRenderData.shaderData.shader, true);
if (previewRenderData.renderTexture != null)
Object.DestroyImmediate(previewRenderData.renderTexture, true);
var node = m_Graph.GetNodeFromGuid(nodeGuid);
if (node != null)
node.onModified -= OnNodeModified;

previewData.shader = null;
previewData.renderTexture = null;
previewData.texture = null;
previewData.onPreviewChanged = null;
previewRenderData.shaderData.shader = null;
previewRenderData.renderTexture = null;
previewRenderData.texture = null;
previewRenderData.onPreviewChanged = null;
}
}

if (m_SceneResources != null)
m_SceneResources.Dispose();
m_SceneResources = null;
var previews = m_Previews.ToList();
var previews = m_RenderDatas.ToList();
foreach (var kvp in previews)
DestroyPreview(kvp.Key, kvp.Value);
}

public delegate void OnPreviewChanged();
public class PreviewData
public class PreviewShaderData
public Mesh mesh { get; set; }
}
public class PreviewRenderData
{
public PreviewShaderData shaderData { get; set; }
public Mesh mesh { get; set; }
public RenderTexture renderTexture { get; set; }
public Texture texture { get; set; }
public OnPreviewChanged onPreviewChanged;

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


var textureInfo = new List<PropertyCollector.TextureInfo>();
PreviewMode previewMode;
FloatShaderProperty outputIdProperty;
string shader = graph.GetShader(copyFromNode, GenerationMode.ForReals, assetName, out textureInfo, out previewMode, out outputIdProperty);
GUIUtility.systemCopyBuffer = shader;
if (copyFromNode is MasterNode)
{
var shader = ((MasterNode)copyFromNode).GetShader(GenerationMode.ForReals, copyFromNode.name, out textureInfo);
GUIUtility.systemCopyBuffer = shader;
}
else
{
string shader = graph.GetShader(copyFromNode, GenerationMode.ForReals, assetName, out textureInfo, out previewMode, out outputIdProperty);
GUIUtility.systemCopyBuffer = shader;
}
}
));

public void HandleGraphChanges()
{
previewManager.HandleGraphChanges();
previewManager.RenderPreviews();
inspectorView.HandleGraphChanges();
foreach (var node in m_Graph.removedNodes)
{
node.onModified -= OnNodeChanged;

{
var nodeView = new MaterialNodeView { userData = node };
m_GraphView.AddElement(nodeView);
nodeView.Initialize(m_GraphView, node as AbstractMaterialNode, m_PreviewManager);
nodeView.Initialize(node as AbstractMaterialNode, m_PreviewManager);
node.onModified += OnNodeChanged;
}

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


public sealed class MaterialNodeView : Node
{
List<VisualElement> m_ControlViews;
PreviewData m_PreviewData;
PreviewRenderData m_PreviewRenderData;
GraphView m_GraphView;
VisualElement m_ControlsDivider;
public void Initialize(GraphView graphView, AbstractMaterialNode inNode, PreviewManager previewManager)
public void Initialize(AbstractMaterialNode inNode, PreviewManager previewManager)
{
AddToClassList("MaterialNode");

m_GraphView = graphView;
node = inNode;
persistenceKey = node.guid.ToString();
UpdateTitle();

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

pickingMode = PickingMode.Ignore,
image = Texture2D.whiteTexture
};
m_PreviewData = previewManager.GetPreview(inNode);
m_PreviewData.onPreviewChanged += UpdatePreviewTexture;
m_PreviewRenderData = previewManager.GetPreview(inNode);
m_PreviewRenderData.onPreviewChanged += UpdatePreviewTexture;
m_PreviewContainer.Add(m_PreviewTextureView);
var collapsePreviewButton = new Label { name = "collapse", text = "▲" };
var collapsePreviewButton = new VisualElement { name = "collapse"};
collapsePreviewButton.Add(new VisualElement { name = "icon" });
collapsePreviewButton.AddManipulator(new Clickable(() =>
{
node.owner.owner.RegisterCompleteObjectUndo("Collapse Preview");

m_PreviewContainer.Add(collapsePreviewButton);
m_PreviewTextureView.Add(collapsePreviewButton);
var expandPreviewButton = new Label { name = "expand", text = "▼" };
var expandPreviewButton = new VisualElement { name = "expand"};
expandPreviewButton.Add(new VisualElement { name = "icon"});
expandPreviewButton.AddManipulator(new Clickable(() =>
{
node.owner.owner.RegisterCompleteObjectUndo("Expand Preview");

}
leftContainer.Add(m_PreviewContainer);
extensionContainer.Add(m_PreviewContainer);
}
m_ControlViews = new List<VisualElement>();

m_Attachers = new List<Attacher>(node.GetInputSlots<MaterialSlot>().Count());
expanded = node.drawState.expanded;
expanded = node.drawState.expanded;
RefreshExpandedState(); //This should not be needed. GraphView needs to improve the extension api here
UpdatePortInputVisibilities();
SetPosition(new Rect(node.drawState.position.x, node.drawState.position.y, 0, 0));

var resizeHandle = new Label { name = "resize", text = "" };
resizeHandle.AddManipulator(new Draggable(OnResize));
Add(resizeHandle);
UpdateSize();
}
}

UpdateControls();
UpdatePortInputVisibilities();
RefreshExpandedState(); //This should not be needed. GraphView needs to improve the extension api here
}
}

return;
if (expanded)
{
if (m_PreviewTextureView.parent != m_PreviewContainer)
{
m_PreviewContainer.Add(m_PreviewTextureView);
}
if (m_PreviewTextureView.parent == m_PreviewContainer)
{
m_PreviewTextureView.RemoveFromHierarchy();
}
m_PreviewContainer.RemoveFromClassList("expanded");
m_PreviewContainer.AddToClassList("collapsed");
}

{
inputContainer.Add(port);
var portInputView = new PortInputView(slot);
m_GraphView.AddElement(portInputView);
m_Attachers.Add(new Attacher(portInputView, port, SpriteAlignment.LeftCenter) { distance = 0f });
Add(portInputView);
m_Attachers.Add(new Attacher(portInputView, port, SpriteAlignment.LeftCenter) { distance = -8f });
}
}
}

void OnResize(Vector2 deltaSize)
{
var updatedWidth = leftContainer.layout.width + deltaSize.x;
var updatedWidth = topContainer.layout.width + deltaSize.x;
var updatedHeight = m_PreviewTextureView.layout.height + deltaSize.y;
var previewNode = node as PreviewNode;

void UpdatePreviewTexture()
{
if (m_PreviewData.texture == null || !node.previewExpanded)
if (m_PreviewRenderData.texture == null || !node.previewExpanded)
{
m_PreviewTextureView.visible = false;
m_PreviewTextureView.image = Texture2D.blackTexture;

m_PreviewTextureView.visible = true;
m_PreviewTextureView.AddToClassList("visible");
m_PreviewTextureView.RemoveFromClassList("hidden");
m_PreviewTextureView.image = m_PreviewData.texture;
if (m_PreviewTextureView.image != m_PreviewRenderData.texture)
m_PreviewTextureView.image = m_PreviewRenderData.texture;
else
m_PreviewTextureView.Dirty(ChangeType.Repaint);
m_PreviewTextureView.Dirty(ChangeType.Repaint);
}
void UpdateControls()

m_ControlsContainer.Clear();
m_ControlsDivider.RemoveFromHierarchy();
}
else if (m_ControlsContainer.childCount != m_ControlViews.Count)
{

extensionContainer.Add(m_ControlsDivider);
if (m_PreviewContainer != null)
m_ControlsDivider.PlaceBehind(m_PreviewContainer);
}
}

var width = previewNode.width;
var height = previewNode.height;
leftContainer.style.width = width;
m_PreviewTextureView.style.height = height;
}

m_Attachers.Clear();
node = null;
if (m_PreviewData != null)
if (m_PreviewRenderData != null)
m_PreviewData.onPreviewChanged -= UpdatePreviewTexture;
m_PreviewData = null;
m_PreviewRenderData.onPreviewChanged -= UpdatePreviewTexture;
m_PreviewRenderData = null;
}
}
}

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/PortInputView.cs


m_EdgeControl = new EdgeControl
{
@from = new Vector2(212f - 20f, 11.5f),
@from = new Vector2(212f - 21f, 11.5f),
edgeWidth = 2
edgeWidth = 2,
pickingMode = PickingMode.Ignore
clippingOptions = ClippingOptions.NoClipping;
m_Container.clippingOptions = ClippingOptions.ClipAndCacheContents;
}
protected override void OnStyleResolved(ICustomStyle styles)

5
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/Slots/MultiFloatSlotControlView.cs


void AddField(Vector4 initialValue, int index, string subLabel)
{
Add(new Label(subLabel));
var label = new Label(subLabel);
Add(label);
var dragger = new FieldMouseDragger<double>(doubleField);
dragger.SetDragZone(label);
doubleField.OnValueChanged(evt =>
{
var value = m_Get();

22
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Importers/ShaderGraphImporterEditor.cs


using System;
using UnityEditor.ShaderGraph;
using Debug = System.Diagnostics.Debug;
using Object = UnityEngine.Object;
[CustomEditor(typeof(ShaderGraphImporter))]
public class ShaderGraphImporterEditor : ScriptedImporterEditor

{
var guid = AssetDatabase.AssetPathToGUID(path);
var extension = Path.GetExtension(path);
Type graphType;
if (extension == ".ShaderGraph")
graphType = typeof(MaterialGraph);
else if (extension == ".LayeredShaderGraph")
graphType = typeof(LayeredShaderGraph);
else if (extension == ".ShaderSubGraph")
graphType = typeof(SubGraph);
else if (extension == ".ShaderRemapGraph")
graphType = typeof(MasterRemapGraph);
else
if (extension != ".ShaderGraph" && extension != ".LayeredShaderGraph" && extension != ".ShaderSubGraph" && extension != ".ShaderRemapGraph")
return false;
var foundWindow = false;

if (!foundWindow)
{
var window = ScriptableObject.CreateInstance<MaterialGraphEditWindow>();
var window = CreateInstance<MaterialGraphEditWindow>();
window.ChangeSelection(guid, graphType);
window.ChangeSelection(guid);
[OnOpenAsset]
[OnOpenAsset(0)]
}

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


background-color: rgb(20, 21, 21);
}
MaterialNodeView > .mainContainer > #left > #previewContainer {
width: 200;
MaterialNodeView #previewContainer,
MaterialNodeView #controls {
background-color: #393939;
MaterialNodeView > .mainContainer > #left > #previewContainer.expanded > #preview.active,
MaterialNodeView > .mainContainer > #left > #previewContainer.expanded > #preview.visible {
MaterialNodeView #previewContainer > #preview {
align-items:center;
MaterialNodeView > .mainContainer > #left > #previewContainer.collapsed > #collapse {
MaterialNodeView #previewContainer > #preview > #collapse {
background-color: #000;
border-color: #F0F0F0;
width: 0;
}
MaterialNodeView > .mainContainer > #left > #previewContainer.expanded > #collapse {
border-radius: 2;
text-alignment: middle-center;
position-left: 87;
position-right: 87;
position-top: 5;
position-type: absolute;
height: 0;
border-top-width: 0;
border-bottom-width: 0;
border-left-width: 0;
border-right-width: 0;
}
MaterialNodeView > .mainContainer > #left > #previewContainer.expanded:hover > #collapse {
background-color: rgba(0, 0, 0, 0.5);
text-color: rgba(255, 255, 255, 0.75);
border-color: rgba(255, 255, 255, 0.75);
opacity: 0;
border-radius: 1;
height: 26;
margin-top: 4;
align-items:center;
justify-content:center;
MaterialNodeView > .mainContainer > #left > #previewContainer.expanded > #collapse:hover {
background-color: rgba(0, 0, 0, 0.75);
text-color: rgba(255, 255, 255, 1);
border-color: rgba(255, 255, 255, 1);
MaterialNodeView #previewContainer:hover > #preview > #collapse {
width: 20;
height: 20;
opacity: 0.6;
MaterialNodeView > .mainContainer > #left > #previewContainer.expanded > #collapse:active {
background-color: rgba(0, 0, 0, 0.66);
MaterialNodeView #previewContainer > #preview > #collapse > #icon
{
background-image : resource("GraphView/Nodes/PreviewCollapse.png");
width: 16;
height: 16;
}
MaterialNodeView #previewContainer > #preview > #collapse:hover {
opacity: 1.0;
MaterialNodeView > .mainContainer > #left > #previewContainer.expanded > #expand {
MaterialNodeView #previewContainer.collapsed > #preview > #collapse {
MaterialNodeView > .mainContainer > #left > #previewContainer.collapsed > #expand {
text-alignment: middle-center;
text-color: rgb(153, 153, 153);
MaterialNodeView #previewContainer > #expand {
width: 50;
width: 56;
height: 16;
flex-direction: row;
justify-content:center;
}
MaterialNodeView #previewContainer > #expand > #icon {
align-self: center;
background-image : resource("GraphView/Nodes/PreviewExpand.png");
width: 16;
height: 16;
MaterialNodeView > .mainContainer > #left > #previewContainer.collapsed > #expand:hover {
background-color: rgba(0, 0, 0, 0.5);
text-color: rgba(255, 255, 255, 1);
MaterialNodeView #previewContainer.collapsed > #expand:hover {
background-color: #2B2B2B;
}
MaterialNodeView #previewContainer.expanded > #expand {
height: 0;
}
MaterialNodeView > #resize {

flex-direction: row;
align-items: center;
padding-left: 8;
margin-right: 10;
margin-right: 12;
border-left-width: 1;
border-top-width: 1;
border-right-width: 1;

MultiFloatSlotControlView > Label {
margin-left: 0;
margin-right: 0;
cursor: slide-arrow;
}
MultiFloatSlotControlView > DoubleField {

MultiFloatControlView {
flex-direction: row;
padding-left: 8;
padding-right: 8;
padding-top: 8;
padding-bottom: 8;
cursor: slide-arrow;
flex: 1;
min-width: 30;
flex-grow: 1;
}
ObjectControlView {

ObjectControlView > ObjectField {
flex: 1;
}
EnumControlView {
flex-direction: row;
}
EnumControlView > EnumField {
flex: 1;
margin-left: 0;
margin-right: 8;
margin-top: 8;
margin-bottom: 8;
}
EnumControlView > Label {
padding-left: 0;
padding-right: 0;
padding-top: 0;
padding-bottom: 0;
margin-left: 8;
margin-right: 8;
margin-top: 8;
margin-bottom: 8;
}
PropertyControlView {
padding-left: 8;
padding-right: 8;
padding-top: 8;
padding-bottom: 8;
}

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


SubShader
Pass
Tags{"RenderType" = "Opaque" "IgnoreProjectors" = "True" "RenderPipeline" = "LightweightPipeline"}
LOD ${LOD}
Tags{"LightMode" = "LightweightForward"}
${Tags}
${Blending}
${Culling}
${ZTest}
${ZWrite}
CGPROGRAM
#pragma target 3.0
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
#pragma multi_compile_fog
#pragma multi_compile_instancing
Pass
{
Tags{"LightMode" = "LightweightForward"}
${Tags}
${Blending}
${Culling}
${ZTest}
${ZWrite}
CGPROGRAM
#pragma target 3.0
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
#pragma multi_compile_fog
#pragma multi_compile_instancing
#pragma vertex vert
#pragma fragment frag
#pragma glsl
#pragma debug
#pragma vertex vert
#pragma fragment frag
#pragma glsl
#pragma debug
#include "UnityCG.cginc"
#include "UnityCG.cginc"
${Defines}
${Defines}
${Graph}
struct GraphVertexOutput
{
float4 position : POSITION;
${Interpolators}
UNITY_VERTEX_OUTPUT_STEREO
};
struct GraphVertexOutput
{
float4 position : POSITION;
${Interpolators}
UNITY_VERTEX_OUTPUT_STEREO
};
GraphVertexOutput vert (GraphVertexInput v)
{
v = PopulateVertexData(v);
UNITY_SETUP_INSTANCE_ID(v);
GraphVertexOutput vert (GraphVertexInput v)
{
v = PopulateVertexData(v);
UNITY_SETUP_INSTANCE_ID(v);
GraphVertexOutput o;
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.position = UnityObjectToClipPos(v.vertex);
${VertexShader}
return o;
}
GraphVertexOutput o;
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.position = UnityObjectToClipPos(v.vertex);
${VertexShader}
return o;
}
fixed4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}
SurfaceInputs surfaceInput;
${SurfaceInputs}
fixed4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}
SurfaceInputs surfaceInput;
${SurfaceInputs}
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float3 Color = 0;
float3 Alpha = 0;
${SurfaceOutputRemap}
#ifdef _ALPHABLEND_ON
return fixed4(Color, Alpha);
#else
return fixed4(Color, 1.0);
#endif
}
ENDCG
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float3 Color = 0;
float Alpha = 0;
${SurfaceOutputRemap}
return fixed4(Color, Alpha);
ENDCG
}

8
MaterialGraphProject/Assets/graphs_PartyPreview.mat


m_Texture: {fileID: 2800000, guid: 7296f51323ae9485a9c834c4e3d722ed, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Texture2D_8897CB1D_Tex:
- _Texture2D_3BDAFFBE_Tex:
m_Texture: {fileID: 2800000, guid: 7296f51323ae9485a9c834c4e3d722ed, type: 3}
m_Scale: {x: 1, y: 1}
m_Offset: {x: 0, y: 0}
- _Texture2D_43A49A96_Tex:
- Float_D2D9489B: 3
- Float_D2D9489B: 10
m_Colors: []

15
MaterialGraphProject/ProjectSettings/EditorSettings.asset


--- !u!159 &1
EditorSettings:
m_ObjectHideFlags: 0
serializedVersion: 5
m_ExternalVersionControlSupport: Visible Meta Files
serializedVersion: 7
m_ExternalVersionControlSupport: Hidden Meta Files
m_LineEndingsForNewScripts: 2
m_SpritePackerMode: 2
m_SpritePackerMode: 0
m_EtcTextureCompressorBehavior: 0
m_EtcTextureFastCompressor: 0
m_EtcTextureCompressorBehavior: 1
m_EtcTextureFastCompressor: 1
m_EtcTextureBestCompressor: 5
m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd;uss
m_EtcTextureBestCompressor: 4
m_ProjectGenerationIncludedExtensions: txt;xml;fnt;cd;asmdef;rsp
m_ProjectGenerationRootNamespace:
m_UserGeneratedProjectSuffix:
m_CollabEditorSettings:

2
MaterialGraphProject/ProjectSettings/GraphicsSettings.asset


m_PreloadedShaders: []
m_SpritesDefaultMaterial: {fileID: 10754, guid: 0000000000000000f000000000000000,
type: 0}
m_CustomRenderPipeline: {fileID: 11400000, guid: e6987eea1dd29074597d54ed91a54a26,
m_CustomRenderPipeline: {fileID: 11400000, guid: 9c068d834ef325345b87395bd103e074,
type: 2}
m_TransparencySortMode: 0
m_TransparencySortAxis: {x: 0, y: 0, z: 1}

2
MaterialGraphProject/ProjectSettings/ProjectVersion.txt


m_EditorVersion: 2018.1.0a6
m_EditorVersion: 2018.1.0a7

5
MaterialGraphProject/UnityPackageManager/manifest.json


{
"registry": "https://staging-packages.unity.com",
"com.unity.render-pipelines.core" : "0.1.11",
"com.unity.render-pipelines.lightweight" : "0.1.11"
}
}

2
MaterialGraphProject/Assets/UnityShaderEditor/Editor/LightWeightShaderPaths.cs.meta


fileFormatVersion: 2
guid: d31e09c69e37abe4f862a481501681be
guid: cddd8645d2052584eaee32f4bfc5cc0b
MonoImporter:
externalObjects: {}
serializedVersion: 2

46
MaterialGraphProject/Assets/UnityShaderEditor/Editor/SerializableGraph/Implementation/NodeUtils.cs


if (node == null)
return;
using (var stackDisposable = StackPool<INode>.GetDisposable())
using (var queueDisposable = QueuePool<INode>.GetDisposable())
{
var stack = stackDisposable.value;
var queue = queueDisposable.value;
queue.Enqueue(node);
// already added this node
if (nodeList.Contains(node))
return;
while (queue.Any())
{
var fromNode = queue.Dequeue();
// already added this node
if (nodeList.Contains(fromNode))
continue;
foreach (var slot in fromNode.GetInputSlots<ISlot>())
{
if (slotIds != null && !slotIds.Contains(slot.id))
continue;
var ids = node.GetInputSlots<ISlot>().Select(x => x.id);
if (slotIds != null)
ids = node.GetInputSlots<ISlot>().Where(x => slotIds.Contains(x.id)).Select(x => x.id);
foreach (var edge in fromNode.owner.GetEdges(fromNode.GetSlotReference(slot.id)))
{
var outputNode = fromNode.owner.GetNodeFromGuid(edge.outputSlot.nodeGuid);
queue.Enqueue(outputNode);
stack.Push(outputNode);
}
}
foreach (var slot in ids)
{
foreach (var edge in node.owner.GetEdges(node.GetSlotReference(slot)))
{
var outputNode = node.owner.GetNodeFromGuid(edge.outputSlot.nodeGuid);
DepthFirstCollectNodesFromNode(nodeList, outputNode);
}
while (stack.Any())
nodeList.Add(stack.Pop());
if (includeSelf == IncludeSelf.Include)
nodeList.Add(node);
}
if (includeSelf == IncludeSelf.Include)
nodeList.Add(node);
}
public static void CollectNodesNodeFeedsInto(List<INode> nodeList, INode node, IncludeSelf includeSelf = IncludeSelf.Include)

33
MaterialGraphProject/Assets/LightweightAsset.asset


%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_PrefabParentObject: {fileID: 0}
m_PrefabInternal: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: bf2edee5c58d82540a51f03df9d42094, type: 3}
m_Name: LightweightAsset
m_EditorClassIdentifier:
m_MaxPixelLights: 4
m_SupportsVertexLight: 0
m_SupportSoftParticles: 0
m_MSAA: 4
m_RenderScale: 1
m_ShadowType: 1
m_ShadowAtlasResolution: 1024
m_ShadowNearPlaneOffset: 2
m_ShadowDistance: 50
m_ShadowCascades: 1
m_Cascade2Split: 0.25
m_Cascade4Split: {x: 0.067, y: 0.2, z: 0.467}
m_DefaultShader: {fileID: 4800000, guid: 933532a4fcc9baf4fa0491de14d08ed7, type: 3}
m_BlitShader: {fileID: 4800000, guid: c17132b1f77d20942aa75f8429c0f8bc, type: 3}
m_CopyDepthShader: {fileID: 4800000, guid: d6dae50ee9e1bfa4db75f19f99355220, type: 3}
m_DefaultMaterial: {fileID: 2100000, guid: 31321ba15b8f8eb4c954353edc038b1d, type: 2}
m_DefaultParticleMaterial: {fileID: 2100000, guid: e823cd5b5d27c0f4b8256e7c12ee3e6d,
type: 2}
m_DefaultTerrainMaterial: {fileID: 2100000, guid: 594ea882c5a793440b60ff72d896021e,
type: 2}

8
MaterialGraphProject/Assets/LightweightAsset.asset.meta


fileFormatVersion: 2
guid: 9c068d834ef325345b87395bd103e074
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:

4
MaterialGraphProject/Assets/UnityShaderEditor/.npmignore


/Editor/Testing*
/.collabignore
/.gitignore
/.gitmodules

79
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/CubemapInputMaterialSlot.cs


using System;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Slots;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
namespace UnityEditor.ShaderGraph
{
[Serializable]
public class CubemapInputMaterialSlot : CubemapMaterialSlot
{
[SerializeField]
private SerializableCubemap m_Cubemap = new SerializableCubemap();
public Cubemap cubemap
{
get { return m_Cubemap.cubemap; }
set { m_Cubemap.cubemap = value; }
}
public CubemapInputMaterialSlot()
{}
public CubemapInputMaterialSlot(
int slotId,
string displayName,
string shaderOutputName,
ShaderStage shaderStage = ShaderStage.Dynamic,
bool hidden = false)
: base(slotId, displayName, shaderOutputName, SlotType.Input, shaderStage, hidden)
{}
public override VisualElement InstantiateControl()
{
return new CubemapSlotControlView(this);
}
public override string GetDefaultValue(GenerationMode generationMode)
{
var matOwner = owner as AbstractMaterialNode;
if (matOwner == null)
throw new Exception(string.Format("Slot {0} either has no owner, or the owner is not a {1}", this, typeof(AbstractMaterialNode)));
return matOwner.GetVariableNameForSlot(id);
}
public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode)
{
var matOwner = owner as AbstractMaterialNode;
if (matOwner == null)
throw new Exception(string.Format("Slot {0} either has no owner, or the owner is not a {1}", this, typeof(AbstractMaterialNode)));
var prop = new CubemapShaderProperty();
prop.overrideReferenceName = matOwner.GetVariableNameForSlot(id);
prop.modifiable = false;
prop.generatePropertyBlock = true;
prop.value.cubemap = cubemap;
properties.AddShaderProperty(prop);
}
public override PreviewProperty GetPreviewProperty(string name)
{
var pp = new PreviewProperty
{
m_Name = name,
m_PropType = PropertyType.Cubemap,
m_Cubemap = cubemap
};
return pp;
}
public override void CopyValuesFrom(MaterialSlot foundSlot)
{
var slot = foundSlot as CubemapInputMaterialSlot;
if (slot != null)
m_Cubemap = slot.m_Cubemap;
}
}
}

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


fileFormatVersion: 2
guid: 7b961f6f7e2617446afb6a8e329d84d4
timeCreated: 1509276977

31
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/CubemapMaterialSlot.cs


using System;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Serializable]
public class CubemapMaterialSlot : MaterialSlot
{
public CubemapMaterialSlot()
{}
public CubemapMaterialSlot(
int slotId,
string displayName,
string shaderOutputName,
SlotType slotType,
ShaderStage shaderStage = ShaderStage.Dynamic,
bool hidden = false)
: base(slotId, displayName, shaderOutputName, slotType, shaderStage, hidden)
{}
public override SlotValueType valueType { get { return SlotValueType.Cubemap; } }
public override ConcreteSlotValueType concreteValueType { get { return ConcreteSlotValueType.Cubemap; } }
public override void AddDefaultProperty(PropertyCollector properties, GenerationMode generationMode)
{}
public override void CopyValuesFrom(MaterialSlot foundSlot)
{}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/CubemapMaterialSlot.cs.meta


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

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


using System;
using System.Text;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Serializable]
public class CubemapShaderProperty : AbstractShaderProperty<SerializableCubemap>
{
[SerializeField]
private bool m_Modifiable = true;
public CubemapShaderProperty()
{
value = new SerializableCubemap();
displayName = "Cubemap";
}
public override PropertyType propertyType
{
get { return PropertyType.Cubemap; }
}
public bool modifiable
{
get { return m_Modifiable; }
set { m_Modifiable = value; }
}
public override Vector4 defaultValue
{
get { return new Vector4(); }
}
public override string GetPropertyBlockString()
{
var result = new StringBuilder();
if (!m_Modifiable)
{
result.Append("[NonModifiableTextureData] ");
}
result.Append("[NoScaleOffset] ");
result.Append(referenceName);
result.Append("(\"");
result.Append(displayName);
result.Append("\", CUBE) = \"\" {}");
return result.ToString();
}
public override string GetPropertyDeclarationString()
{
return "samplerCUBE " + referenceName + ";";
}
public override PreviewProperty GetPreviewMaterialProperty()
{
return new PreviewProperty()
{
m_Name = referenceName,
m_PropType = PropertyType.Cubemap,
m_Cubemap = value.cubemap
};
}
}
}

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


fileFormatVersion: 2
guid: ca5ddce766d5ae24f8be282b4f7a21bd
timeCreated: 1505346949

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


using System;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Serializable]
public class SerializableCubemap
{
[SerializeField]
private string m_SerializedCubemap;
[Serializable]
private class CubemapHelper
{
public Cubemap cubemap;
}
public Cubemap cubemap
{
get
{
if (string.IsNullOrEmpty(m_SerializedCubemap))
return null;
var cube = new CubemapHelper();
EditorJsonUtility.FromJsonOverwrite(m_SerializedCubemap, cube);
return cube.cubemap;
}
set
{
if (cubemap == value)
return;
var cube = new CubemapHelper();
cube.cubemap = value;
m_SerializedCubemap = EditorJsonUtility.ToJson(cube, true);
}
}
}
}

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


fileFormatVersion: 2
guid: 01e80e004e94f5e48ad1cb83d5701300
timeCreated: 1505346945

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


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
public class LightWeightPBRSubShader
{
Pass m_ForwardPassMetallic = new Pass()
{
Name = "LightweightForward",
PixelShaderSlots = new List<int>()
{
PBRMasterNode.AlbedoSlotId,
PBRMasterNode.NormalSlotId,
PBRMasterNode.EmissionSlotId,
PBRMasterNode.MetallicSlotId,
PBRMasterNode.SmoothnessSlotId,
PBRMasterNode.OcclusionSlotId,
PBRMasterNode.AlphaSlotId
}
};
struct Pass
{
public string Name;
public List<int> VertexShaderSlots;
public List<int> PixelShaderSlots;
}
Pass m_ForwardPassSpecular = new Pass()
{
Name = "LightweightForward",
PixelShaderSlots = new List<int>()
{
PBRMasterNode.AlbedoSlotId,
PBRMasterNode.NormalSlotId,
PBRMasterNode.EmissionSlotId,
PBRMasterNode.SpecularSlotId,
PBRMasterNode.SmoothnessSlotId,
PBRMasterNode.OcclusionSlotId,
PBRMasterNode.AlphaSlotId
}
};
private static string GetShaderPassFromTemplate(string template, PBRMasterNode masterNode, Pass pass, GenerationMode mode, SurfaceMaterialOptions materialOptions)
{
var surfaceVertexShader = new ShaderGenerator();
var surfaceDescriptionFunction = new ShaderGenerator();
var surfaceDescriptionStruct = new ShaderGenerator();
var shaderFunctionVisitor = new ShaderGenerator();
var surfaceInputs = new ShaderGenerator();
var shaderProperties = new PropertyCollector();
var graphVertexInput = @"
struct GraphVertexInput
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 tangent : TANGENT;
float4 color : COLOR;
float4 texcoord0 : TEXCOORD0;
float4 lightmapUV : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
};";
surfaceInputs.AddShaderChunk("struct SurfaceInputs{", false);
surfaceInputs.Indent();
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots);
var requirements = AbstractMaterialGraph.GetRequirements(activeNodeList);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresNormal, InterpolatorType.Normal, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresTangent, InterpolatorType.Tangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresBitangent, InterpolatorType.BiTangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresViewDir, InterpolatorType.ViewDirection, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresPosition, InterpolatorType.Position, surfaceInputs);
if (requirements.requiresVertexColor)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.VertexColor), false);
if (requirements.requiresScreenPosition)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.ScreenPosition), false);
foreach (var channel in requirements.requiresMeshUVs.Distinct())
surfaceInputs.AddShaderChunk(string.Format("half4 {0};", channel.GetUVName()), false);
surfaceInputs.Deindent();
surfaceInputs.AddShaderChunk("};", false);
surfaceVertexShader.AddShaderChunk("GraphVertexInput PopulateVertexData(GraphVertexInput v){", false);
surfaceVertexShader.Indent();
surfaceVertexShader.AddShaderChunk("return v;", false);
surfaceVertexShader.Deindent();
surfaceVertexShader.AddShaderChunk("}", false);
var slots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
slots.Add(masterNode.FindSlot<MaterialSlot>(id));
AbstractMaterialGraph.GenerateSurfaceDescriptionStruct(surfaceDescriptionStruct, slots, true);
var usedSlots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
usedSlots.Add(masterNode.FindSlot<MaterialSlot>(id));
AbstractMaterialGraph.GenerateSurfaceDescription(
activeNodeList,
masterNode,
masterNode.owner as AbstractMaterialGraph,
surfaceDescriptionFunction,
shaderFunctionVisitor,
shaderProperties,
requirements,
mode,
"PopulateSurfaceData",
"SurfaceDescription",
null,
null,
usedSlots);
var graph = new ShaderGenerator();
graph.AddShaderChunk(shaderFunctionVisitor.GetShaderString(2), false);
graph.AddShaderChunk(graphVertexInput, false);
graph.AddShaderChunk(surfaceInputs.GetShaderString(2), false);
graph.AddShaderChunk(surfaceDescriptionStruct.GetShaderString(2), false);
graph.AddShaderChunk(shaderProperties.GetPropertiesDeclaration(2), false);
graph.AddShaderChunk(surfaceVertexShader.GetShaderString(2), false);
graph.AddShaderChunk(surfaceDescriptionFunction.GetShaderString(2), false);
var blendingVisitor = new ShaderGenerator();
var cullingVisitor = new ShaderGenerator();
var zTestVisitor = new ShaderGenerator();
var zWriteVisitor = new ShaderGenerator();
materialOptions.GetBlend(blendingVisitor);
materialOptions.GetCull(cullingVisitor);
materialOptions.GetDepthTest(zTestVisitor);
materialOptions.GetDepthWrite(zWriteVisitor);
var interpolators = new ShaderGenerator();
var localVertexShader = new ShaderGenerator();
var localPixelShader = new ShaderGenerator();
var localSurfaceInputs = new ShaderGenerator();
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,
10,
interpolators,
localVertexShader,
localPixelShader,
localSurfaceInputs,
requirements,
reqs,
CoordinateSpace.World);
ShaderGenerator defines = new ShaderGenerator();
if (masterNode.IsSlotConnected(PBRMasterNode.NormalSlotId))
defines.AddShaderChunk("#define _NORMALMAP 1", true);
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;
case PBRMasterNode.AlphaMode.Clip:
defines.AddShaderChunk("#define _AlphaClip 1", true);
break;
}
var templateLocation = ShaderGenerator.GetTemplatePath(template);
foreach (var slot in usedSlots)
{
surfaceOutputRemap.AddShaderChunk(slot.shaderOutputName
+ " = surf."
+ slot.shaderOutputName + ";", true);
}
if (!File.Exists(templateLocation))
return string.Empty;
var subShaderTemplate = File.ReadAllText(templateLocation);
var resultPass = subShaderTemplate.Replace("${Defines}", defines.GetShaderString(3));
resultPass = resultPass.Replace("${Graph}", graph.GetShaderString(3));
resultPass = resultPass.Replace("${Interpolators}", interpolators.GetShaderString(3));
resultPass = resultPass.Replace("${VertexShader}", localVertexShader.GetShaderString(3));
resultPass = resultPass.Replace("${LocalPixelShader}", localPixelShader.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceInputs}", localSurfaceInputs.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceOutputRemap}", surfaceOutputRemap.GetShaderString(3));
resultPass = resultPass.Replace("${Tags}", string.Empty);
resultPass = resultPass.Replace("${Blending}", blendingVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${Culling}", cullingVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${ZTest}", zTestVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${ZWrite}", zWriteVisitor.GetShaderString(2));
return resultPass;
}
public IEnumerable<string> GetSubshader(PBRMasterNode masterNode, GenerationMode mode)
{
var subShader = new ShaderGenerator();
subShader.AddShaderChunk("SubShader", true);
subShader.AddShaderChunk("{", true);
subShader.Indent();
subShader.AddShaderChunk("Tags{ \"RenderPipeline\" = \"LightweightPipeline\"}", true);
var materialOptions = new SurfaceMaterialOptions();
switch (masterNode.alphaMode)
{
case PBRMasterNode.AlphaMode.Overwrite:
case PBRMasterNode.AlphaMode.Clip:
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 tagsVisitor = new ShaderGenerator();
materialOptions.GetTags(tagsVisitor);
subShader.AddShaderChunk(tagsVisitor.GetShaderString(0), true);
subShader.AddShaderChunk(
GetShaderPassFromTemplate(
"lightweightPBRForwardPass.template",
masterNode,
masterNode.model == PBRMasterNode.Model.Metallic ? m_ForwardPassMetallic : m_ForwardPassSpecular,
mode,
materialOptions),
true);
var extraPassesTemplateLocation = ShaderGenerator.GetTemplatePath("lightweightPBRExtraPasses.template");
if (File.Exists(extraPassesTemplateLocation))
subShader.AddShaderChunk(File.ReadAllText(extraPassesTemplateLocation), true);
subShader.Deindent();
subShader.AddShaderChunk("}", true);
return new[] { subShader.GetShaderString(0) };
}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs.meta


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

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


using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
public class LightWeightUnlitSubShader
{
Pass m_UnlitPass = new Pass()
{
Name = "Unlit",
PixelShaderSlots = new List<int>()
{
UnlitMasterNode.ColorSlotId,
UnlitMasterNode.AlphaSlotId
}
};
struct Pass
{
public string Name;
public List<int> VertexShaderSlots;
public List<int> PixelShaderSlots;
}
private static string GetShaderPassFromTemplate(string template, UnlitMasterNode masterNode, Pass pass, GenerationMode mode)
{
var surfaceVertexShader = new ShaderGenerator();
var surfaceDescriptionFunction = new ShaderGenerator();
var surfaceDescriptionStruct = new ShaderGenerator();
var shaderFunctionVisitor = new ShaderGenerator();
var surfaceInputs = new ShaderGenerator();
var shaderProperties = new PropertyCollector();
var graphVertexInput = @"
struct GraphVertexInput
{
float4 vertex : POSITION;
float3 normal : NORMAL;
float4 tangent : TANGENT;
float4 color : COLOR;
float4 texcoord0 : TEXCOORD0;
float4 lightmapUV : TEXCOORD1;
UNITY_VERTEX_INPUT_INSTANCE_ID
};";
surfaceInputs.AddShaderChunk("struct SurfaceInputs{", false);
surfaceInputs.Indent();
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, masterNode, NodeUtils.IncludeSelf.Include, pass.PixelShaderSlots);
var requirements = AbstractMaterialGraph.GetRequirements(activeNodeList);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresNormal, InterpolatorType.Normal, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresTangent, InterpolatorType.Tangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresBitangent, InterpolatorType.BiTangent, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresViewDir, InterpolatorType.ViewDirection, surfaceInputs);
ShaderGenerator.GenerateSpaceTranslationSurfaceInputs(requirements.requiresPosition, InterpolatorType.Position, surfaceInputs);
if (requirements.requiresVertexColor)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.VertexColor), false);
if (requirements.requiresScreenPosition)
surfaceInputs.AddShaderChunk(string.Format("float4 {0};", ShaderGeneratorNames.ScreenPosition), false);
foreach (var channel in requirements.requiresMeshUVs.Distinct())
surfaceInputs.AddShaderChunk(string.Format("half4 {0};", channel.GetUVName()), false);
surfaceInputs.Deindent();
surfaceInputs.AddShaderChunk("};", false);
surfaceVertexShader.AddShaderChunk("GraphVertexInput PopulateVertexData(GraphVertexInput v){", false);
surfaceVertexShader.Indent();
surfaceVertexShader.AddShaderChunk("return v;", false);
surfaceVertexShader.Deindent();
surfaceVertexShader.AddShaderChunk("}", false);
var slots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
{
var slot = masterNode.FindSlot<MaterialSlot>(id);
if (slot != null)
slots.Add(slot);
}
AbstractMaterialGraph.GenerateSurfaceDescriptionStruct(surfaceDescriptionStruct, slots, true);
var usedSlots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
usedSlots.Add(masterNode.FindSlot<MaterialSlot>(id));
AbstractMaterialGraph.GenerateSurfaceDescription(
activeNodeList,
masterNode,
masterNode.owner as AbstractMaterialGraph,
surfaceDescriptionFunction,
shaderFunctionVisitor,
shaderProperties,
requirements,
mode,
"PopulateSurfaceData",
"SurfaceDescription",
null,
null,
usedSlots);
var graph = new ShaderGenerator();
graph.AddShaderChunk(shaderFunctionVisitor.GetShaderString(2), false);
graph.AddShaderChunk(graphVertexInput, false);
graph.AddShaderChunk(surfaceInputs.GetShaderString(2), false);
graph.AddShaderChunk(surfaceDescriptionStruct.GetShaderString(2), false);
graph.AddShaderChunk(shaderProperties.GetPropertiesDeclaration(2), false);
graph.AddShaderChunk(surfaceVertexShader.GetShaderString(2), false);
graph.AddShaderChunk(surfaceDescriptionFunction.GetShaderString(2), false);
var tagsVisitor = new ShaderGenerator();
var blendingVisitor = new ShaderGenerator();
var cullingVisitor = new ShaderGenerator();
var zTestVisitor = new ShaderGenerator();
var zWriteVisitor = new ShaderGenerator();
var materialOptions = new SurfaceMaterialOptions();
materialOptions.GetTags(tagsVisitor);
materialOptions.GetBlend(blendingVisitor);
materialOptions.GetCull(cullingVisitor);
materialOptions.GetDepthTest(zTestVisitor);
materialOptions.GetDepthWrite(zWriteVisitor);
var interpolators = new ShaderGenerator();
var localVertexShader = new ShaderGenerator();
var localPixelShader = new ShaderGenerator();
var localSurfaceInputs = new ShaderGenerator();
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,
10,
interpolators,
localVertexShader,
localPixelShader,
localSurfaceInputs,
requirements,
reqs,
CoordinateSpace.World);
ShaderGenerator defines = new ShaderGenerator();
var templateLocation = ShaderGenerator.GetTemplatePath(template);
foreach (var slot in usedSlots)
{
surfaceOutputRemap.AddShaderChunk(slot.shaderOutputName
+ " = surf."
+ slot.shaderOutputName + ";", true);
}
if (!File.Exists(templateLocation))
return string.Empty;
var subShaderTemplate = File.ReadAllText(templateLocation);
var resultPass = subShaderTemplate.Replace("${Defines}", defines.GetShaderString(3));
resultPass = resultPass.Replace("${Graph}", graph.GetShaderString(3));
resultPass = resultPass.Replace("${Interpolators}", interpolators.GetShaderString(3));
resultPass = resultPass.Replace("${VertexShader}", localVertexShader.GetShaderString(3));
resultPass = resultPass.Replace("${LocalPixelShader}", localPixelShader.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceInputs}", localSurfaceInputs.GetShaderString(3));
resultPass = resultPass.Replace("${SurfaceOutputRemap}", surfaceOutputRemap.GetShaderString(3));
resultPass = resultPass.Replace("${Tags}", tagsVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${Blending}", blendingVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${Culling}", cullingVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${ZTest}", zTestVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${ZWrite}", zWriteVisitor.GetShaderString(2));
resultPass = resultPass.Replace("${LOD}", "" + materialOptions.lod);
return resultPass;
}
public IEnumerable<string> GetSubshader(UnlitMasterNode masterNode, GenerationMode mode)
{
var subShader = new ShaderGenerator();
subShader.AddShaderChunk("SubShader", true);
subShader.AddShaderChunk("{", true);
subShader.Indent();
subShader.AddShaderChunk("Tags{ \"RenderType\" = \"Opaque\" \"RenderPipeline\" = \"LightweightPipeline\"}", true);
subShader.AddShaderChunk(
GetShaderPassFromTemplate(
"lightweightUnlitPass.template",
masterNode,
m_UnlitPass,
mode),
true);
subShader.Deindent();
subShader.AddShaderChunk("}", true);
return new[] { subShader.GetShaderString(0) };
}
}
}

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


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

165
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/PBRMasterNode.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Serializable]
[Title("Master/PBR")]
public class PBRMasterNode : MasterNode
{
public const string AlbedoSlotName = "Albedo";
public const string NormalSlotName = "Normal";
public const string EmissionSlotName = "Emission";
public const string MetallicSlotName = "Metallic";
public const string SpecularSlotName = "Specular";
public const string SmoothnessSlotName = "Smoothness";
public const string OcclusionSlotName = "Occlusion";
public const string AlphaSlotName = "Alpha";
public const string VertexOffsetName = "VertexPosition";
public const int AlbedoSlotId = 0;
public const int NormalSlotId = 1;
public const int MetallicSlotId = 2;
public const int SpecularSlotId = 3;
public const int EmissionSlotId = 4;
public const int SmoothnessSlotId = 5;
public const int OcclusionSlotId = 6;
public const int AlphaSlotId = 7;
public enum Model
{
Specular,
Metallic
}
public enum AlphaMode
{
Overwrite,
AlphaBlend,
AdditiveBlend,
Clip
}
[SerializeField]
private Model m_Model = Model.Metallic;
[EnumControl("")]
public Model model
{
get { return m_Model; }
set
{
if (m_Model == value)
return;
m_Model = value;
UpdateNodeAfterDeserialization();
if (onModified != null)
{
onModified(this, ModificationScope.Topological);
}
}
}
[SerializeField]
private AlphaMode m_AlphaMode;
[EnumControl("")]
public AlphaMode alphaMode
{
get { return m_AlphaMode; }
set
{
if (m_AlphaMode == value)
return;
m_AlphaMode = value;
if (onModified != null)
{
onModified(this, ModificationScope.Graph);
}
}
}
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()
{
name = "PBR Master";
AddSlot(new Vector3MaterialSlot(AlbedoSlotId, AlbedoSlotName, AlbedoSlotName, SlotType.Input, new Vector4(0.5f, 0.5f, 0.5f), ShaderStage.Fragment));
AddSlot(new Vector3MaterialSlot(NormalSlotId, NormalSlotName, NormalSlotName, SlotType.Input, new Vector3(0, 0, 1), ShaderStage.Fragment));
AddSlot(new Vector3MaterialSlot(EmissionSlotId, EmissionSlotName, EmissionSlotName, SlotType.Input, Vector3.zero, ShaderStage.Fragment));
if (model == Model.Metallic)
AddSlot(new Vector1MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input, 0, ShaderStage.Fragment));
else
AddSlot(new Vector3MaterialSlot(SpecularSlotId, SpecularSlotName, SpecularSlotName, SlotType.Input, Vector3.zero, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0.5f, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(OcclusionSlotId, OcclusionSlotName, OcclusionSlotName, SlotType.Input, 1f, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1f, ShaderStage.Fragment));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
model == Model.Metallic ? MetallicSlotId : SpecularSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId
});
}
public override string GetShader(GenerationMode mode, string outputName, out List<PropertyCollector.TextureInfo> configuredTextures)
{
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, this);
var shaderProperties = new PropertyCollector();
var abstractMaterialGraph = owner as AbstractMaterialGraph;
if (abstractMaterialGraph != null)
abstractMaterialGraph.CollectShaderProperties(shaderProperties, mode);
foreach (var activeNode in activeNodeList.OfType<AbstractMaterialNode>())
activeNode.CollectShaderProperties(shaderProperties, mode);
var finalShader = new ShaderGenerator();
finalShader.AddShaderChunk(string.Format(@"Shader ""{0}""", outputName), false);
finalShader.AddShaderChunk("{", false);
finalShader.Indent();
finalShader.AddShaderChunk("Properties", false);
finalShader.AddShaderChunk("{", false);
finalShader.Indent();
finalShader.AddShaderChunk(shaderProperties.GetPropertiesBlock(2), false);
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);
var lwSub = new LightWeightPBRSubShader();
foreach (var subshader in lwSub.GetSubshader(this, mode))
finalShader.AddShaderChunk(subshader, true);
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);
configuredTextures = shaderProperties.GetConfiguredTexutres();
return finalShader.GetShaderString(0);
}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/PBRMasterNode.cs.meta


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

79
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/UnlitMasterNode.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Serializable]
[Title("Master/Unlit")]
public class UnlitMasterNode : MasterNode
{
public const string ColorSlotName = "Color";
public const string AlphaSlotName = "Alpha";
public const string VertexOffsetName = "VertexPosition";
public const int ColorSlotId = 0;
public const int AlphaSlotId = 7;
public UnlitMasterNode()
{
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
name = "Unlit Master";
AddSlot(new Vector3MaterialSlot(ColorSlotId, ColorSlotName, ColorSlotName, SlotType.Input, new Vector3(0.5f, 0.5f, 0.5f), ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 1, ShaderStage.Fragment));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
ColorSlotId,
AlphaSlotId
});
}
public override string GetShader(GenerationMode mode, string outputName, out List<PropertyCollector.TextureInfo> configuredTextures)
{
var activeNodeList = ListPool<INode>.Get();
NodeUtils.DepthFirstCollectNodesFromNode(activeNodeList, this);
var shaderProperties = new PropertyCollector();
var abstractMaterialGraph = owner as AbstractMaterialGraph;
if (abstractMaterialGraph != null)
abstractMaterialGraph.CollectShaderProperties(shaderProperties, mode);
foreach (var activeNode in activeNodeList.OfType<AbstractMaterialNode>())
activeNode.CollectShaderProperties(shaderProperties, mode);
var finalShader = new ShaderGenerator();
finalShader.AddShaderChunk(string.Format(@"Shader ""{0}""", outputName), false);
finalShader.AddShaderChunk("{", false);
finalShader.Indent();
finalShader.AddShaderChunk("Properties", false);
finalShader.AddShaderChunk("{", false);
finalShader.Indent();
finalShader.AddShaderChunk(shaderProperties.GetPropertiesBlock(2), false);
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);
var lwSub = new LightWeightUnlitSubShader();
foreach (var subshader in lwSub.GetSubshader(this, mode))
finalShader.AddShaderChunk(subshader, true);
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);
configuredTextures = shaderProperties.GetConfiguredTexutres();
return finalShader.GetShaderString(0);
}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/UnlitMasterNode.cs.meta


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

166
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/ChannelMixerNode.cs


using System;
using System.Collections.Generic;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Title("Artistic/Adjustment/Channel Mixer")]
public class ChannelMixerNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction
{
public ChannelMixerNode()
{
name = "Channel Mixer";
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_ChannelMixer_" + precision;
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Vector3MaterialSlot(InputSlotId, kInputSlotName, kInputSlotName, SlotType.Input, Vector3.zero));
AddSlot(new Vector3MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector3.zero));
RemoveSlotsNameNotMatching(new[] { InputSlotId, OutputSlotId });
}
[SerializeField]
ChannelMixer m_ChannelMixer = new ChannelMixer( new Vector3(1, 0, 0), new Vector3(0, 1, 0), new Vector3(0, 0, 1));
[Serializable]
public struct ChannelMixer
{
public Vector3 outRed;
public Vector3 outGreen;
public Vector3 outBlue;
public ChannelMixer(Vector3 red, Vector3 green, Vector3 blue)
{
outRed = red;
outGreen = green;
outBlue = blue;
}
}
[ChannelMixerControl("")]
public ChannelMixer channelMixer
{
get { return m_ChannelMixer; }
set
{
if ((value.outRed == m_ChannelMixer.outRed) && (value.outGreen == m_ChannelMixer.outGreen) && (value.outBlue == m_ChannelMixer.outBlue))
return;
m_ChannelMixer = value;
if (onModified != null)
onModified(this, ModificationScope.Node);
}
}
string GetFunctionPrototype(string argIn, string argRed, string argGreen, string argBlue, string argOut)
{
return string.Format("void {0} ({1} {2}, {3} {4}, {3} {5}, {3} {6}, out {7} {8})", GetFunctionName(),
ConvertConcreteSlotValueTypeToString(precision, FindInputSlot<MaterialSlot>(InputSlotId).concreteValueType), argIn,
precision+"3", argRed, argGreen, argBlue,
ConvertConcreteSlotValueTypeToString(precision, FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType), argOut);
}
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
string inputValue = GetSlotValue(InputSlotId, generationMode);
string outputValue = GetSlotValue(OutputSlotId, generationMode);
visitor.AddShaderChunk(string.Format("{0} {1};", ConvertConcreteSlotValueTypeToString(precision, FindInputSlot<MaterialSlot>(InputSlotId).concreteValueType), GetVariableNameForSlot(OutputSlotId)), true);
if(!generationMode.IsPreview())
{
visitor.AddShaderChunk(string.Format("{0}3 _{1}_Red = {0}3 ({2}, {3}, {4});", precision, GetVariableNameForNode(), channelMixer.outRed[0], channelMixer.outRed[1], channelMixer.outRed[2]), true);
visitor.AddShaderChunk(string.Format("{0}3 _{1}_Green = {0}3 ({2}, {3}, {4});", precision, GetVariableNameForNode(), channelMixer.outGreen[0], channelMixer.outGreen[1], channelMixer.outGreen[2]), true);
visitor.AddShaderChunk(string.Format("{0}3 _{1}_Blue = {0}3 ({2}, {3}, {4});", precision, GetVariableNameForNode(), channelMixer.outBlue[0], channelMixer.outBlue[1], channelMixer.outBlue[2]), true);
}
visitor.AddShaderChunk(GetFunctionCallBody(inputValue, string.Format("_{0}_Red", GetVariableNameForNode()), string.Format("_{0}_Green", GetVariableNameForNode()), string.Format("_{0}_Blue", GetVariableNameForNode()), outputValue), true);
}
string GetFunctionCallBody(string inputValue, string red, string green, string blue, string outputValue)
{
return GetFunctionName() + " (" + inputValue + ", " + red + ", " + green + ", " + blue + ", " + outputValue + ");";
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
{
base.CollectPreviewMaterialProperties(properties);
properties.Add(new PreviewProperty()
{
m_Name = string.Format("_{0}_Red", GetVariableNameForNode()),
m_PropType = PropertyType.Vector3,
m_Vector4 = channelMixer.outRed
});
properties.Add(new PreviewProperty()
{
m_Name = string.Format("_{0}_Green", GetVariableNameForNode()),
m_PropType = PropertyType.Vector3,
m_Vector4 = channelMixer.outGreen
});
properties.Add(new PreviewProperty()
{
m_Name = string.Format("_{0}_Blue", GetVariableNameForNode()),
m_PropType = PropertyType.Vector3,
m_Vector4 = channelMixer.outBlue
});
}
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
{
if (!generationMode.IsPreview())
return;
base.CollectShaderProperties(properties, generationMode);
properties.AddShaderProperty(new Vector4ShaderProperty()
{
overrideReferenceName = string.Format("_{0}_Red", GetVariableNameForNode()),
generatePropertyBlock = false
});
properties.AddShaderProperty(new Vector4ShaderProperty()
{
overrideReferenceName = string.Format("_{0}_Green", GetVariableNameForNode()),
generatePropertyBlock = false
});
properties.AddShaderProperty(new Vector4ShaderProperty()
{
overrideReferenceName = string.Format("_{0}_Blue", GetVariableNameForNode()),
generatePropertyBlock = false
});
}
public void GenerateNodeFunction(ShaderGenerator visitor, GenerationMode generationMode)
{
visitor.AddShaderChunk(GetFunctionPrototype("In", "Red", "Green", "Blue", "Out"), false);
visitor.AddShaderChunk("{", false);
visitor.Indent();
visitor.AddShaderChunk(string.Format("Out = {0} (dot(In, Red), dot(In, Green), dot(In, Blue));",
ConvertConcreteSlotValueTypeToString(precision, FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType)), true);
visitor.Deindent();
visitor.AddShaderChunk("}", false);
}
}
}

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


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

38
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/ReplaceColorNode.cs


using System.Reflection;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Title("Artistic/Adjustment/Replace Color")]
public class ReplaceColorNode : CodeFunctionNode
{
public ReplaceColorNode()
{
name = "Replace Color";
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_ReplaceColor", BindingFlags.Static | BindingFlags.NonPublic);
}
static string Unity_ReplaceColor(
[Slot(0, Binding.None)] Vector3 In,
[Slot(1, Binding.None)] Color From,
[Slot(2, Binding.None)] Color To,
[Slot(3, Binding.None)] Vector1 Range,
[Slot(4, Binding.None)] out Vector3 Out)
{
Out = Vector2.zero;
return
@"
{
{precision}3 col = In;
{precision} Distance = distance(From, In);
if(Distance <= Range)
col = To;
Out = col;
}";
}
}
}

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/ReplaceColorNode.cs.meta


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

71
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Adjustment/WhiteBalanceNode.cs


using System.Reflection;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Title("Artistic/Adjustment/White Balance")]
public class WhiteBalanceNode : CodeFunctionNode
{
public WhiteBalanceNode()
{
name = "White Balance";
}
protected override MethodInfo GetFunctionToConvert()
{
return GetType().GetMethod("Unity_WhiteBalance", BindingFlags.Static | BindingFlags.NonPublic);
}
static string Unity_WhiteBalance(
[Slot(0, Binding.None)] Vector3 In,
[Slot(1, Binding.None)] Vector1 Temperature,
[Slot(2, Binding.None)] Vector1 Tint,
[Slot(3, Binding.None)] out Vector3 Out)
{
Out = Vector3.zero;
return @"
{
// Range ~[-1.67;1.67] works best
{precision} t1 = Temperature * 10 / 6;
{precision} t2 = Tint * 10 / 6;
// Get the CIE xy chromaticity of the reference white point.
// Note: 0.31271 = x value on the D65 white point
{precision} x = 0.31271 - t1 * (t1 < 0 ? 0.1 : 0.05);
{precision} standardIlluminantY = 2.87 * x - 3 * x * x - 0.27509507;
{precision} y = standardIlluminantY + t2 * 0.05;
// Calculate the coefficients in the LMS space.
{precision}3 w1 = {precision}3(0.949237, 1.03542, 1.08728); // D65 white point
// CIExyToLMS
{precision} Y = 1;
{precision} X = Y * x / y;
{precision} Z = Y * (1 - x - y) / y;
{precision} L = 0.7328 * X + 0.4296 * Y - 0.1624 * Z;
{precision} M = -0.7036 * X + 1.6975 * Y + 0.0061 * Z;
{precision} S = 0.0030 * X + 0.0136 * Y + 0.9834 * Z;
{precision}3 w2 = {precision}3(L, M, S);
{precision}3 balance = {precision}3(w1.x / w2.x, w1.y / w2.y, w1.z / w2.z);
{precision}3x3 LIN_2_LMS_MAT = {
3.90405e-1, 5.49941e-1, 8.92632e-3,
7.08416e-2, 9.63172e-1, 1.35775e-3,
2.31082e-2, 1.28021e-1, 9.36245e-1
};
{precision}3x3 LMS_2_LIN_MAT = {
2.85847e+0, -1.62879e+0, -2.48910e-2,
-2.10182e-1, 1.15820e+0, 3.24281e-4,
-4.18120e-2, -1.18169e-1, 1.06867e+0
};
{precision}3 lms = mul(LIN_2_LMS_MAT, In);
lms *= balance;
Out = mul(LMS_2_LIN_MAT, lms);
}
";
}
}
}

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


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

8
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Artistic/Mask.meta


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

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


using System;
using System.Collections.Generic;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
namespace UnityEditor.ShaderGraph
{
[Title("Channel/Flip")]
public class FlipNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction
{
public FlipNode()
{
name = "Flip";
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_Flip_" + 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 (int)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;
if (onModified != null)
{
onModified(this, 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;
if (onModified != null)
{
onModified(this, 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;
if (onModified != null)
{
onModified(this, 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;
if (onModified != null)
{
onModified(this, ModificationScope.Node);
}
}
}
string GetFunctionPrototype(string inArg, string flipArg, string outArg)
{
return string.Format("void {0} ({1} {2}, {3} {4}, out {5} {6})", GetFunctionName(),
ConvertConcreteSlotValueTypeToString(precision, FindInputSlot<MaterialSlot>(InputSlotId).concreteValueType), inArg,
ConvertConcreteSlotValueTypeToString(precision, FindInputSlot<MaterialSlot>(InputSlotId).concreteValueType), flipArg,
ConvertConcreteSlotValueTypeToString(precision, FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType), outArg);
}
public void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
string inputValue = GetSlotValue(InputSlotId, generationMode);
string outputValue = GetSlotValue(OutputSlotId, generationMode);
visitor.AddShaderChunk(string.Format("{0} {1};", ConvertConcreteSlotValueTypeToString(precision, FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType), GetVariableNameForSlot(OutputSlotId)), true);
if(!generationMode.IsPreview())
{
visitor.AddShaderChunk(string.Format("{0} _{1}_Flip = {0} ({2}{3}{4}{5});",
ConvertConcreteSlotValueTypeToString(precision, FindOutputSlot<MaterialSlot>(OutputSlotId).concreteValueType),
GetVariableNameForNode(),
Convert.ToInt32(m_RedChannel).ToString(),
channelCount > 1 ? string.Format(", {0}", (Convert.ToInt32(m_GreenChannel)).ToString()) : "",
channelCount > 2 ? string.Format(", {0}", (Convert.ToInt32(m_BlueChannel)).ToString()) : "",
channelCount > 3 ? string.Format(", {0}", (Convert.ToInt32(m_AlphaChannel)).ToString()) : ""), true);
}
visitor.AddShaderChunk(GetFunctionCallBody(inputValue, string.Format("_{0}_Flip", GetVariableNameForNode()), outputValue), true);
}
string GetFunctionCallBody(string inputValue, string flipValue, string outputValue)
{
return GetFunctionName() + " (" + inputValue + ", " + flipValue + ", " + outputValue + ");";
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
{
base.CollectPreviewMaterialProperties(properties);
properties.Add(new PreviewProperty()
{
m_Name = string.Format("_{0}_Flip", GetVariableNameForNode()),
m_PropType = PropertyType.Vector4,
m_Vector4 = 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}_Flip", GetVariableNameForNode()),
generatePropertyBlock = false
});
}
public void GenerateNodeFunction(ShaderGenerator visitor, GenerationMode generationMode)
{
var outputString = new ShaderGenerator();
outputString.AddShaderChunk(GetFunctionPrototype("In", "Flip", "Out"), true);
outputString.AddShaderChunk("{", true);
outputString.Indent();
outputString.AddShaderChunk("Out = abs(Flip - In);", true);
outputString.Deindent();
outputString.AddShaderChunk("}", true);
visitor.AddShaderChunk(outputString.GetShaderString(0), true);
}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Channel/FlipNode.cs.meta


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

78
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/CubemapAssetNode.cs


using System.Collections.Generic;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Title("Input/Texture/Cubemap Asset")]
public class CubemapAssetNode : AbstractMaterialNode, IPropertyFromNode
{
public const int OutputSlotId = 0;
const string kOutputSlotName = "Out";
public CubemapAssetNode()
{
name = "Cubemap Asset";
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new CubemapMaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output));
RemoveSlotsNameNotMatching(new[] { OutputSlotId });
}
[SerializeField]
private SerializableCubemap m_Cubemap = new SerializableCubemap();
[CubemapControl("")]
public Cubemap cubemap
{
get { return m_Cubemap.cubemap; }
set
{
if (m_Cubemap.cubemap == value)
return;
m_Cubemap.cubemap = value;
if (onModified != null)
{
onModified(this, ModificationScope.Node);
}
}
}
public override void CollectShaderProperties(PropertyCollector properties, GenerationMode generationMode)
{
properties.AddShaderProperty(new CubemapShaderProperty()
{
overrideReferenceName = GetVariableNameForSlot(OutputSlotId),
generatePropertyBlock = true,
value = m_Cubemap,
modifiable = false
});
}
public override void CollectPreviewMaterialProperties(List<PreviewProperty> properties)
{
properties.Add(new PreviewProperty
{
m_Name = GetVariableNameForSlot(OutputSlotId),
m_PropType = PropertyType.Cubemap,
m_Cubemap = cubemap
});
}
public IShaderProperty AsShaderProperty()
{
var prop = new CubemapShaderProperty();
prop.value = m_Cubemap;
if (cubemap != null)
prop.displayName = cubemap.name;
return prop;
}
public int outputSlotId { get { return OutputSlotId; } }
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/CubemapAssetNode.cs.meta


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

81
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/CubemapNode.cs


using System.Linq;
using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEditor.ShaderGraph.Drawing.Controls;
namespace UnityEditor.ShaderGraph
{
[Title("Input/Texture/Cubemap")]
public class CubemapNode : AbstractMaterialNode, IGeneratesBodyCode, IMayRequireViewDirection, IMayRequireNormal
{
public const int OutputSlotId = 0;
public const int CubemapInputId = 1;
public const int ViewDirInputId = 2;
public const int NormalInputId = 3;
public const int LODInputId = 4;
const string kOutputSlotName = "Out";
const string kCubemapInputName = "Cube";
const string kViewDirInputName = "ViewDir";
const string kNormalInputName = "Normal";
const string kLODInputName = "LOD";
public override bool hasPreview { get { return true; } }
public CubemapNode()
{
name = "Cubemap";
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Vector4MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector4.zero));
AddSlot(new CubemapInputMaterialSlot(CubemapInputId, kCubemapInputName, kCubemapInputName));
AddSlot(new ViewDirectionMaterialSlot(ViewDirInputId, kViewDirInputName, kViewDirInputName, CoordinateSpace.Object));
AddSlot(new NormalMaterialSlot(NormalInputId, kNormalInputName, kNormalInputName, CoordinateSpace.Object));
AddSlot(new Vector1MaterialSlot(LODInputId, kLODInputName, kLODInputName, SlotType.Input, 0));
RemoveSlotsNameNotMatching(new[] { OutputSlotId, CubemapInputId, ViewDirInputId, NormalInputId, LODInputId });
}
public override PreviewMode previewMode
{
get { return PreviewMode.Preview3D; }
}
// Node generations
public virtual void GenerateNodeCode(ShaderGenerator visitor, GenerationMode generationMode)
{
string result = string.Format("{0}4 {1} = texCUBElod ({2}, {0}4(reflect(-{3}, {4}), {5}));"
, precision
, GetVariableNameForSlot(OutputSlotId)
, GetSlotValue(CubemapInputId, generationMode)
, GetSlotValue(ViewDirInputId, generationMode)
, GetSlotValue(NormalInputId, generationMode)
, GetSlotValue(LODInputId, generationMode));
visitor.AddShaderChunk(result, true);
}
public NeededCoordinateSpace RequiresViewDirection()
{
var viewDirSlot = FindInputSlot<MaterialSlot>(ViewDirInputId);
var edgesViewDir = owner.GetEdges(viewDirSlot.slotReference);
if (!edgesViewDir.Any())
return CoordinateSpace.Object.ToNeededCoordinateSpace();
else
return NeededCoordinateSpace.None;
}
public NeededCoordinateSpace RequiresNormal()
{
var normalSlot = FindInputSlot<MaterialSlot>(NormalInputId);
var edgesNormal = owner.GetEdges(normalSlot.slotReference);
if (!edgesNormal.Any())
return CoordinateSpace.Object.ToNeededCoordinateSpace();
else
return NeededCoordinateSpace.None;
}
}
}

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/Input/Texture/CubemapNode.cs.meta


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

79
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ChannelEnumControl.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 ChannelEnumControlAttribute : Attribute, IControlAttribute
{
string m_Label;
int m_SlotId;
public ChannelEnumControlAttribute(string label = null, int slotId = 0)
{
m_Label = label;
m_SlotId = slotId;
}
public VisualElement InstantiateControl(AbstractMaterialNode node, PropertyInfo propertyInfo)
{
return new ChannelEnumControlView(m_Label, m_SlotId, node, propertyInfo);
}
}
public class ChannelEnumControlView : VisualElement, INodeModificationListener
{
GUIContent m_Label;
AbstractMaterialNode m_Node;
PropertyInfo m_PropertyInfo;
IMGUIContainer m_Container;
int m_SlotId;
public ChannelEnumControlView(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 = (int)SlotValueHelper.GetChannelCount(m_Node.FindSlot<MaterialSlot>(m_SlotId).concreteValueType);
var enumEntryCount = (Enum)m_PropertyInfo.GetValue(m_Node, null);
string[] enumEntryNames = Enum.GetNames(enumEntryCount.GetType());
string[] popupEntries = new string[channelCount];
for (int i = 0; i < popupEntries.Length; i++)
popupEntries[i] = enumEntryNames[i];
value = EditorGUILayout.Popup(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/ChannelEnumControl.cs.meta


fileFormatVersion: 2
guid: 74fdde12d8253bd4c874acc555be0585
timeCreated: 1507817885

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


using System;
using System.Reflection;
using UnityEditor.Experimental.UIElements;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleSheets;
using UnityEditor.ShaderGraph;
namespace UnityEditor.ShaderGraph.Drawing.Controls
{
[AttributeUsage(AttributeTargets.Property)]
public class ChannelMixerControlAttribute : Attribute, IControlAttribute
{
string m_Label;
float m_Minimum;
float m_Maximum;
public ChannelMixerControlAttribute(string label = null, float minimum = -2f, float maximum = 2f)
{
m_Label = label;
m_Minimum = minimum;
m_Maximum = maximum;
}
public VisualElement InstantiateControl(AbstractMaterialNode node, PropertyInfo propertyInfo)
{
return new ChannelMixerControlView(m_Label, m_Minimum, m_Maximum, node, propertyInfo);
}
}
public class ChannelMixerControlView : VisualElement
{
AbstractMaterialNode m_Node;
PropertyInfo m_PropertyInfo;
ChannelMixerNode.ChannelMixer m_ChannelMixer;
int m_OutChannel;
Slider m_RedSlider;
Slider m_GreenSlider;
Slider m_BlueSlider;
float m_Minimum;
float m_Maximum;
bool m_Initialized;
public ChannelMixerControlView(string label, float minimum, float maximum, AbstractMaterialNode node, PropertyInfo propertyInfo)
{
m_Node = node;
m_PropertyInfo = propertyInfo;
m_ChannelMixer = (ChannelMixerNode.ChannelMixer)m_PropertyInfo.GetValue(m_Node, null);
m_OutChannel = 0;
m_Minimum = minimum;
m_Maximum = maximum;
if (propertyInfo.PropertyType != typeof(ChannelMixerNode.ChannelMixer))
throw new ArgumentException("Property must be of type ChannelMixer.", "propertyInfo");
label = label ?? ObjectNames.NicifyVariableName(propertyInfo.Name);
if (!string.IsNullOrEmpty(label))
Add(new Label(label));
Action changedOutputRed = () => OnClickButton(0);
var outputButtonRed = new Button(changedOutputRed);
Add(outputButtonRed);
Action changedOutputGreen = () => OnClickButton(1);
var outputButtonGreen = new Button(changedOutputGreen);
Add(outputButtonGreen);
Action changedOutputBlue = () => OnClickButton(2);
var outputButtonBlue = new Button(changedOutputBlue);
Add(outputButtonBlue);
Add(new Label("Red"));
Action<float> changedRedIn = (s) => { OnChangeSlider(s, 0); };
m_RedSlider = new Slider(m_Minimum, m_Maximum, changedRedIn);
Add(m_RedSlider);
Add(new Label("Green"));
Action<float> changedGreenIn = (s) => { OnChangeSlider(s, 1); };
m_GreenSlider = new Slider(m_Minimum, m_Maximum, changedGreenIn);
Add(m_GreenSlider);
Add(new Label("Blue"));
Action<float> changedBlueIn = (s) => { OnChangeSlider(s, 2); };
m_BlueSlider = new Slider(m_Minimum, m_Maximum, changedBlueIn);
Add(m_BlueSlider);
m_Initialized = true;
ResetSliders();
}
void ResetSliders()
{
Vector3 outputChannel = GetOutputChannel();
m_RedSlider.value = outputChannel[0];
m_GreenSlider.value = outputChannel[1];
m_BlueSlider.value = outputChannel[2];
}
void OnChangeSlider(float value, int inChannel)
{
if (!m_Initialized)
return;
m_Node.owner.owner.RegisterCompleteObjectUndo("Slider 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;
}
m_PropertyInfo.SetValue(m_Node, m_ChannelMixer, null);
}
void OnClickButton(int outChannel)
{
m_OutChannel = outChannel;
ResetSliders();
}
Vector3 GetOutputChannel()
{
switch (m_OutChannel)
{
case 1:
return m_ChannelMixer.outGreen;
case 2:
return m_ChannelMixer.outBlue;
default:
return m_ChannelMixer.outRed;
}
}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/ChannelMixerControl.cs.meta


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

55
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/CubemapControl.cs


using System;
using System.Reflection;
using UnityEditor.Experimental.UIElements;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleSheets;
using UnityEditor.ShaderGraph;
namespace UnityEditor.ShaderGraph.Drawing.Controls
{
[AttributeUsage(AttributeTargets.Property)]
public class CubemapControlAttribute : Attribute, IControlAttribute
{
string m_Label;
public CubemapControlAttribute(string label = null)
{
m_Label = label;
}
public VisualElement InstantiateControl(AbstractMaterialNode node, PropertyInfo propertyInfo)
{
return new CubemapControlView(m_Label, node, propertyInfo);
}
}
public class CubemapControlView : VisualElement
{
AbstractMaterialNode m_Node;
PropertyInfo m_PropertyInfo;
public CubemapControlView(string label, AbstractMaterialNode node, PropertyInfo propertyInfo)
{
m_Node = node;
m_PropertyInfo = propertyInfo;
if (propertyInfo.PropertyType != typeof(Cubemap))
throw new ArgumentException("Property must be of type Texture.", "propertyInfo");
label = label ?? ObjectNames.NicifyVariableName(propertyInfo.Name);
if (!string.IsNullOrEmpty(label))
Add(new Label(label));
var cubemapField = new ObjectField { value = (Cubemap) m_PropertyInfo.GetValue(m_Node, null), objectType = typeof(Cubemap) };
cubemapField.OnValueChanged(OnChange);
Add(cubemapField);
}
void OnChange(ChangeEvent<UnityEngine.Object> evt)
{
m_Node.owner.owner.RegisterCompleteObjectUndo("Cubemap Change");
m_PropertyInfo.SetValue(m_Node, evt.newValue, null);
Dirty(ChangeType.Repaint);
}
}
}

11
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Controls/CubemapControl.cs.meta


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

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


using System;
using System.Reflection;
using UnityEngine;
using UnityEditor.Graphing;
using UnityEngine.Experimental.UIElements;
namespace UnityEditor.ShaderGraph.Drawing.Controls
{
[Serializable]
public struct Toggle
{
public bool isOn;
public bool isEnabled;
public Toggle(bool on, bool enabled)
{
isOn = on;
isEnabled = enabled;
}
public Toggle(bool on)
{
isOn = on;
isEnabled = true;
}
}
[AttributeUsage(AttributeTargets.Property)]
public class ToggleControlAttribute : Attribute, IControlAttribute
{
string m_Label;
public ToggleControlAttribute(string label = null)
{
m_Label = label;
}
public VisualElement InstantiateControl(AbstractMaterialNode node, PropertyInfo propertyInfo)
{
return new ToggleControlView(m_Label, node, propertyInfo);
}
}
public class ToggleControlView : VisualElement, INodeModificationListener
{
GUIContent m_Label;
AbstractMaterialNode m_Node;
PropertyInfo m_PropertyInfo;
IMGUIContainer m_Container;
public ToggleControlView(string label, AbstractMaterialNode node, PropertyInfo propertyInfo)
{
m_Node = node;
m_PropertyInfo = propertyInfo;
if (propertyInfo.PropertyType != typeof(Toggle))
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);
}
public void OnNodeModified(ModificationScope scope)
{
if (scope == ModificationScope.Graph)
m_Container.Dirty(ChangeType.Repaint);
}
void OnGUIHandler()
{
var value = (Toggle) m_PropertyInfo.GetValue(m_Node, null);
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);
}
}
}
}
}

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


fileFormatVersion: 2
guid: 5e83ab8eb10c20c4fbed2700d4f4f11c
timeCreated: 1507817885

35
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/Slots/CubemapSlotControlView.cs


using System;
using UnityEditor.Experimental.UIElements;
using UnityEditor.Graphing;
using UnityEngine;
using UnityEngine.Experimental.UIElements;
using UnityEngine.Experimental.UIElements.StyleSheets;
using Object = UnityEngine.Object;
namespace UnityEditor.ShaderGraph.Drawing.Slots
{
public class CubemapSlotControlView : VisualElement
{
CubemapInputMaterialSlot m_Slot;
public CubemapSlotControlView(CubemapInputMaterialSlot slot)
{
m_Slot = slot;
var objectField = new ObjectField { objectType = typeof(Cubemap), value = m_Slot.cubemap };
objectField.OnValueChanged(OnValueChanged);
Add(objectField);
}
void OnValueChanged(ChangeEvent<Object> evt)
{
var cubemap = evt.newValue as Cubemap;
if (cubemap != m_Slot.cubemap)
{
m_Slot.owner.owner.owner.RegisterCompleteObjectUndo("Change Cubemap");
m_Slot.cubemap = cubemap;
if (m_Slot.owner.onModified != null)
m_Slot.owner.onModified(m_Slot.owner, ModificationScope.Node);
}
}
}
}

3
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/Slots/CubemapSlotControlView.cs.meta


fileFormatVersion: 2
guid: b54f542a9d5f7b84e974b54d625d73ea
timeCreated: 1509718979

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

正在加载...
取消
保存