Created
July 26, 2018 18:20
-
-
Save ciro-unity/b6e226b41b30be44d1aee003ce6262d6 to your computer and use it in GitHub Desktop.
A custom node for Unity's ShaderGraph to capture lighting and use it into the shader.Works as of July 2018, but the APIs might change!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
using UnityEditor.ShaderGraph; | |
using System.Reflection; | |
[Title("Custom", "Main Light")] | |
public class MainLightNode : CodeFunctionNode | |
{ | |
public override bool hasPreview {get {return false;}} | |
private static string functionBodyForReals = @"{ | |
Light mainLight = GetMainLight(); | |
Color = mainLight.color; | |
Direction = mainLight.direction; | |
float4 shadowCoord; | |
#ifdef _SHADOWS_ENABLED | |
#if SHADOWS_SCREEN | |
float4 clipPos = TransformWorldToHClip(WorldPos); | |
shadowCoord = ComputeShadowCoord(clipPos); | |
#else | |
shadowCoord = TransformWorldToShadowCoord(WorldPos); | |
#endif | |
mainLight.attenuation = MainLightRealtimeShadowAttenuation(shadowCoord); | |
#endif | |
Attenuation = mainLight.attenuation; | |
}"; | |
private static string functionBodyPreview = @"{ | |
Color = 1; | |
Direction = float3(-0.5, -.5, 0.5); | |
Attenuation = 1; | |
}"; | |
private static bool isPreview; | |
private static string functionBody | |
{ | |
get | |
{ | |
if(isPreview) | |
return functionBodyPreview; | |
else | |
return functionBodyForReals; | |
} | |
} | |
public MainLightNode() | |
{ | |
name = "Main Light"; | |
} | |
protected override MethodInfo GetFunctionToConvert() | |
{ | |
return GetType().GetMethod("CustomFunction", BindingFlags.Static | BindingFlags.NonPublic); | |
} | |
public override void GenerateNodeFunction(FunctionRegistry registry, GraphContext graphContext, GenerationMode generationMode) | |
{ | |
isPreview = generationMode == GenerationMode.Preview; | |
base.GenerateNodeFunction(registry, graphContext, generationMode); | |
} | |
private static string CustomFunction( | |
[Slot(0, Binding.None)] out Vector3 Direction, | |
[Slot(1, Binding.None)] out Vector1 Attenuation, | |
[Slot(2, Binding.None)] out Vector3 Color, | |
[Slot(3, Binding.WorldSpacePosition)] Vector3 WorldPos) | |
{ | |
Direction = Vector3.zero; | |
Color = Vector3.zero; | |
return functionBody; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment