浏览代码

hack and slash.

/main
Tim Cooper 7 年前
当前提交
6f035d8a
共有 26 个文件被更改,包括 566 次插入975 次删除
  1. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/AssetCallbacks/CreateShaderGraph.cs
  2. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Graphs/AbstractMaterialGraph.cs
  3. 84
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightMetallicMasterNode.cs
  4. 2
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/IMasterNode.cs
  5. 13
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/Nodes/MasterNode.cs
  6. 6
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/LayeredShaderGraph.cs
  7. 4
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Drawing/Views/GraphEditorView.cs
  8. 223
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs
  9. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightWeightPBRSubShader.cs.meta
  10. 129
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/PBRMasterNode.cs
  11. 11
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/PBRMasterNode.cs.meta
  12. 40
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRExtraPasses.template
  13. 7
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRExtraPasses.template.meta
  14. 134
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRForwardPass.template
  15. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightPBRMasterNode.cs.meta
  16. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightSpecularMasterNode.cs.meta
  17. 12
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightUnlitMasterNode.cs.meta
  18. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightMasterNode.cs.meta
  19. 57
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightPBRMasterNode.cs
  20. 79
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightSpecularMasterNode.cs
  21. 71
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightUnlitMasterNode.cs
  22. 337
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightMasterNode.cs
  23. 3
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/MasterRemapNode.cs.meta
  24. 101
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/MasterRemapNode.cs
  25. 182
      MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightSubshaderPBR.template
  26. 0
      /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRForwardPass.template.meta

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


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

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


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);
// var subShaders = masterNode.GetSubshader(requirements, null);
// foreach (var ss in subShaders)
// finalShader.AddShaderChunk(ss, false);
}
else
{

84
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightMetallicMasterNode.cs


using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Serializable]
[Title("Master/Lightweight/PBR Metallic")]
public class LightweightMetallicMasterNode : AbstractLightweightPBRMasterNode
{
public const string MetallicSlotName = "Metallic";
public const int MetallicSlotId = 2;
public LightweightMetallicMasterNode()
{
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
name = "LW Metallic 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));
AddSlot(new Vector1MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input,0, 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, 0, ShaderStage.Fragment));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
MetallicSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId
});
}
protected override string GetTemplateName()
{
return "lightweightSubshaderPBR.template";
}
protected override void GetLightweightDefinesAndRemap(ShaderGenerator defines, ShaderGenerator surfaceOutputRemap, MasterRemapGraph remapper)
{
base.GetLightweightDefinesAndRemap(defines, surfaceOutputRemap, remapper);
defines.AddShaderChunk("#define _METALLIC_SETUP 1", true);
}
protected override IEnumerable<int> masterSurfaceInputs
{
get
{
return new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
MetallicSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId,
};
}
}
protected override IEnumerable<int> masterVertexInputs
{
get
{
return new int[]
{
};
}
}
}
}

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, out List<PropertyCollector.TextureInfo> configuredTextures);
}
}

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, out List<PropertyCollector.TextureInfo> configuredTextures);
}
}

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


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();

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


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

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


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)
{
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);
AbstractMaterialGraph.GenerateSurfaceDescription(
masterNode,
pass.PixelShaderSlots,
masterNode.owner as AbstractMaterialGraph,
surfaceDescriptionFunction,
shaderFunctionVisitor,
shaderProperties,
requirements,
mode);
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);
var usedSlots = new List<MaterialSlot>();
foreach (var id in pass.PixelShaderSlots)
usedSlots.Add(masterNode.FindSlot<MaterialSlot>(id));
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(PBRMasterNode 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(
"lightweightPBRForwardPass.template",
masterNode,
masterNode.model == PBRMasterNode.Model.Metallic ? m_ForwardPassMetallic : m_ForwardPassSpecular,
mode),
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:

129
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
}
[SerializeField]
private Model m_Model;
[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);
}
}
}
public PBRMasterNode()
{
UpdateNodeAfterDeserialization();
}
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));
AddSlot(new Vector1MaterialSlot(MetallicSlotId, MetallicSlotName, MetallicSlotName, SlotType.Input, 0, ShaderStage.Fragment));
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, 0, 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, 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, GenerationMode.ForReals);
foreach (var activeNode in activeNodeList.OfType<AbstractMaterialNode>())
activeNode.CollectShaderProperties(shaderProperties, GenerationMode.ForReals);
var finalShader = new ShaderGenerator();
finalShader.AddShaderChunk(string.Format(@"Shader ""{0}""", name), 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, GenerationMode.ForReals))
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:

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


Pass
{
Tags{"Lightmode" = "ShadowCaster"}
ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 2.0
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#include "UnityCG.cginc"
#include "LightweightPassShadow.cginc"
ENDCG
}
Pass
{
Tags{"Lightmode" = "DepthOnly"}
ZWrite On
CGPROGRAM
#pragma target 2.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
float4 vert(float4 pos : POSITION) : SV_POSITION
{
return UnityObjectToClipPos(pos);
}
half4 frag() : SV_TARGET
{
return 0;
}
ENDCG
}

7
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRExtraPasses.template.meta


fileFormatVersion: 2
guid: 5fa0a7ad9ac73b34691439e5cf40a1c3
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

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


Pass
{
Tags{"LightMode" = "LightweightForward"}
${Tags}
${Blending}
${Culling}
${ZTest}
${ZWrite}
CGPROGRAM
#pragma target 3.0
#pragma multi_compile _MAIN_DIRECTIONAL_LIGHT _MAIN_SPOT_LIGHT _MAIN_POINT_LIGHT
#pragma multi_compile _ _ADDITIONAL_LIGHTS
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ _HARD_SHADOWS _SOFT_SHADOWS _HARD_SHADOWS_CASCADES _SOFT_SHADOWS_CASCADES
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile_fog
#pragma multi_compile_instancing
#pragma vertex vert
#pragma fragment frag
#pragma glsl
#pragma debug
${Defines}
#include "LightweightLighting.cginc"
${Graph}
struct GraphVertexOutput
{
float4 position : POSITION;
float4 lwCustom : TEXCOORD0;
float4 fogCoord : TEXCOORD1; // x: fogCoord, yzw: vertexColor
${Interpolators}
UNITY_VERTEX_OUTPUT_STEREO
};
GraphVertexOutput vert (GraphVertexInput v)
{
v = PopulateVertexData(v);
UNITY_SETUP_INSTANCE_ID(v);
GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.position = UnityObjectToClipPos(v.vertex);
${VertexShader}
#ifdef LIGHTMAP_ON
o.lwCustom.zw = v.lightmapUV * unity_LightmapST.xy + unity_LightmapST.zw;
#endif
float3 lwWNormal = normalize(UnityObjectToWorldNormal(v.normal));
float3 lwWorldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
// TODO: change to only support point lights per vertex. This will greatly simplify shader ALU
#if defined(_VERTEX_LIGHTS) && defined(_MULTIPLE_LIGHTS)
half3 diffuse = half3(1.0, 1.0, 1.0);
// pixel lights shaded = min(pixelLights, perObjectLights)
// vertex lights shaded = min(vertexLights, perObjectLights) - pixel lights shaded
// Therefore vertexStartIndex = pixelLightCount; vertexEndIndex = min(vertexLights, perObjectLights)
int vertexLightStart = min(globalLightCount.x, unity_LightIndicesOffsetAndCount.y);
int vertexLightEnd = min(globalLightCount.y, unity_LightIndicesOffsetAndCount.y);
for (int lightIter = vertexLightStart; lightIter < vertexLightEnd; ++lightIter)
{
int lightIndex = unity_4LightIndices0[lightIter];
LightInput lightInput;
INITIALIZE_LIGHT(lightInput, lightIndex);
half3 lightDirection;
half atten = ComputeLightAttenuationVertex(lightInput, lwWNormal, lwWorldPos, lightDirection);
o.fogCoord.yzw += LightingLambert(diffuse, lightDirection, lwWNormal, atten);
}
#endif
#if defined(_LIGHT_PROBES_ON) && !defined(LIGHTMAP_ON)
o.fogCoord.yzw += max(half3(0, 0, 0), ShadeSH9(half4(lwWNormal, 1)));
#endif
UNITY_TRANSFER_FOG(o, o.position);
return o;
}
fixed4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}
SurfaceInputs surfaceInput = (SurfaceInputs)0;
${SurfaceInputs}
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float3 Albedo = float3(0.5, 0.5, 0.5);
float3 Specular = float3(0, 0, 0);
float Metallic = 0;
float3 Normal = float3(0, 0, 1);
float3 Emission = 0;
float Smoothness = 0.5;
float Occlusion = 1;
float Alpha = 1;
${SurfaceOutputRemap}
#if defined(UNITY_COLORSPACE_GAMMA)
Albedo = Albedo * Albedo;
Emission = Emission * Emission;
#endif
return LightweightFragmentPBR(
IN.lwCustom,
WorldSpacePosition,
WorldSpaceNormal,
WorldSpaceTangent,
WorldSpaceBiTangent,
WorldSpaceViewDirection,
IN.fogCoord.x,
Albedo,
Metallic,
Specular,
Smoothness,
Normal,
Occlusion,
Emission,
Alpha);
}
ENDCG
}

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightPBRMasterNode.cs.meta


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

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightSpecularMasterNode.cs.meta


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

12
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/LightweightUnlitMasterNode.cs.meta


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

3
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightMasterNode.cs.meta


fileFormatVersion: 2
guid: 72c867ea29464bec864ea612e2bcecd3
timeCreated: 1505799928

57
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightPBRMasterNode.cs


using System;
using System.Linq;
namespace UnityEditor.ShaderGraph
{
[Serializable]
public abstract class AbstractLightweightPBRMasterNode : AbstractLightweightMasterNode
{
public const string AlbedoSlotName = "Albedo";
public const string NormalSlotName = "Normal";
public const string EmissionSlotName = "Emission";
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 EmissionSlotId = 3;
public const int SmoothnessSlotId = 4;
public const int OcclusionSlotId = 5;
public const int AlphaSlotId = 6;
protected override void GetLightweightDefinesAndRemap(ShaderGenerator defines, ShaderGenerator surfaceOutputRemap, MasterRemapGraph remapper)
{
base.GetLightweightDefinesAndRemap(defines, surfaceOutputRemap, remapper);
defines.AddShaderChunk("#define _GLOSSYREFLECTIONS_ON", true);
defines.AddShaderChunk("#define _SPECULARHIGHLIGHTS_ON", true);
if(IsNormalMapConnected())
defines.AddShaderChunk("#define _NORMALMAP 1", true);
}
protected override int GetInterpolatorStartIndex()
{
return 2;
}
public override ShaderGraphRequirements GetNodeSpecificRequirements()
{
var reqs = ShaderGraphRequirements.none;
reqs.requiresNormal |= NeededCoordinateSpace.World;
reqs.requiresTangent |= NeededCoordinateSpace.World;
reqs.requiresBitangent |= NeededCoordinateSpace.World;
reqs.requiresPosition |= NeededCoordinateSpace.World;
reqs.requiresViewDir |= NeededCoordinateSpace.World;
return base.GetNodeSpecificRequirements().Union(reqs);
}
bool IsNormalMapConnected()
{
var nm = FindSlot<MaterialSlot>(NormalSlotId);
return owner.GetEdges(nm.slotReference).Any();
}
}
}

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


using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Serializable]
[Title("Master/Lightweight/PBR Specular")]
public class LightweightSpecularMasterNode : AbstractLightweightPBRMasterNode
{
public const string SpecularSlotName = "Specular";
public const int SpecularSlotId = 2;
public const string WorkflowName = "Specular";
public LightweightSpecularMasterNode()
{
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
name = "LW Specular Master";
AddSlot(new Vector3MaterialSlot(AlbedoSlotId, AlbedoSlotName, AlbedoSlotName, SlotType.Input, new Vector3(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));
AddSlot(new Vector3MaterialSlot(SpecularSlotId, SpecularSlotName, SpecularSlotName, SlotType.Input, Vector3.zero, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(SmoothnessSlotId, SmoothnessSlotName, SmoothnessSlotName, SlotType.Input, 0, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(OcclusionSlotId, OcclusionSlotName, OcclusionSlotName, SlotType.Input,0, 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[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
SpecularSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId
});
}
protected override string GetTemplateName()
{
return "lightweightSubshaderPBR.template";
}
protected override IEnumerable<int> masterSurfaceInputs
{
get
{
return new[]
{
AlbedoSlotId,
NormalSlotId,
EmissionSlotId,
SpecularSlotId,
SmoothnessSlotId,
OcclusionSlotId,
AlphaSlotId,
};
}
}
protected override IEnumerable<int> masterVertexInputs
{
get
{
return new int[]
{
};
}
}
}
}

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


using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Serializable]
[Title("Master/Lightweight/Unlit")]
public class LightweightUnlitMasterNode : AbstractLightweightMasterNode
{
public const string ColorSlotName = "Color";
public const string AlphaSlotName = "Alpha";
public const int ColorSlotId = 0;
public const int AlphaSlotId = 1;
public LightweightUnlitMasterNode()
{
name = "LightweightUnlitMasterNode";
UpdateNodeAfterDeserialization();
}
public sealed override void UpdateNodeAfterDeserialization()
{
AddSlot(new Vector3MaterialSlot(ColorSlotId, ColorSlotName, ColorSlotName, SlotType.Input, Vector3.zero, ShaderStage.Fragment));
AddSlot(new Vector1MaterialSlot(AlphaSlotId, AlphaSlotName, AlphaSlotName, SlotType.Input, 0, ShaderStage.Fragment));
// clear out slot names that do not match the slots
// we support
RemoveSlotsNameNotMatching(
new[]
{
ColorSlotId,
AlphaSlotId
});
}
protected override IEnumerable<int> masterSurfaceInputs
{
get
{
return new[]
{
ColorSlotId,
AlphaSlotId,
};
}
}
protected override IEnumerable<int> masterVertexInputs
{
get
{
return new int[]
{
};
}
}
protected override string GetTemplateName()
{
return "lightweightSubshaderUnlit.template";
}
protected override int GetInterpolatorStartIndex()
{
return 0;
}
}
}

337
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/LightweightPipeline/AbstractLightweightMasterNode.cs


using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
public abstract class AbstractLightweightMasterNode : MasterNode
{
private const int kMaxInterpolators = 8;
protected abstract IEnumerable<int> masterSurfaceInputs { get; }
protected abstract IEnumerable<int> masterVertexInputs { get; }
protected abstract string GetTemplateName();
protected virtual void GetLightweightDefinesAndRemap(ShaderGenerator defines, ShaderGenerator surfaceOutputRemap, MasterRemapGraph remapper)
{
// Step 1: no remapper, working with raw master node..
if (remapper == null)
{
foreach (var slot in GetInputSlots<MaterialSlot>())
{
surfaceOutputRemap.AddShaderChunk(slot.shaderOutputName
+ " = surf."
+ slot.shaderOutputName + ";", true);
}
}
// Step 2: remapper present... complex workflow time
else
{
surfaceOutputRemap.AddShaderChunk("{", false);
surfaceOutputRemap.Indent();
foreach (var prop in remapper.properties)
{
surfaceOutputRemap.AddShaderChunk(prop.GetInlinePropertyDeclarationString(), true);
surfaceOutputRemap.AddShaderChunk(string.Format("{0} = surf.{0};", prop.referenceName), true);
}
List<INode> nodes = new List<INode>();
NodeUtils.DepthFirstCollectNodesFromNode(nodes, this, NodeUtils.IncludeSelf.Exclude);
foreach (var activeNode in nodes.OfType<AbstractMaterialNode>())
{
if (activeNode is IGeneratesBodyCode)
(activeNode as IGeneratesBodyCode).GenerateNodeCode(surfaceOutputRemap, GenerationMode.ForReals);
}
foreach (var input in GetInputSlots<MaterialSlot>())
{
foreach (var edge in owner.GetEdges(input.slotReference))
{
var outputRef = edge.outputSlot;
var fromNode = owner.GetNodeFromGuid<AbstractMaterialNode>(outputRef.nodeGuid);
if (fromNode == null)
continue;
surfaceOutputRemap.AddShaderChunk(
string.Format("{0} = {1};", input.shaderOutputName,
fromNode.GetVariableNameForSlot(outputRef.slotId)), true);
}
}
surfaceOutputRemap.Deindent();
surfaceOutputRemap.AddShaderChunk("}", false);
}
}
struct Pass
{
public string Name;
public List<int> VertexShaderSlots;
public List<int> PixelShaderSlots;
}
public string GetShader(GenerationMode mode, 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}""", name), 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 LightWeightSubShader();
foreach (var subshader in lwSub.GetSubshader(this, GenerationMode.ForReals))
finalShader.AddShaderChunk(subshader, true);
finalShader.Deindent();
finalShader.AddShaderChunk("}", false);
configuredTextures = shaderProperties.GetConfiguredTexutres();
return finalShader.GetShaderString(0);
}
public class LightWeightSubShader
{
Pass m_ForwardPass = new Pass()
{
Name = "LightweightForward",
PixelShaderSlots = new List<int>()
{
AbstractLightweightPBRMasterNode.AlbedoSlotId,
AbstractLightweightPBRMasterNode.EmissionSlotId,
AbstractLightweightPBRMasterNode.NormalSlotId,
AbstractLightweightPBRMasterNode.OcclusionSlotId,
AbstractLightweightPBRMasterNode.SmoothnessSlotId,
AbstractLightweightPBRMasterNode.AlphaSlotId
}
};
public IEnumerable<string> GetSubshader(AbstractLightweightMasterNode masterNode, 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, m_ForwardPass.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 m_ForwardPass.PixelShaderSlots)
slots.Add(masterNode.FindSlot<MaterialSlot>(id));
AbstractMaterialGraph.GenerateSurfaceDescriptionStruct(surfaceDescriptionStruct, slots, true);
AbstractMaterialGraph.GenerateSurfaceDescription(
masterNode,
m_ForwardPass.PixelShaderSlots,
masterNode.owner as AbstractMaterialGraph,
surfaceDescriptionFunction,
shaderFunctionVisitor,
shaderProperties,
requirements,
mode);
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("lightweightSubshaderPBR.template");
var usedSlots = new List<MaterialSlot>();
foreach (var id in m_ForwardPass.PixelShaderSlots)
usedSlots.Add(masterNode.FindSlot<MaterialSlot>(id));
foreach (var slot in usedSlots)
{
surfaceOutputRemap.AddShaderChunk(slot.shaderOutputName
+ " = surf."
+ slot.shaderOutputName + ";", true);
}
if (!File.Exists(templateLocation))
return new string[] { };
var subShaderTemplate = File.ReadAllText(templateLocation);
var resultShader = subShaderTemplate.Replace("${Defines}", defines.GetShaderString(3));
resultShader = resultShader.Replace("${Graph}", graph.GetShaderString(3));
resultShader = resultShader.Replace("${Interpolators}", interpolators.GetShaderString(3));
resultShader = resultShader.Replace("${VertexShader}", localVertexShader.GetShaderString(3));
resultShader = resultShader.Replace("${LocalPixelShader}", localPixelShader.GetShaderString(3));
resultShader = resultShader.Replace("${SurfaceInputs}", localSurfaceInputs.GetShaderString(3));
resultShader = resultShader.Replace("${SurfaceOutputRemap}", surfaceOutputRemap.GetShaderString(3));
resultShader = resultShader.Replace("${Tags}", tagsVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${Blending}", blendingVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${Culling}", cullingVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ZTest}", zTestVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ZWrite}", zWriteVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${LOD}", "" + materialOptions.lod);
return new[] { resultShader };
}
}
public override IEnumerable<string> GetSubshader(ShaderGraphRequirements graphRequirements, MasterRemapGraph remapper)
{
var tagsVisitor = new ShaderGenerator();
var blendingVisitor = new ShaderGenerator();
var cullingVisitor = new ShaderGenerator();
var zTestVisitor = new ShaderGenerator();
var zWriteVisitor = new ShaderGenerator();
m_MaterialOptions.GetTags(tagsVisitor);
m_MaterialOptions.GetBlend(blendingVisitor);
m_MaterialOptions.GetCull(cullingVisitor);
m_MaterialOptions.GetDepthTest(zTestVisitor);
m_MaterialOptions.GetDepthWrite(zWriteVisitor);
var interpolators = new ShaderGenerator();
var vertexShader = new ShaderGenerator();
var localPixelShader = new ShaderGenerator();
var surfaceInputs = new ShaderGenerator();
ShaderGenerator.GenerateStandardTransforms(
GetInterpolatorStartIndex(),
10,
interpolators,
vertexShader,
localPixelShader,
surfaceInputs,
graphRequirements,
GetNodeSpecificRequirements(),
CoordinateSpace.World);
ShaderGenerator defines = new ShaderGenerator();
ShaderGenerator surfaceOutputRemap = new ShaderGenerator();
GetLightweightDefinesAndRemap(defines, surfaceOutputRemap, remapper);
var templateLocation = ShaderGenerator.GetTemplatePath(GetTemplateName());
if (!File.Exists(templateLocation))
return new string[] {};
var subShaderTemplate = File.ReadAllText(templateLocation);
var resultShader = subShaderTemplate.Replace("${Defines}", defines.GetShaderString(3));
resultShader = resultShader.Replace("${Interpolators}", interpolators.GetShaderString(3));
resultShader = resultShader.Replace("${VertexShader}", vertexShader.GetShaderString(3));
resultShader = resultShader.Replace("${LocalPixelShader}", localPixelShader.GetShaderString(3));
resultShader = resultShader.Replace("${SurfaceInputs}", surfaceInputs.GetShaderString(3));
resultShader = resultShader.Replace("${SurfaceOutputRemap}", surfaceOutputRemap.GetShaderString(3));
resultShader = resultShader.Replace("${Tags}", tagsVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${Blending}", blendingVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${Culling}", cullingVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ZTest}", zTestVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${ZWrite}", zWriteVisitor.GetShaderString(2));
resultShader = resultShader.Replace("${LOD}", "" + m_MaterialOptions.lod);
return new[] {resultShader};
}
protected abstract int GetInterpolatorStartIndex();
}
}

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


fileFormatVersion: 2
guid: 861139fc6f60415cae2eb9a9625aaeb8
timeCreated: 1506873607

101
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Data/SubGraph/MasterRemapNode.cs


using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEditor.ShaderGraph.Drawing.Controls;
using UnityEngine;
using UnityEditor.Graphing;
namespace UnityEditor.ShaderGraph
{
[Title("Master/Remap-Node")]
public class MasterRemapNode : AbstractSubGraphNode, IMasterNode
{
[SerializeField]
protected SurfaceMaterialOptions m_MaterialOptions = new SurfaceMaterialOptions();
public SurfaceMaterialOptions options
{
get { return m_MaterialOptions; }
}
public override PreviewMode previewMode
{
get { return PreviewMode.Preview3D; }
}
[SerializeField]
private string m_SerializedRemapGraph = string.Empty;
[Serializable]
private class RemapGraphHelper
{
public MasterRemapGraphAsset remapGraph;
}
protected override AbstractSubGraph referencedGraph
{
get
{
if (remapGraphAsset == null)
return null;
return remapGraphAsset.remapGraph;
}
}
#if UNITY_EDITOR
[ObjectControl("Remap")]
public MasterRemapGraphAsset remapGraphAsset
{
get
{
if (string.IsNullOrEmpty(m_SerializedRemapGraph))
return null;
var helper = new RemapGraphHelper();
EditorJsonUtility.FromJsonOverwrite(m_SerializedRemapGraph, helper);
return helper.remapGraph;
}
set
{
if (remapGraphAsset == value)
return;
var helper = new RemapGraphHelper();
helper.remapGraph = value;
m_SerializedRemapGraph = EditorJsonUtility.ToJson(helper, true);
UpdateSlots();
if (onModified != null)
onModified(this, ModificationScope.Topological);
}
}
#else
public MaterialSubGraphAsset subGraphAsset {get; set; }
#endif
public MasterRemapNode()
{
name = "RemapMaster";
}
public IEnumerable<string> GetSubshader(ShaderGraphRequirements graphRequirements, MasterRemapGraph remapper)
{
if (referencedGraph == null)
return new string[]{};
var masterNodes = referencedGraph.activeNodes.OfType<IMasterNode>().ToList();
if (masterNodes.Count == 0)
return new string[]{};
var results = new List<string>();
foreach (var master in masterNodes)
results.AddRange(master.GetSubshader(graphRequirements, referencedGraph as MasterRemapGraph));
return results;
}
}
}

182
MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightSubshaderPBR.template


SubShader
{
Tags{"RenderType" = "Opaque" "RenderPipeline" = "LightweightPipeline"}
LOD ${LOD}
Pass
{
Tags{"LightMode" = "LightweightForward"}
${Tags}
${Blending}
${Culling}
${ZTest}
${ZWrite}
CGPROGRAM
#pragma target 3.0
#pragma multi_compile _MAIN_DIRECTIONAL_LIGHT _MAIN_SPOT_LIGHT _MAIN_POINT_LIGHT
#pragma multi_compile _ _ADDITIONAL_LIGHTS
#pragma multi_compile _ UNITY_SINGLE_PASS_STEREO STEREO_INSTANCING_ON STEREO_MULTIVIEW_ON
#pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ _HARD_SHADOWS _SOFT_SHADOWS _HARD_SHADOWS_CASCADES _SOFT_SHADOWS_CASCADES
#pragma multi_compile _ _VERTEX_LIGHTS
#pragma multi_compile_fog
#pragma multi_compile_instancing
#pragma vertex vert
#pragma fragment frag
#pragma glsl
#pragma debug
${Defines}
#include "LightweightLighting.cginc"
${Graph}
struct GraphVertexOutput
{
float4 position : POSITION;
float4 lwCustom : TEXCOORD0;
float4 fogCoord : TEXCOORD1; // x: fogCoord, yzw: vertexColor
${Interpolators}
UNITY_VERTEX_OUTPUT_STEREO
};
GraphVertexOutput vert (GraphVertexInput v)
{
v = PopulateVertexData(v);
UNITY_SETUP_INSTANCE_ID(v);
GraphVertexOutput o = (GraphVertexOutput)0;
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(o);
o.position = UnityObjectToClipPos(v.vertex);
${VertexShader}
#ifdef LIGHTMAP_ON
o.lwCustom.zw = v.lightmapUV * unity_LightmapST.xy + unity_LightmapST.zw;
#endif
float3 lwWNormal = normalize(UnityObjectToWorldNormal(v.normal));
float3 lwWorldPos = mul(unity_ObjectToWorld, v.vertex).xyz;
// TODO: change to only support point lights per vertex. This will greatly simplify shader ALU
#if defined(_VERTEX_LIGHTS) && defined(_MULTIPLE_LIGHTS)
half3 diffuse = half3(1.0, 1.0, 1.0);
// pixel lights shaded = min(pixelLights, perObjectLights)
// vertex lights shaded = min(vertexLights, perObjectLights) - pixel lights shaded
// Therefore vertexStartIndex = pixelLightCount; vertexEndIndex = min(vertexLights, perObjectLights)
int vertexLightStart = min(globalLightCount.x, unity_LightIndicesOffsetAndCount.y);
int vertexLightEnd = min(globalLightCount.y, unity_LightIndicesOffsetAndCount.y);
for (int lightIter = vertexLightStart; lightIter < vertexLightEnd; ++lightIter)
{
int lightIndex = unity_4LightIndices0[lightIter];
LightInput lightInput;
INITIALIZE_LIGHT(lightInput, lightIndex);
half3 lightDirection;
half atten = ComputeLightAttenuationVertex(lightInput, lwWNormal, lwWorldPos, lightDirection);
o.fogCoord.yzw += LightingLambert(diffuse, lightDirection, lwWNormal, atten);
}
#endif
#if defined(_LIGHT_PROBES_ON) && !defined(LIGHTMAP_ON)
o.fogCoord.yzw += max(half3(0, 0, 0), ShadeSH9(half4(lwWNormal, 1)));
#endif
UNITY_TRANSFER_FOG(o, o.position);
return o;
}
fixed4 frag (GraphVertexOutput IN) : SV_Target
{
${LocalPixelShader}
SurfaceInputs surfaceInput = (SurfaceInputs)0;
${SurfaceInputs}
SurfaceDescription surf = PopulateSurfaceData(surfaceInput);
float3 Albedo = float3(0.5, 0.5, 0.5);
float3 Specular = float3(0, 0, 0);
float Metallic = 0;
float3 Normal = float3(0, 0, 1);
float3 Emission = 0;
float Smoothness = 0.5;
float Occlusion = 1;
float Alpha = 1;
${SurfaceOutputRemap}
#if defined(UNITY_COLORSPACE_GAMMA)
Albedo = Albedo * Albedo;
Emission = Emission * Emission;
#endif
return LightweightFragmentPBR(
IN.lwCustom,
WorldSpacePosition,
WorldSpaceNormal,
WorldSpaceTangent,
WorldSpaceBiTangent,
WorldSpaceViewDirection,
IN.fogCoord.x,
Albedo,
Metallic,
Specular,
Smoothness,
Normal,
Occlusion,
Emission,
Alpha);
}
ENDCG
}
Pass
{
Tags{"Lightmode" = "ShadowCaster"}
ZWrite On ZTest LEqual
CGPROGRAM
#pragma target 2.0
#pragma vertex ShadowPassVertex
#pragma fragment ShadowPassFragment
#include "UnityCG.cginc"
#include "LightweightPassShadow.cginc"
ENDCG
}
Pass
{
Tags{"Lightmode" = "DepthOnly"}
ZWrite On
CGPROGRAM
#pragma target 2.0
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
float4 vert(float4 pos : POSITION) : SV_POSITION
{
return UnityObjectToClipPos(pos);
}
half4 frag() : SV_TARGET
{
return 0;
}
ENDCG
}
}

/MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightSubshaderPBR.template.meta → /MaterialGraphProject/Assets/UnityShaderEditor/Editor/Templates/lightweightPBRForwardPass.template.meta

正在加载...
取消
保存