32 Commits

Author SHA1 Message Date
Misaki
27e743755d Finish the ShadingColorScope; 2025-02-01 00:32:02 +09:00
780b3f9f13 Added PBRScope; 2025-01-31 22:28:21 +08:00
68870fe818 Update ShadingColorScope tooltips; 2025-01-31 20:01:49 +08:00
9822fa61ca Implement ShowSection for RimLightScope; 2025-01-31 19:19:46 +08:00
d92a103be2 Added RimLightScope; 2025-01-31 19:15:11 +08:00
Misaki
068e501fad Rename ShadingColorSettingsScope to ShadingColorScope 2025-01-31 17:27:44 +09:00
Misaki
e8d1d5923a Optmize shader structure 2025-01-31 17:25:19 +09:00
f41c6c9b34 Optimize ShadingColorSettingsScope toggle style; 2025-01-31 16:17:29 +08:00
5d23bd906b Added ShadingColorScope; 2025-01-30 22:36:37 +08:00
Misaki
181a53a3b2 Added UtsEvaluateAngelRing;
Added UTSTonemapping;
2025-01-30 22:54:43 +09:00
Misaki
d8b12a0ca9 Added SurfaceFeatureFlags;
Added OutlineScope;
Added AngelRingScope;

Change up Outline pass
2025-01-29 21:54:17 +09:00
Misaki
018300e046 Folder clean up;
Added Emissive;
2025-01-29 12:27:09 +09:00
Misaki
1a82022a6f Shader code cleanup;
Added punctual light evaluation in light loop;
2025-01-27 17:54:19 +09:00
Misaki
fac66d8694 Added UtsEvaluateBSDF_MatCapDiffuse;
Added UtsEvaluateBSDF_MatCapSpecular;
2025-01-24 17:59:40 +09:00
Misaki
476fdc3774 Updated dependency 2025-01-24 11:55:44 +09:00
Misaki
6a8095d7e0 Code Cleanup; 2025-01-23 23:56:32 +09:00
Misaki
e6b58cb321 Added UtsAreaLight.hlsl;
Fixed the problem that the appearence of direct diffuse is incorrect when area light intensity is low.

Changed the file name of PBR.hlsl to UtsPBR.hlsl
Changed the file name of EnvLighting.hlsl to UtsEnvLighting.hlsl
2025-01-18 14:14:00 +09:00
Misaki
12a03e9c3c Added UTSPolygonFormFactor and UTSComputeEdgeFactor 2025-01-17 18:47:37 +09:00
Misaki
b838223551 Changed area light calculation, need feature clean up 2025-01-17 18:45:41 +09:00
Misaki
b1ef8afc8d Update version to 2.1.0; 2025-01-09 15:32:35 +09:00
75a71635a0 Merge pull request 'feature/hair-eye-blending' (#1) from feature/hair-eye-blending into main
Reviewed-on: #1
2025-01-09 06:29:07 +00:00
Misaki
d47641e5e2 Added HairBlending shader pass;
Added HairBlendingSetting in UTSRenderPassSetting;
Added MaterialType to UTS;
Added MaterialFeature scope to UTS material editor;

Merged HairBlendingPass and HairShadowPass into UTSPass;

Fixed the bug that character box light can not update rotation correctly according to bound light source;
2025-01-09 07:58:06 +09:00
Misaki
9290223624 Merge branch 'main' of https://git.personalnas.com/Misaki/com.misaki.hdrp-toon into feature/hair-eye-blending
# Conflicts:
#	README.md
2025-01-08 23:20:17 +09:00
Misaki
9f86d53804 Update the version to 2.0.5 2025-01-08 23:12:47 +09:00
Misaki
968b83870f Removed the dependency of layer mask of hair shadow caster;
Added HairShadowCaster pass;
2025-01-08 23:09:55 +09:00
Misaki
a7a9ad16b5 Updated namespace;
Added UTSPass;
Chnaged the RTHanlde _HairShadowMap to not reallocate when screen resolution decreased;
2025-01-08 22:19:04 +09:00
Misaki
23862b4380 Merge branch 'main' of https://git.personalnas.com/Misaki/com.misaki.hdrp-toon 2024-12-26 16:17:27 +09:00
Misaki
1d2a815803 Merge branch 'main' of https://git.personalnas.com/Misaki/com.misaki.hdrp-toon 2024-12-26 16:17:22 +09:00
Misaki
e91a602add Merge branch 'main' of https://git.personalnas.com/Misaki/com.misaki.hdrp-toon 2024-12-26 16:14:49 +09:00
Misaki
eda516fdab Fixed README assets missing; 2024-12-26 16:14:36 +09:00
Misaki
d33d3f2bb7 Fixed README assets missing; 2024-12-26 16:13:19 +09:00
Misaki
140734dc06 Update README; 2024-12-16 19:28:18 +09:00
150 changed files with 5001 additions and 5149 deletions

View File

@@ -2,6 +2,31 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
## [2.1.0] - 09-Jan-2025
### Added
- Added HairBlending shader pass;
- Added HairBlendingSetting in UTSRenderPassSetting;
- Added MaterialType to UTS;
- Added MaterialFeature scope to UTS material editor;
### Changed
- Merged HairBlendingPass and HairShadowPass into UTSPass;
### Fixed
- Fixed the bug that character box light can not update rotation correctly according to bound light source;
## [2.0.5] - 08-Jan-2025
### Added
- Added UTSPass custom pass;
- Added HairShadowCaster shader pass;
### Changed
- Chnaged the RTHanlde _HairShadowMap to not reallocate when screen resolution decreased;
- Changed namespace;
- Removed the dependency of layer mask of hair shadow caster;
## [2.0.2] - 26-Dec-2024 ## [2.0.2] - 26-Dec-2024
### Changed ### Changed

View File

@@ -1,13 +1,10 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor; using UnityEditor;
using Unity.Rendering.Toon;
namespace UnityEditor.Rendering.Toon namespace Misaki.HdrpToon.Editor
{ {
[CustomEditor(typeof(DebugShadowmap))] [CustomEditor(typeof(DebugShadowmap))]
internal class DebugShadowmapInspector : Editor internal class DebugShadowmapInspector : UnityEditor.Editor
{ {
public override void OnInspectorGUI() public override void OnInspectorGUI()
@@ -19,14 +16,14 @@ namespace UnityEditor.Rendering.Toon
bool isChanged = false; var isChanged = false;
var obj = target as DebugShadowmap; var obj = target as DebugShadowmap;
// hi cut filter // hi cut filter
EditorGUI.BeginChangeCheck(); EditorGUI.BeginChangeCheck();
bool showShadow = EditorGUILayout.Toggle(labelDebugShadowmap, obj.m_enableShadowmapDebugging); var showShadow = EditorGUILayout.Toggle(labelDebugShadowmap, obj.m_enableShadowmapDebugging);
if (EditorGUI.EndChangeCheck()) if (EditorGUI.EndChangeCheck())
{ {
Undo.RecordObject(target, "Changed Shadowmap debbuging flag"); Undo.RecordObject(target, "Changed Shadowmap debbuging flag");
@@ -41,7 +38,7 @@ namespace UnityEditor.Rendering.Toon
EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck(); EditorGUI.BeginChangeCheck();
bool binalization = EditorGUILayout.Toggle(labelBinalization, obj.m_enableBinalization); var binalization = EditorGUILayout.Toggle(labelBinalization, obj.m_enableBinalization);
if (EditorGUI.EndChangeCheck()) if (EditorGUI.EndChangeCheck())
{ {
@@ -59,7 +56,7 @@ namespace UnityEditor.Rendering.Toon
EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck(); EditorGUI.BeginChangeCheck();
bool showSlefShadow = EditorGUILayout.Toggle(labelDebugSelfShadow, obj.m_enableSelfShadowDebugging); var showSlefShadow = EditorGUILayout.Toggle(labelDebugSelfShadow, obj.m_enableSelfShadowDebugging);
if (EditorGUI.EndChangeCheck()) if (EditorGUI.EndChangeCheck())
{ {
@@ -72,7 +69,7 @@ namespace UnityEditor.Rendering.Toon
EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck(); EditorGUI.BeginChangeCheck();
bool showOutline = EditorGUILayout.Toggle(labelNoOutline, obj.m_enableOutlineDebugging); var showOutline = EditorGUILayout.Toggle(labelNoOutline, obj.m_enableOutlineDebugging);
if (EditorGUI.EndChangeCheck()) if (EditorGUI.EndChangeCheck())
{ {

View File

@@ -3,7 +3,7 @@ using UnityEditor;
using UnityEngine; using UnityEngine;
using UnityEngine.UIElements; using UnityEngine.UIElements;
namespace Unity.Toonshader.Editor namespace Misaki.HdrpToon.Editor
{ {
public class ConverterInitializer public class ConverterInitializer
{ {

View File

@@ -1,6 +1,6 @@
using UnityEngine; using UnityEngine;
namespace Unity.Toonshader.Editor namespace Misaki.HdrpToon.Editor
{ {
public struct QuaternionToVector3Converter public struct QuaternionToVector3Converter
{ {

View File

@@ -1,16 +1,19 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor; using UnityEditor;
using Unity.Rendering.Toon; using UnityEngine;
namespace UnityEditor.Rendering.Toon
namespace Misaki.HdrpToon.Editor
{ {
[CustomEditor(typeof(ModelToonEvAdjustment))] [CustomEditor(typeof(ModelToonEvAdjustment))]
internal class ModelToonEvAdjustmentInspector : Editor internal class ModelToonEvAdjustmentInspector : UnityEditor.Editor
{ {
SerializedObject m_SerializedObject; SerializedObject m_SerializedObject;
public static AnimationCurve DefaultAnimationCurve()
{
return AnimationCurve.Linear(-10f, -10f, -1.32f, -1.32f);
}
public override void OnInspectorGUI() public override void OnInspectorGUI()
{ {
@@ -20,14 +23,14 @@ namespace UnityEditor.Rendering.Toon
const string labeIgnoreVolumeExposure = "Ignore Volume Exposure"; const string labeIgnoreVolumeExposure = "Ignore Volume Exposure";
const string labelCompensation = "Compensation"; const string labelCompensation = "Compensation";
bool isChanged = false; var isChanged = false;
var obj = target as ModelToonEvAdjustment; var obj = target as ModelToonEvAdjustment;
// hi cut filter // hi cut filter
EditorGUI.BeginChangeCheck(); EditorGUI.BeginChangeCheck();
bool egnoreExposure = EditorGUILayout.Toggle(labeIgnoreVolumeExposure, obj.m_IgnorVolumeExposure); var egnoreExposure = EditorGUILayout.Toggle(labeIgnoreVolumeExposure, obj.m_IgnorVolumeExposure);
if (EditorGUI.EndChangeCheck()) if (EditorGUI.EndChangeCheck())
{ {
Undo.RecordObject(target, "Changed Ignore Volume Exposure"); Undo.RecordObject(target, "Changed Ignore Volume Exposure");
@@ -38,7 +41,7 @@ namespace UnityEditor.Rendering.Toon
// hi cut filter // hi cut filter
EditorGUI.BeginChangeCheck(); EditorGUI.BeginChangeCheck();
bool lightFilterr = EditorGUILayout.Toggle(labelLightHighCutFilter, obj.m_ToonLightHiCutFilter); var lightFilterr = EditorGUILayout.Toggle(labelLightHighCutFilter, obj.m_ToonLightHiCutFilter);
if (EditorGUI.EndChangeCheck()) if (EditorGUI.EndChangeCheck())
{ {
Undo.RecordObject(target, "Changed Light Hi Cut Filter"); Undo.RecordObject(target, "Changed Light Hi Cut Filter");
@@ -50,7 +53,7 @@ namespace UnityEditor.Rendering.Toon
// Compensation // Compensation
EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginHorizontal();
EditorGUI.BeginChangeCheck(); EditorGUI.BeginChangeCheck();
float compensation = EditorGUILayout.FloatField(labelCompensation, obj.m_Compensation); var compensation = EditorGUILayout.FloatField(labelCompensation, obj.m_Compensation);
if (EditorGUI.EndChangeCheck()) if (EditorGUI.EndChangeCheck())
{ {
Undo.RecordObject(target, "Changed Compensation"); Undo.RecordObject(target, "Changed Compensation");
@@ -62,7 +65,7 @@ namespace UnityEditor.Rendering.Toon
// curve // curve
EditorGUI.BeginChangeCheck(); EditorGUI.BeginChangeCheck();
bool exposureAdjustment = EditorGUILayout.Toggle(labelLightAdjustment, obj.m_ExposureAdjustmnt); var exposureAdjustment = EditorGUILayout.Toggle(labelLightAdjustment, obj.m_ExposureAdjustmnt);
if (EditorGUI.EndChangeCheck()) if (EditorGUI.EndChangeCheck())
{ {
Undo.RecordObject(target, "Changed Expsure Adjustment"); Undo.RecordObject(target, "Changed Expsure Adjustment");
@@ -82,7 +85,7 @@ namespace UnityEditor.Rendering.Toon
EditorGUI.BeginChangeCheck(); EditorGUI.BeginChangeCheck();
// var ranges = new Rect(-10, -10, 20, 20); // var ranges = new Rect(-10, -10, 20, 20);
// var curve = EditorGUILayout.CurveField(labelExposureCurave, obj.m_AnimationCurve, Color.green,ranges); // var curve = EditorGUILayout.CurveField(labelExposureCurave, obj.m_AnimationCurve, Color.green,ranges);
AnimationCurve curve = EditorGUILayout.CurveField(labelLightAdjustmentCurve, obj.m_AnimationCurve); var curve = EditorGUILayout.CurveField(labelLightAdjustmentCurve, obj.m_AnimationCurve);
if (EditorGUI.EndChangeCheck()) if (EditorGUI.EndChangeCheck())
{ {
@@ -91,11 +94,11 @@ namespace UnityEditor.Rendering.Toon
isChanged = true; isChanged = true;
} }
EditorGUI.BeginChangeCheck(); EditorGUI.BeginChangeCheck();
bool buttonIsPressed = GUILayout.Button("Reset", GUILayout.Width(50)); var buttonIsPressed = GUILayout.Button("Reset", GUILayout.Width(50));
var curve2 = obj.m_AnimationCurve; var curve2 = obj.m_AnimationCurve;
if (buttonIsPressed) if (buttonIsPressed)
{ {
curve2 = SceneToonEvAdjustment.DefaultAnimationCurve(); curve2 = DefaultAnimationCurve();
} }
if (EditorGUI.EndChangeCheck()) if (EditorGUI.EndChangeCheck())
{ {
@@ -134,7 +137,7 @@ namespace UnityEditor.Rendering.Toon
float ConvertFromEV100(float EV100) float ConvertFromEV100(float EV100)
{ {
float val = Mathf.Pow(2, EV100) * 2.5f; var val = Mathf.Pow(2, EV100) * 2.5f;
return val; return val;
} }
@@ -155,7 +158,7 @@ namespace UnityEditor.Rendering.Toon
var go = Selection.activeGameObject; var go = Selection.activeGameObject;
if (go == null) if (go == null)
go.AddComponent<ModelToonEvAdjustment>(); go.AddComponent<ModelToonEvAdjustment>();
else else
{ {
Debug.LogError("Please, select a GameObject you want to attach."); Debug.LogError("Please, select a GameObject you want to attach.");

View File

@@ -1,9 +1,8 @@
using Unity.Rendering.HighDefinition.Toon;
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
using UnityEngine.UIElements; using UnityEngine.UIElements;
namespace Unity.Toonshader.Editor namespace Misaki.HdrpToon.Editor
{ {
[CustomEditor(typeof(BoxLightAdjustment))] [CustomEditor(typeof(BoxLightAdjustment))]
public class BoxLightAdjustmentView : UnityEditor.Editor public class BoxLightAdjustmentView : UnityEditor.Editor

View File

@@ -1,10 +1,10 @@
<engine:UXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:engine="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../../../../UIElementsSchema/UIElements.xsd" editor-extension-mode="True"> <engine:UXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:engine="UnityEngine.UIElements" xmlns:editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../../../../UIElementsSchema/UIElements.xsd" editor-extension-mode="True">
<engine:VisualElement data-source-type="Unity.Rendering.HighDefinition.Toon.BoxLightAdjustment, Unity.Toonshader" style="flex-grow: 1;"> <engine:VisualElement data-source-type="Misaki.HdrpToon.BoxLightAdjustment, Misaki.HdrpToon" style="flex-grow: 1;">
<engine:Label text="Rendering" style="-unity-font-style: bold; margin-top: 4px; margin-bottom: 2px;" /> <engine:Label text="Rendering" style="-unity-font-style: bold; margin-top: 4px; margin-bottom: 2px;" />
<engine:VisualElement name="renderingGroup" style="padding-left: 8px;"> <engine:VisualElement name="renderingGroup" style="padding-left: 8px;">
<editor:RenderingLayerMaskField label="Layer Mask" value="DynamicTransform" type="UnityEngine.Rendering.HighDefinition.RenderingLayerMask, Unity.RenderPipelines.HighDefinition.Runtime"> <editor:RenderingLayerMaskField label="Layer Mask" value="DynamicTransform" type="UnityEngine.Rendering.HighDefinition.RenderingLayerMask, Unity.RenderPipelines.HighDefinition.Runtime">
<Bindings> <Bindings>
<engine:DataBinding property="value" data-source-path="LayerMask" data-source-type="Unity.Rendering.HighDefinition.Toon.BoxLightAdjustment, Unity.Toonshader" binding-mode="TwoWay" /> <engine:DataBinding property="value" data-source-path="LayerMask" binding-mode="TwoWay" />
</Bindings> </Bindings>
</editor:RenderingLayerMaskField> </editor:RenderingLayerMaskField>
<editor:ObjectField label="Source Light" type="UnityEngine.Light, UnityEngine.CoreModule"> <editor:ObjectField label="Source Light" type="UnityEngine.Light, UnityEngine.CoreModule">
@@ -30,21 +30,11 @@
<engine:DataBinding property="index" data-source-path="followGameObjectPosition" binding-mode="TwoWay" /> <engine:DataBinding property="index" data-source-path="followGameObjectPosition" binding-mode="TwoWay" />
</Bindings> </Bindings>
</engine:DropdownField> </engine:DropdownField>
<engine:DropdownField label="Follow Rotation" choices="Disable,Enable" index="0"> <engine:FloatField label="Distance Offset" value="20">
<Bindings> <Bindings>
<engine:DataBinding property="index" data-source-path="followGameObjectRotation" binding-mode="TwoWay" /> <engine:DataBinding property="value" data-source-path="distanceOffset" binding-mode="TwoWay" />
</Bindings> </Bindings>
</engine:DropdownField> </engine:FloatField>
<engine:Vector3Field label="Position Offset">
<Bindings>
<engine:DataBinding property="value" data-source-path="positionOffset" binding-mode="TwoWay" />
</Bindings>
</engine:Vector3Field>
<engine:Vector3Field label="Rotation Offset">
<Bindings>
<engine:DataBinding property="value" data-source-path="rotationOffset" binding-mode="TwoWay" source-to-ui-converters="QuaternionToVector3Converter" ui-to-source-converters="QuaternionToVector3Converter" />
</Bindings>
</engine:Vector3Field>
</engine:VisualElement> </engine:VisualElement>
</engine:VisualElement> </engine:VisualElement>
</engine:UXML> </engine:UXML>

View File

@@ -0,0 +1,23 @@
namespace Misaki.HdrpToon.Editor
{
public enum ShaderGUIExpandable : uint
{
SurfaceOptions = 1 << 0,
ShadingColor = 1 << 1,
ShadingGrade = 1 << 2,
MaterialFeature = 1 << 3,
PBR = 1 << 4,
AmbientMode = 1 << 5,
Highlight = 1 << 6,
Rimlight = 1 << 7,
MatCap = 1 << 8,
AngelRing = 1 << 9,
Emission = 1 << 10,
Outline = 1 << 11,
TessellationLegacy = 1 << 12,
TessellationHDRP = 1 << 13,
SceneLight = 1 << 14,
EnvironmentalLightEffectiveness = 1 << 15,
MetaverseSettings = 1 << 16,
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 63067f176ae106c459bcb9cc105f626d

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: 29660dd543a3ad04ea860b6366d28b54 guid: bc8d991d265341a4598574f90fc0e21c
folderAsset: yes folderAsset: yes
DefaultImporter: DefaultImporter:
externalObjects: {} externalObjects: {}

View File

@@ -0,0 +1,52 @@
using Misaki.ShaderGUI;
using UnityEditor;
using UnityEngine;
namespace Misaki.HdrpToon.Editor
{
internal class AngelRingScope : MaterialUIScope<ShaderGUIExpandable>
{
private static class Properties
{
public static MaterialProperty angelRingColor;
public static MaterialProperty angelRingColorMap;
public static MaterialProperty angelRingIntensity;
public static MaterialProperty angelRingOffsetU;
public static MaterialProperty angelRingOffsetV;
}
private static class Styles
{
public static readonly GUIContent angelRingColorText = new("Angel Ring Color", "Specifies the color of the angel ring.");
public static readonly GUIContent angelRingIntensityText = new("Angel Ring Intensity", "Specifies the intensity of the angel ring.");
public static readonly GUIContent angelRingOffsetUText = new("Angel Ring Offset U", "Specifies the offset of the angel ring in the U direction.");
public static readonly GUIContent angelRingOffsetVText = new("Angel Ring Offset V", "Specifies the offset of the angel ring in the V direction.");
}
protected override bool ShowSection => SurfaceOptionsScope.HasFeature(SurfaceFeatureFlags.AngelRing);
protected override ShaderGUIExpandable ExpandableBit => ShaderGUIExpandable.AngelRing;
protected override GUIContent Header => EditorGUIUtility.TrTextContent("Angel Ring Settings");
public override void LoadMaterialProperties()
{
Properties.angelRingColor = FindProperty("_AngelRingColor");
Properties.angelRingColorMap = FindProperty("_AngelRingColorMap");
Properties.angelRingIntensity = FindProperty("_AngelRingIntensity");
Properties.angelRingOffsetU = FindProperty("_AngelRingOffsetU");
Properties.angelRingOffsetV = FindProperty("_AngelRingOffsetV");
}
protected override void DrawContent()
{
editor.TexturePropertySingleLine(Styles.angelRingColorText, Properties.angelRingColorMap, Properties.angelRingColor);
editor.ShaderProperty(Properties.angelRingIntensity, Styles.angelRingIntensityText);
editor.ShaderProperty(Properties.angelRingOffsetU, Styles.angelRingOffsetUText);
editor.ShaderProperty(Properties.angelRingOffsetV, Styles.angelRingOffsetVText);
EditorGUILayout.Space();
editor.TextureScaleOffsetProperty(Properties.angelRingColorMap);
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f21124eb2f73ac14e8cda9a0340191cd

View File

@@ -0,0 +1,65 @@
using Misaki.ShaderGUI;
using UnityEditor;
using UnityEngine;
namespace Misaki.HdrpToon.Editor
{
internal class OutlineScope : MaterialUIScope<ShaderGUIExpandable>
{
private static class Properties
{
public static MaterialProperty outlineWidth;
public static MaterialProperty outlineWidthMap;
public static MaterialProperty outlineColor;
public static MaterialProperty outlineColorMap;
public static MaterialProperty albedoAffectOutline;
public static MaterialProperty fadeIn;
public static MaterialProperty fadeOut;
public static MaterialProperty useSmoothedNormal;
}
private static class Styles
{
public static readonly GUIContent outlineWidthText = new("Outline Width", "Specifies the width of the outline.");
public static readonly GUIContent outlineColorText = new("Outline Color", "Specifies the color of the outline.");
public static readonly GUIContent albedoAffectOutlineText = new("Albedo Affect Outline", "Enable to affect the outline color with the albedo color.");
public static readonly GUIContent fadeInText = new("Fade In Distance", "Specify the nearest distance, where the outline width changes with the distance between the camera and the object. The outline will be the maximum width at this distance.");
public static readonly GUIContent fadeOutText = new("Fade Out Distance", "Specify the furthest distance, where the outline width changes with the distance between the camera and the object. The outline will be zero at this distance.");
public static readonly GUIContent useSmoothedNormalText = new("Use Smoothed Normal", "Enable to use smoothed normal(that packed in uv2) for outline calculation.");
}
protected override bool ShowSection => SurfaceOptionsScope.HasFeature(SurfaceFeatureFlags.Outline);
protected override ShaderGUIExpandable ExpandableBit => ShaderGUIExpandable.Outline;
protected override GUIContent Header => EditorGUIUtility.TrTextContent("Outline Settings");
public override void LoadMaterialProperties()
{
Properties.outlineWidth = FindProperty("_OutlineWidth");
Properties.outlineWidthMap = FindProperty("_OutlineWidthMap");
Properties.outlineColor = FindProperty("_OutlineColor");
Properties.outlineColorMap = FindProperty("_OutlineColorMap");
Properties.albedoAffectOutline = FindProperty("_AlbedoAffectOutline");
Properties.fadeIn = FindProperty("_OutlineFadeIn");
Properties.fadeOut = FindProperty("_OutlineFadeOut");
Properties.useSmoothedNormal = FindProperty("_UseSmoothedNormal");
}
protected override void DrawContent()
{
editor.TexturePropertySingleLine(Styles.outlineWidthText, Properties.outlineWidthMap, Properties.outlineWidth);
editor.TexturePropertySingleLine(Styles.outlineColorText, Properties.outlineColorMap, Properties.outlineColor);
editor.ShaderProperty(Properties.albedoAffectOutline, Styles.albedoAffectOutlineText);
editor.ShaderProperty(Properties.fadeIn, Styles.fadeInText);
editor.ShaderProperty(Properties.fadeOut, Styles.fadeOutText);
editor.ShaderProperty(Properties.useSmoothedNormal, Styles.useSmoothedNormalText);
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: ac42903bc14e05f41a9a06d1e6cf5cd9

View File

@@ -0,0 +1,224 @@
using System.Linq;
using Misaki.ShaderGUI;
using UnityEditor;
using UnityEditor.Rendering;
using UnityEngine;
using UnityEngine.Rendering;
namespace Misaki.HdrpToon.Editor
{
public class PBRScope : MaterialUIScope<ShaderGUIExpandable>
{
private static class Properties
{
public static MaterialProperty PbrMode;
public static MaterialProperty NormalMap;
public static MaterialProperty NormalMapScale;
public static MaterialProperty MaskMap;
public static MaterialProperty Metallic;
public static MaterialProperty MetallicRemapMin;
public static MaterialProperty MetallicRemapMax;
public static MaterialProperty AORemapMin;
public static MaterialProperty AORemapMax;
public static MaterialProperty RoughnessRemapMin;
public static MaterialProperty RoughnessRemapMax;
public static MaterialProperty Smoothness;
public static MaterialProperty AnisotropyMap;
public static MaterialProperty Anisotropy;
public static MaterialProperty KKColor;
public static MaterialProperty BSDFContribution;
public static MaterialProperty SpecularColorMap;
public static MaterialProperty SpecularColor;
public static MaterialProperty SpecularFeather;
public static MaterialProperty SpecularStep;
}
private static class Styles
{
public static readonly GUIContent PbrModeText = new("PBR Mode", "PBR Mode");
public static readonly GUIContent NormalMapText =
new("Normal Map", "A texture that dictates the bumpiness of the material.");
public static readonly GUIContent MaskMapText = new("Mask Map",
"A texture that dictates the physical properties of the material. R: Metallic, G: Occlusion, A: Smoothness");
public static readonly GUIContent MetallicText =
new("Metallic", "Specifies the metallicness of the material.");
public static readonly GUIContent MetallicRemap =
new("Metallic Remap", "Remap the max and min value of metallic");
public static readonly GUIContent AORemap =
new GUIContent("AO Remap", "Remap the max and min value of ambient occlusion");
public static readonly GUIContent RoughnessRemap =
new GUIContent("Smoothness Remap", "Remap the max and min value of smoothness");
public static readonly GUIContent SmoothnessText =
new("Smoothness", "Specifies the smoothness of the material.");
public static readonly GUIContent AnisotropyMapText =
new("Anisotropy Map", "Specifies the anisotropy map of the material.");
public static readonly GUIContent KKColorText = new("KK specular Color",
"Specifies the color of KK specular.");
public static readonly GUIContent BSDFContributionText = new("BSDF Contribution",
"BSDF smoothness contribution, 1 means KK Hair smoothness will fully contribute bsdf calculation");
public static readonly GUIContent SpecularColorMapText = new("Specular Color Map",
"Specifies the specular color map of the material.");
public static readonly GUIContent SpecRemap = new("Specular Remap",
"Feather and step value of Toon Specular");
}
public override void LoadMaterialProperties()
{
Properties.PbrMode = FindProperty("_PBR_Mode");
Properties.NormalMap = FindProperty("_NormalMap");
Properties.NormalMapScale = FindProperty("_NormalScale");
Properties.MaskMap = FindProperty("_MaskMap");
Properties.Metallic = FindProperty("_Metallic");
Properties.MetallicRemapMin = FindProperty("_MetallicRemapMin");
Properties.MetallicRemapMax = FindProperty("_MetallicRemapMax");
Properties.AORemapMin = FindProperty("_AORemapMin");
Properties.AORemapMax = FindProperty("_AORemapMax");
Properties.RoughnessRemapMin = FindProperty("_SmoothnessRemapMin");
Properties.RoughnessRemapMax = FindProperty("_SmoothnessRemapMax");
Properties.Smoothness = FindProperty("_Smoothness");
Properties.AnisotropyMap = FindProperty("_AnisotropyMap");
Properties.Anisotropy = FindProperty("_Anisotropy");
Properties.KKColor = FindProperty("_KKColor");
Properties.BSDFContribution = FindProperty("_BSDFContribution");
Properties.SpecularColorMap = FindProperty("_SpecularColorMap");
Properties.SpecularColor = FindProperty("_SpecularColor");
Properties.SpecularFeather = FindProperty("_ToonSpecularFeather");
Properties.SpecularStep = FindProperty("_ToonSpecularStep");
}
protected override void DrawContent()
{
editor.ShaderProperty(Properties.PbrMode, Styles.PbrModeText);
EditorGUILayout.Space();
editor.TexturePropertySingleLine(Styles.NormalMapText, Properties.NormalMap, Properties.NormalMapScale);
var materials = GetMaterials().ToList();
foreach (Material material in materials)
{
material.SetKeyword(new LocalKeyword(material.shader, "_NORMAL_MAP"),
Properties.NormalMap.textureValue != null);
}
PBRMode pbrMode = (PBRMode)Properties.PbrMode.floatValue;
if (pbrMode != PBRMode.Off)
{
editor.TexturePropertySingleLine(Styles.MaskMapText, Properties.MaskMap);
if (Properties.MaskMap.textureValue == null)
{
foreach (Material material in materials)
{
material.DisableKeyword(new LocalKeyword(material.shader, "_MASK_MAP"));
}
if (pbrMode != PBRMode.KKHair)
editor.ShaderProperty(Properties.Metallic, Styles.MetallicText);
editor.ShaderProperty(Properties.Smoothness, Styles.SmoothnessText);
}
else
{
foreach (Material material in materials)
{
material.EnableKeyword(new LocalKeyword(material.shader, "_MASK_MAP"));
}
editor.MinMaxShaderProperty(Properties.MetallicRemapMin, Properties.MetallicRemapMax, 0, 1,
Styles.MetallicRemap);
editor.MinMaxShaderProperty(Properties.AORemapMin, Properties.AORemapMax, 0, 1, Styles.AORemap);
editor.MinMaxShaderProperty(Properties.RoughnessRemapMin, Properties.RoughnessRemapMax, 0, 1,
Styles.RoughnessRemap);
}
}
else
{
foreach (Material material in materials)
{
material.DisableKeyword(new LocalKeyword(material.shader, "_MASK_MAP"));
material.DisableKeyword(new LocalKeyword(material.shader, "_ANISOTROPY_MAP"));
material.DisableKeyword(new LocalKeyword(material.shader, "_SPECULAR_COLOR_MAP"));
}
}
switch (pbrMode)
{
case PBRMode.Anisotropy or PBRMode.KKHair:
{
editor.TexturePropertySingleLine(Styles.AnisotropyMapText, Properties.AnisotropyMap,
Properties.Anisotropy);
if (pbrMode == PBRMode.KKHair)
{
editor.ShaderProperty(Properties.KKColor, Styles.KKColorText);
editor.ShaderProperty(Properties.BSDFContribution, Styles.BSDFContributionText);
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Anisotropy Map only ST");
editor.TextureScaleOffsetProperty(Properties.AnisotropyMap);
if (Properties.AnisotropyMap.textureValue == null)
{
foreach (Material material in materials)
{
material.DisableKeyword(new LocalKeyword(material.shader, "_ANISOTROPY_MAP"));
}
}
else
{
foreach (Material material in materials)
{
material.EnableKeyword(new LocalKeyword(material.shader, "_ANISOTROPY_MAP"));
}
}
break;
}
case PBRMode.Toon:
{
editor.TexturePropertySingleLine(Styles.SpecularColorMapText, Properties.SpecularColorMap,
Properties.SpecularColor);
if (Properties.SpecularColorMap.textureValue == null)
{
foreach (Material material in materials)
{
material.DisableKeyword(new LocalKeyword(material.shader, "_SPECULAR_COLOR_MAP"));
}
}
else
{
foreach (Material material in materials)
{
material.EnableKeyword(new LocalKeyword(material.shader, "_SPECULAR_COLOR_MAP"));
}
}
editor.MinMaxShaderProperty(Properties.SpecularFeather, Properties.SpecularStep, 0, 1,
Styles.SpecRemap);
break;
}
}
}
private enum PBRMode
{
Off,
Standard,
Anisotropy,
KKHair,
Toon
}
protected override ShaderGUIExpandable ExpandableBit => ShaderGUIExpandable.PBR;
protected override GUIContent Header => new("PBR Settings");
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f611f3d462b5414f9241ed80e4f1d0bb
timeCreated: 1738325165

View File

@@ -0,0 +1,142 @@
using Misaki.ShaderGUI;
using UnityEditor;
using UnityEngine;
namespace Misaki.HdrpToon.Editor
{
public class RimLightScope : MaterialUIScope<ShaderGUIExpandable>
{
private static class Properties
{
public static MaterialProperty rimLightEnabled;
public static MaterialProperty rimLightColor;
public static MaterialProperty rimLightStrength;
public static MaterialProperty rimLightLevel;
public static MaterialProperty colorBlendingMode;
public static MaterialProperty adjustRimLightArea;
public static MaterialProperty rimLightFeatherOff;
public static MaterialProperty lightDirection;
public static MaterialProperty lightDirectionRimLightLevel;
public static MaterialProperty invertedDirectionRimLight;
public static MaterialProperty invertedRimLightColor;
public static MaterialProperty inversedRimLightLevel;
public static MaterialProperty invertedRimLightFeatherOff;
public static MaterialProperty rimLightMaskMap;
public static MaterialProperty rimLightMaskLevel;
}
private static class Styles
{
public static readonly GUIContent rimLightEnabledText = new("Rim Light",
"A light that hits the 3D model from behind and emphasizes the contours of the model from the front.");
public static readonly GUIContent rimLightColorText =
new("Rim Light Color", "Specifies the color of rim light.");
public static readonly GUIContent rimLightStrengthText =
new("Rim Light Strength", "Specifies Rim Light strength.");
public static readonly GUIContent rimLightLevelText =
new("Rim Light Level", "Specifies Rim Light power intensity.");
public static readonly GUIContent colorBlendingModeText =
new("Color Blending Mode", "Rim light color blending mode. Multiply or Add.");
public static readonly GUIContent adjustRimLightAreaText =
new("Adjust Rim Light Area", "Increasing this value narrows the area of influence of Rim Light.");
public static readonly GUIContent rimLightFeatherOffText =
new("Rim Light Feather Off", "Disable Rim light feather.");
public static readonly GUIContent lightDirectionText =
new("Light Direction",
"When Enabled, rim light is generated only in the direction of the light source.");
public static readonly GUIContent lightDirectionRimLightLevelText =
new("Light Direction Rim Light Level",
"Specifies intensity of Rim Light in the light source direction,");
public static readonly GUIContent invertedDirectionRimLightText =
new("Inverted Direction Rim Light", "Rim light from inverted/antipodean direction.");
public static readonly GUIContent invertedRimLightColorText =
new("Inverted Rim Light Color", "Specifies the color of inverted/antipodean rim light.");
public static readonly GUIContent inversedRimLightLevelText =
new("Inversed Rim Light Level", "Specifies Inverted/Antipodean Rim Light Level.");
public static readonly GUIContent invertedRimLightFeatherOffText =
new("Inverted Rim Light Feather Off", "Disable Inverted Rim light feather.");
public static readonly GUIContent rimLightMaskMapText = new("Rim Light Mask",
"Rim Light Mask : Texture(linear). The white part of the texture is displayed as Rim Light, and the black part is masked and not displayed.");
public static readonly GUIContent rimLightMaskLevelText =
new("Rim Light Mask Level",
"-1 gives 0% for the Rim Light effect, 0 gives 100% for the Rim Light and Mask effect, 1 gives 100% for the Rim Light and 0% for the Mask effect.");
}
public override void LoadMaterialProperties()
{
Properties.rimLightEnabled = FindProperty("_RimLight");
Properties.rimLightColor = FindProperty("_RimLightColor");
Properties.rimLightStrength = FindProperty("_RimLight_Strength");
Properties.rimLightLevel = FindProperty("_RimLight_Power");
Properties.colorBlendingMode = FindProperty("_Is_BlendAddToRimColor");
Properties.adjustRimLightArea = FindProperty("_RimLight_InsideMask");
Properties.rimLightFeatherOff = FindProperty("_RimLight_FeatherOff");
Properties.lightDirection = FindProperty("_LightDirection_MaskOn");
Properties.lightDirectionRimLightLevel = FindProperty("_Tweak_LightDirection_MaskLevel");
Properties.invertedDirectionRimLight = FindProperty("_Add_Antipodean_RimLight");
Properties.invertedRimLightColor = FindProperty("_Ap_RimLightColor");
Properties.inversedRimLightLevel = FindProperty("_Ap_RimLight_Power");
Properties.invertedRimLightFeatherOff = FindProperty("_Ap_RimLight_FeatherOff");
Properties.rimLightMaskMap = FindProperty("_Set_RimLightMask");
Properties.rimLightMaskLevel = FindProperty("_Tweak_RimLightMaskLevel");
}
protected override void DrawContent()
{
editor.ShaderProperty(Properties.rimLightEnabled, Styles.rimLightEnabledText);
EditorGUI.BeginDisabledGroup(Properties.rimLightEnabled.floatValue == 0);
{
EditorGUI.indentLevel++;
editor.ShaderProperty(Properties.rimLightColor, Styles.rimLightColorText);
editor.ShaderProperty(Properties.rimLightStrength, Styles.rimLightStrengthText);
editor.ShaderProperty(Properties.rimLightLevel, Styles.rimLightLevelText);
editor.ShaderProperty(Properties.colorBlendingMode, Styles.colorBlendingModeText);
editor.ShaderProperty(Properties.adjustRimLightArea, Styles.adjustRimLightAreaText);
editor.ShaderProperty(Properties.rimLightFeatherOff, Styles.rimLightFeatherOffText);
editor.ShaderProperty(Properties.lightDirection, Styles.lightDirectionText);
EditorGUI.BeginDisabledGroup(Properties.lightDirection.floatValue == 0);
{
EditorGUI.indentLevel++;
editor.ShaderProperty(Properties.lightDirectionRimLightLevel,
Styles.lightDirectionRimLightLevelText);
editor.ShaderProperty(Properties.invertedDirectionRimLight,
Styles.invertedDirectionRimLightText);
EditorGUI.BeginDisabledGroup(Properties.invertedDirectionRimLight.floatValue == 0);
{
EditorGUI.indentLevel++;
editor.ShaderProperty(Properties.invertedRimLightColor, Styles.invertedRimLightColorText);
editor.ShaderProperty(Properties.inversedRimLightLevel, Styles.inversedRimLightLevelText);
editor.ShaderProperty(Properties.invertedRimLightFeatherOff,
Styles.invertedRimLightFeatherOffText);
}
EditorGUI.EndDisabledGroup();
EditorGUI.indentLevel--;
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.Space();
EditorGUI.indentLevel--;
editor.TexturePropertySingleLine(Styles.rimLightMaskMapText, Properties.rimLightMaskMap);
editor.ShaderProperty(Properties.rimLightMaskLevel, Styles.rimLightMaskLevelText);
}
EditorGUI.EndDisabledGroup();
}
protected override ShaderGUIExpandable ExpandableBit => ShaderGUIExpandable.Rimlight;
protected override GUIContent Header => EditorGUIUtility.TrTextContent("Rim Light Settings");
protected override bool ShowSection => SurfaceOptionsScope.HasFeature(SurfaceFeatureFlags.RimLight);
}
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c18934f763fe4f3cb5e6f02599209764
timeCreated: 1738311777

View File

@@ -0,0 +1,148 @@
using Misaki.ShaderGUI;
using UnityEditor;
using UnityEngine;
namespace Misaki.HdrpToon.Editor
{
public class ShadingColorScope : MaterialUIScope<ShaderGUIExpandable>
{
private static class Properties
{
public static MaterialProperty baseColor;
public static MaterialProperty baseColorMap;
public static MaterialProperty applyTo1stShadingMapEnable;
public static MaterialProperty firstShadingColor;
public static MaterialProperty firstShadingMap;
public static MaterialProperty applyTo2ndShadingMapEnable;
public static MaterialProperty secondShadingColor;
public static MaterialProperty secondShadingMap;
public static MaterialProperty sdfShadowMap;
public static MaterialProperty sdfShadowLevel;
public static MaterialProperty sdfSmoothLevel;
public static MaterialProperty sdfHighlightStrength;
public static MaterialProperty sdfHighlightSmoothLevel;
public static MaterialProperty shadingGradeMap;
public static MaterialProperty shadingIndex;
}
private static class Styles
{
public static readonly GUIContent baseMapText = new("Base Map", "Base Color : Texture(sRGB) x Color(RGB) Default:White");
public static readonly GUIContent applyTo1stShadingMapText = new("Apply to 1st shading map", "Apply Base map to the 1st shading map.");
public static readonly GUIContent firstShadingMapText = new("1st Shading Map", "The map used for the brighter portions of the shadow.");
public static readonly GUIContent applyTo2ndShadingMapText = new("Apply to 2nd shading map", "Apply Base map or the 1st shading map to the 2st shading map.");
public static readonly GUIContent secondShadingMapText = new("2nd Shading Map", "The map used for the darker portions of the shadow.");
public static readonly GUIContent sdfShadowMapText = new("SDF Shadow Map", "SDF Shadow Map");
public static readonly GUIContent sdfShadowLevelText = new("SDF Shadow Level", "SDF Shadow Level");
public static readonly GUIContent sdfSmoothLevelText = new("SDF Smooth Level", "SDF Smooth Level");
public static readonly GUIContent sdfHighlightStrengthText = new("SDF Highlight Strength", "SDF Highlight Strength");
public static readonly GUIContent sdfHighlightSmoothLevelText = new("SDF Highlight Smooth Level", "SDF Highlight Smooth Level");
public static readonly GUIContent shadingGradeMapText = new("Shading Grade Map", "Shading Grade Map");
public static readonly GUIContent shadingIndexText = new("Shading Index", "The index to choose when sampling the texture 2d array.");
}
protected override ShaderGUIExpandable ExpandableBit => ShaderGUIExpandable.ShadingColor;
protected override GUIContent Header => EditorGUIUtility.TrTextContent("Shading Color Settings");
private void DrawSecondShadingMapProperties()
{
EditorGUI.indentLevel += 2;
editor.ShaderProperty(Properties.applyTo2ndShadingMapEnable, Styles.applyTo2ndShadingMapText);
EditorGUI.indentLevel -= 2;
if (Mathf.Approximately(Properties.applyTo2ndShadingMapEnable.floatValue, 1))
{
EditorGUI.indentLevel += 2;
editor.ColorProperty(Properties.secondShadingColor, Styles.secondShadingMapText.text);
EditorGUI.indentLevel -= 2;
}
else
{
editor.TexturePropertySingleLine(Styles.secondShadingMapText, Properties.secondShadingMap,
Properties.secondShadingColor);
}
}
private void DrawFirstShadingMapProperties()
{
EditorGUI.indentLevel += 2;
editor.ShaderProperty(Properties.applyTo1stShadingMapEnable, Styles.applyTo1stShadingMapText);
EditorGUI.indentLevel -= 2;
if (Mathf.Approximately(Properties.applyTo1stShadingMapEnable.floatValue, 1))
{
EditorGUI.indentLevel += 2;
editor.ColorProperty(Properties.firstShadingColor, Styles.firstShadingMapText.text);
EditorGUI.indentLevel -= 2;
}
else
{
editor.TexturePropertySingleLine(Styles.firstShadingMapText, Properties.firstShadingMap,
Properties.firstShadingColor);
}
}
private void DrawSDFProperties()
{
editor.TexturePropertySingleLine(Styles.sdfShadowMapText, Properties.sdfShadowMap);
editor.ShaderProperty(Properties.sdfShadowLevel, Styles.sdfShadowLevelText);
editor.ShaderProperty(Properties.sdfSmoothLevel, Styles.sdfSmoothLevelText);
editor.ShaderProperty(Properties.sdfHighlightStrength, Styles.sdfHighlightStrengthText);
editor.ShaderProperty(Properties.sdfHighlightSmoothLevel, Styles.sdfHighlightSmoothLevelText);
}
private void DrawShadingGradeProperties()
{
editor.TexturePropertySingleLine(Styles.shadingGradeMapText, Properties.shadingGradeMap);
editor.ShaderProperty(Properties.shadingIndex, Styles.shadingIndexText);
}
public override void LoadMaterialProperties()
{
Properties.baseColor = FindProperty("_BaseColor");
Properties.baseColorMap = FindProperty("_BaseColorMap");
Properties.applyTo1stShadingMapEnable = FindProperty("_UseBaseAs1st");
Properties.firstShadingColor = FindProperty("_1stShadeColor");
Properties.firstShadingMap = FindProperty("_1stShadeColorMap");
Properties.applyTo2ndShadingMapEnable = FindProperty("_Use1stAs2nd");
Properties.secondShadingColor = FindProperty("_2ndShadeColor");
Properties.secondShadingMap = FindProperty("_2ndShadeColorMap");
Properties.sdfShadowMap = FindProperty("_SDFShadowMap");
Properties.sdfShadowLevel = FindProperty("_SDFShadowLevel");
Properties.sdfSmoothLevel = FindProperty("_SDFSmoothLevel");
Properties.sdfHighlightStrength = FindProperty("_SDFHighlightStrength");
Properties.sdfHighlightSmoothLevel = FindProperty("_SDFHighlightSmoothLevel");
Properties.shadingGradeMap = FindProperty("_ShadingGradeMap");
Properties.shadingIndex = FindProperty("_ShadingIndex");
}
protected override void DrawContent()
{
editor.TexturePropertySingleLine(Styles.baseMapText, Properties.baseColorMap, Properties.baseColor);
switch (SurfaceOptionsScope.GetShadingMode())
{
case ShadingMode.ThreeColorStep:
DrawFirstShadingMapProperties();
DrawSecondShadingMapProperties();
break;
case ShadingMode.SDF:
DrawSDFProperties();
break;
case ShadingMode.Ramp:
DrawShadingGradeProperties();
break;
default:
break;
}
EditorGUILayout.Space();
editor.TextureScaleOffsetProperty(Properties.baseColorMap);
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 35d7c7fd9279ea64199f1aa61c24fbcd

View File

@@ -0,0 +1,23 @@
using Misaki.ShaderGUI;
using UnityEditor;
using UnityEngine;
namespace Misaki.HdrpToon.Editor
{
public class ShadingGradeScope : MaterialUIScope<ShaderGUIExpandable>
{
protected override ShaderGUIExpandable ExpandableBit => ShaderGUIExpandable.ShadingGrade;
protected override GUIContent Header => EditorGUIUtility.TrTextContent("Shading Grade Settings");
public override void LoadMaterialProperties()
{
throw new System.NotImplementedException();
}
protected override void DrawContent()
{
throw new System.NotImplementedException();
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: faf2eabd1c2767d40a2ecfe89cb56d28

View File

@@ -0,0 +1,116 @@
using Misaki.ShaderGUI;
using UnityEditor;
using UnityEngine;
namespace Misaki.HdrpToon.Editor
{
internal class SurfaceOptionsScope : MaterialUIScope<ShaderGUIExpandable>
{
private static class Properties
{
public static MaterialProperty transparentMode;
public static MaterialProperty alphaClipEnable;
public static MaterialProperty alphaClip;
public static MaterialProperty cullMode;
public static MaterialProperty shadingMode;
public static MaterialProperty materialType;
public static MaterialProperty pbrMode;
public static MaterialProperty receiveHairShadow;
public static MaterialProperty hairBlendingTarget;
public static MaterialProperty surfaceFeatures;
}
private static class Styles
{
public static readonly GUIContent transparentModeText = new("Transparent Mode", "Enable different modes that allow the simulation of a variety of transparent objects.");
public static readonly GUIContent alphaClipEnableText = new("Alpha Clipping", "Enable alpha clipping.");
public static readonly GUIContent alphaClipText = new("Alpha Clipping Threshold", "Threshold for alpha clipping.");
public static readonly GUIContent cullingModeText = new("Culling Mode", "Controls the sides of polygons that should not be drawn (culled).");
public static readonly GUIContent shadingModeText = new("Shading Color Mode", "Specifies the shading grade mode.");
public static readonly GUIContent materialTypeText = new("Material Type", "Specifies the material type.");
public static readonly GUIContent pbrModeText = new("PBR Mode", "Specifies PBR model mode.");
public static readonly GUIContent receiveHairShadowText = new("Receive Hair Shadow", "Enable to receive shadow from hair shadow caster");
public static readonly GUIContent hairBlendingTargetText = new("Hair Blending Target", "Enable to be blended with hair");
public static readonly GUIContent surfaceFeaturesText = new("Surface Features", "Specifies the surface features.");
}
protected override ShaderGUIExpandable ExpandableBit => ShaderGUIExpandable.SurfaceOptions;
protected override GUIContent Header => EditorGUIUtility.TrTextContent("Surface Options");
public static ShadingMode GetShadingMode()
{
return (ShadingMode)Properties.shadingMode.floatValue;
}
public static bool HasFeature(SurfaceFeatureFlags feature)
{
return ((SurfaceFeatureFlags)Properties.surfaceFeatures.floatValue & feature) != 0;
}
public override void LoadMaterialProperties()
{
Properties.transparentMode = FindProperty("_TransparentEnabled");
Properties.alphaClipEnable = FindProperty("_AlphaCutoffEnable");
Properties.alphaClip = FindProperty("_AlphaCutoff");
Properties.cullMode = FindProperty("_CullMode");
Properties.shadingMode = FindProperty("_Shading_Mode");
Properties.materialType = FindProperty("_Material_Type");
Properties.pbrMode = FindProperty("_PBR_Mode");
Properties.receiveHairShadow = FindProperty("_Receive_Hair_Shadow");
Properties.hairBlendingTarget = FindProperty("_HairBlendingTarget");
Properties.surfaceFeatures = FindProperty("_SurfaceFeatures");
}
protected override void DrawContent()
{
editor.ShaderProperty(Properties.transparentMode, Styles.transparentModeText);
editor.ShaderProperty(Properties.alphaClipEnable, Styles.alphaClipEnableText);
if (Properties.alphaClipEnable.floatValue == 1.0f)
{
EditorGUI.indentLevel++;
editor.ShaderProperty(Properties.alphaClip, Styles.alphaClipText);
EditorGUI.indentLevel--;
}
editor.ShaderProperty(Properties.cullMode, Styles.cullingModeText);
editor.ShaderProperty(Properties.shadingMode, Styles.shadingModeText);
editor.ShaderProperty(Properties.materialType, Styles.materialTypeText);
editor.ShaderProperty(Properties.pbrMode, Styles.pbrModeText);
editor.ShaderProperty(Properties.receiveHairShadow, Styles.receiveHairShadowText);
EditorGUI.BeginChangeCheck();
editor.ShaderProperty(Properties.hairBlendingTarget, Styles.hairBlendingTargetText);
if (EditorGUI.EndChangeCheck())
{
foreach (var material in editor.GetMaterials())
{
material.SetShaderPassEnabled(UtsShaderPassName.HAIR_BLENDING_TARGET_PASS_NAME, Properties.hairBlendingTarget.floatValue == 1.0f);
}
}
var surfaceFeatures = (SurfaceFeatureFlags)Properties.surfaceFeatures.floatValue;
EditorGUI.BeginChangeCheck();
surfaceFeatures = (SurfaceFeatureFlags)EditorGUILayout.EnumFlagsField(Styles.surfaceFeaturesText, surfaceFeatures);
if (EditorGUI.EndChangeCheck())
{
Properties.surfaceFeatures.floatValue = (float)surfaceFeatures;
foreach (var material in editor.GetMaterials())
{
material.SetShaderPassEnabled(UtsShaderPassName.OUTLINE_PASS_NAME, HasFeature(SurfaceFeatureFlags.Outline));
}
}
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f62b264626a3bbd42a7b45b899084983

View File

@@ -1,6 +1,7 @@
//#define USE_SIMPLE_UI //#define USE_SIMPLE_UI
using Misaki.HdrpToon;
using System; using System;
using UnityEngine; using UnityEngine;
using UnityEngine.Rendering; using UnityEngine.Rendering;
@@ -51,24 +52,6 @@ namespace UnityEditor.Rendering.Toon
} }
} }
internal static string OutlineLightingModeName
{
get
{
const string legacyDefaultLightModeName = "Always";
const string OutlineLightingModeName = "Outline";
if (currentRenderPipeline == RenderPipeline.Legacy)
{
return legacyDefaultLightModeName; // default.
}
return OutlineLightingModeName;
}
}
internal void RenderingPerChennelsSetting(Material material) internal void RenderingPerChennelsSetting(Material material)
{ {
if (currentRenderPipeline == RenderPipeline.HDRP) if (currentRenderPipeline == RenderPipeline.HDRP)
@@ -116,11 +99,17 @@ namespace UnityEditor.Rendering.Toon
internal const string ShaderProp_Set_RimLightMask = "_Set_RimLightMask"; internal const string ShaderProp_Set_RimLightMask = "_Set_RimLightMask";
internal const string ShaderProp_HighColor_Tex = "_HighColor_Tex"; internal const string ShaderProp_HighColor_Tex = "_HighColor_Tex";
internal const string ShaderProp_Set_HighColorMask = "_Set_HighColorMask"; internal const string ShaderProp_Set_HighColorMask = "_Set_HighColorMask";
internal const string ShaderProp_MatCap_Sampler = "_MatCap_Sampler"; internal const string ShaderProp_MatCapMap = "_MatCapMap";
internal const string ShaderProp_Set_MatcapMask = "_Set_MatcapMask"; internal const string ShaderProp_Set_MatcapMask = "_Set_MatcapMask";
internal const string ShaderProp_OutlineTex = "_OutlineTex"; internal const string ShaderProp_OutlineTex = "_OutlineTex";
internal const string ShaderProp_Outline_Sampler = "_Outline_Sampler"; internal const string ShaderProp_Outline_Sampler = "_Outline_Sampler";
internal const string ShaderPropCastHairShadow = "_Is_CastHairShadow";
internal const string ShaderPropReceiveHairShadow = "_Receive_Hair_Shadow";
internal const string ShaderPropEyeParallax = "_Is_EyeParallax";
internal const string ShaderPropHairBlendingTarget = "_HairBlendingTarget";
internal const string ShaderPropSimpleUI = "_simpleUI"; internal const string ShaderPropSimpleUI = "_simpleUI";
internal const string ShaderPropAutoRenderQueue = "_AutoRenderQueue"; internal const string ShaderPropAutoRenderQueue = "_AutoRenderQueue";
internal const string ShaderPropStencilMode = "_StencilMode"; internal const string ShaderPropStencilMode = "_StencilMode";
@@ -139,7 +128,10 @@ namespace UnityEditor.Rendering.Toon
internal const string ShaderPropUtsVersionZ = "_utsVersionZ"; internal const string ShaderPropUtsVersionZ = "_utsVersionZ";
internal const string ShaderPropIsUnityToonShader = "_isUnityToonshader"; internal const string ShaderPropIsUnityToonShader = "_isUnityToonshader";
internal const string ShaderPropShadowMode = "_Shadow_Mode"; internal const string ShaderPropShadowMode = "_Shadow_Mode";
internal const string ShaderPropMaterialType = "_Material_Type";
internal const string ShaderPropPBR = "_PBR_Mode"; internal const string ShaderPropPBR = "_PBR_Mode";
internal const string ShaderPropIDMode = "_Indirect_Diffuse_Mode";
internal const string ShaderPropISMode = "_Indirect_Specular_Mode";
internal const string ShaderPropOutline = "_OUTLINE"; internal const string ShaderPropOutline = "_OUTLINE";
internal const string ShaderPropNormalMapToHighColor = "_Is_NormalMapToHighColor"; internal const string ShaderPropNormalMapToHighColor = "_Is_NormalMapToHighColor";
internal const string ShaderPropIsNormalMapToRimLight = "_Is_NormalMapToRimLight"; internal const string ShaderPropIsNormalMapToRimLight = "_Is_NormalMapToRimLight";
@@ -166,7 +158,6 @@ namespace UnityEditor.Rendering.Toon
internal const string ShaderPropInvert_MatcapMask = "_Inverse_MatcapMask"; internal const string ShaderPropInvert_MatcapMask = "_Inverse_MatcapMask";
internal const string ShaderPropUse_BaseAs1st = "_Use_BaseAs1st"; internal const string ShaderPropUse_BaseAs1st = "_Use_BaseAs1st";
internal const string ShaderPropUse_1stAs2nd = "_Use_1stAs2nd"; internal const string ShaderPropUse_1stAs2nd = "_Use_1stAs2nd";
internal const string ShaderPropIs_NormalMapToBase = "_Is_NormalMapToBase";
internal const string ShaderPropIs_ColorShift = "_Is_ColorShift"; internal const string ShaderPropIs_ColorShift = "_Is_ColorShift";
internal const string ShaderPropRimLight = "_RimLight"; internal const string ShaderPropRimLight = "_RimLight";
internal const string ShaderPropRimLight_FeatherOff = "_RimLight_FeatherOff"; internal const string ShaderPropRimLight_FeatherOff = "_RimLight_FeatherOff";
@@ -216,11 +207,6 @@ namespace UnityEditor.Rendering.Toon
internal const string ShaderDefineIS_CLIPPING_MATTE = "_IS_CLIPPING_MATTE"; internal const string ShaderDefineIS_CLIPPING_MATTE = "_IS_CLIPPING_MATTE";
internal const string ShaderPropReceiveHairShadow = "_Is_ReceiveHairShadow";
internal const string ShaderPropEyeParallax = "_Is_EyeParallax";
internal const string ShaderPropEyebrowSeethrough = "_Is_EyebrowSeethrough";
protected readonly string[] UtsModeNames = { "Standard", "PBR" }; protected readonly string[] UtsModeNames = { "Standard", "PBR" };
protected readonly string[] EmissiveScrollMode = { "UV Coordinate Scroll", "View Coordinate Scroll" }; protected readonly string[] EmissiveScrollMode = { "UV Coordinate Scroll", "View Coordinate Scroll" };
@@ -228,6 +214,11 @@ namespace UnityEditor.Rendering.Toon
protected readonly string[] StencilModeNames = { "Off", "Draw If Not Equal to", "Replace Stencil Buffer with" }; protected readonly string[] StencilModeNames = { "Off", "Draw If Not Equal to", "Replace Stencil Buffer with" };
protected readonly string[] ZTestModeNames = { "Disabled", "Never", "Less", "Equal", "LessEqual", "Greater", "NotEqual", "GreaterEqual", "Always" }; protected readonly string[] ZTestModeNames = { "Disabled", "Never", "Less", "Equal", "LessEqual", "Greater", "NotEqual", "GreaterEqual", "Always" };
protected readonly string[] materialTypeDefines = { "_MATERIAL_TYPE_STANDARD", "_MATERIAL_TYPE_FRONTHAIR", "_MATERIAL_TYPE_FACE", "_MATERIAL_TYPE_EYE" };
protected readonly string[] PbrModeDefines = { "_PBR_MODE_OFF", "_PBR_MODE_STANDARD", "_PBR_MODE_ANISOTROPY", "_PBR_MODE_HAIR", "_PBR_MODE_TOON" };
protected readonly string[] IndirectDiffuseModeDefines = { "_INDIRECT_DIFFUSE_OFF", "_INDIRECT_DIFFUSE_IBL", "_INDIRECT_DIFFUSE_MATCAP", "_INDIRECT_DIFFUSE_RAMP" };
protected readonly string[] IndirectSpecularModeDefines = { "_INDIRECT_SPECULAR_OFF", "_INDIRECT_SPECULAR_IBL", "_INDIRECT_SPECULAR_MATCAP" };
public enum UTS_ClippingMode public enum UTS_ClippingMode
{ {
Off, On, TransClippingMode Off, On, TransClippingMode
@@ -294,11 +285,30 @@ namespace UnityEditor.Rendering.Toon
Normal, SDF Normal, SDF
} }
public enum MaterialType
{
Standard,
FrontHair,
Face,
Eye
}
public enum PBRMode public enum PBRMode
{ {
Off, Standard, Anisotropy, KKHair, Toon Off, Standard, Anisotropy, KKHair, Toon
} }
public enum IndirectDiffuseMode
{
Off, IBL, Matcap, Ramp
}
public enum IndirectSpecularMode
{
Off, IBL, Matcap
}
public enum OutlineMode public enum OutlineMode
{ {
NormalDirection, PositionScaling NormalDirection, PositionScaling
@@ -324,23 +334,25 @@ namespace UnityEditor.Rendering.Toon
#if UNITY_2021_1_OR_NEWER #if UNITY_2021_1_OR_NEWER
[UTS3InspectorHelpURL("instruction")] [UTS3InspectorHelpURL("instruction")]
#endif // UNITY_2021_1_OR_NEWER #endif // UNITY_2021_1_OR_NEWER
protected enum Expandable protected enum Expandable : uint
{ {
Shader = 1 << 0, Shader = 1 << 0,
Basic = 1 << 1, Basic = 1 << 1,
ShadingStepAndFeather = 1 << 2, ShadingStepAndFeather = 1 << 2,
NormalMap = 1 << 3, MaterialFeature = 1 << 3,
Highlight = 1 << 4, PBR = 1 << 4,
Rimlight = 1 << 5, AmbientMode = 1 << 5,
MatCap = 1 << 6, Highlight = 1 << 6,
AngelRing = 1 << 7, Rimlight = 1 << 7,
Emission = 1 << 8, MatCap = 1 << 8,
Outline = 1 << 9, AngelRing = 1 << 9,
TessellationLegacy = 1 << 10, Emission = 1 << 10,
TessellationHDRP = 1 << 11, Outline = 1 << 11,
SceneLight = 1 << 12, TessellationLegacy = 1 << 12,
EnvironmentalLightEffectiveness = 1 << 13, TessellationHDRP = 1 << 13,
MetaverseSettings = 1 << 14, SceneLight = 1 << 14,
EnvironmentalLightEffectiveness = 1 << 15,
MetaverseSettings = 1 << 16,
} }
// variables which must be gotten from shader at the beggning of GUI // variables which must be gotten from shader at the beggning of GUI
@@ -348,7 +360,10 @@ namespace UnityEditor.Rendering.Toon
internal int m_renderQueue = (int)UnityEngine.Rendering.RenderQueue.Geometry; internal int m_renderQueue = (int)UnityEngine.Rendering.RenderQueue.Geometry;
// variables which just to be held. // variables which just to be held.
internal ShadowMode m_shadowMode; internal ShadowMode m_shadowMode;
internal MaterialType m_materialType;
internal PBRMode m_pbrMode; internal PBRMode m_pbrMode;
internal IndirectDiffuseMode m_IndirectDiffuseMode;
internal IndirectSpecularMode m_IndirectSpecularMode;
internal OutlineMode m_outlineMode; internal OutlineMode m_outlineMode;
internal CullingMode m_cullingMode; internal CullingMode m_cullingMode;
internal EmissionMode m_emissionMode; internal EmissionMode m_emissionMode;
@@ -412,7 +427,7 @@ namespace UnityEditor.Rendering.Toon
protected MaterialProperty set_2nd_ShadePosition = null; protected MaterialProperty set_2nd_ShadePosition = null;
protected MaterialProperty shadingGradeMap = null; protected MaterialProperty shadingGradeMap = null;
protected MaterialProperty hairBlendingMap = null;
protected MaterialProperty highColor_Tex = null; protected MaterialProperty highColor_Tex = null;
protected MaterialProperty highColor = null; protected MaterialProperty highColor = null;
@@ -424,7 +439,7 @@ namespace UnityEditor.Rendering.Toon
protected MaterialProperty ap_RimLight_Power = null; protected MaterialProperty ap_RimLight_Power = null;
protected MaterialProperty set_RimLightMask = null; protected MaterialProperty set_RimLightMask = null;
protected MaterialProperty matCap_Sampler = null; protected MaterialProperty matCapMap = null;
protected MaterialProperty matCapColor = null; protected MaterialProperty matCapColor = null;
protected MaterialProperty normalMapForMatCap = null; protected MaterialProperty normalMapForMatCap = null;
protected MaterialProperty bumpScaleMatcap = null; protected MaterialProperty bumpScaleMatcap = null;
@@ -506,6 +521,7 @@ namespace UnityEditor.Rendering.Toon
set_2nd_ShadePosition = FindProperty(ShaderProp_Set_2nd_ShadePosition, props, false); set_2nd_ShadePosition = FindProperty(ShaderProp_Set_2nd_ShadePosition, props, false);
shadingGradeMap = FindProperty(ShaderProp_ShadingGradeMap, props, false); shadingGradeMap = FindProperty(ShaderProp_ShadingGradeMap, props, false);
hairBlendingMap = FindProperty("_HairBlendingMap", props);
highColor_Tex = FindProperty(ShaderProp_HighColor_Tex, props); highColor_Tex = FindProperty(ShaderProp_HighColor_Tex, props);
highColor = FindProperty("_HighColor", props); highColor = FindProperty("_HighColor", props);
@@ -516,7 +532,7 @@ namespace UnityEditor.Rendering.Toon
set_RimLightMask = FindProperty(ShaderProp_Set_RimLightMask, props); set_RimLightMask = FindProperty(ShaderProp_Set_RimLightMask, props);
matCap_Sampler = FindProperty(ShaderProp_MatCap_Sampler, props); matCapMap = FindProperty(ShaderProp_MatCapMap, props);
matCapColor = FindProperty("_MatCapColor", props); matCapColor = FindProperty("_MatCapColor", props);
normalMapForMatCap = FindProperty("_NormalMapForMatCap", props); normalMapForMatCap = FindProperty("_NormalMapForMatCap", props);
@@ -528,8 +544,8 @@ namespace UnityEditor.Rendering.Toon
angelRing_Sampler = FindProperty("_AngelRing_Sampler", props, false); angelRing_Sampler = FindProperty("_AngelRing_Sampler", props, false);
angelRing_Color = FindProperty("_AngelRing_Color", props, false); angelRing_Color = FindProperty("_AngelRing_Color", props, false);
emissive_Tex = FindProperty("_Emissive_Tex", props); emissive_Tex = FindProperty("_EmissiveColorMap", props);
emissive_Color = FindProperty("_Emissive_Color", props); emissive_Color = FindProperty("_EmissiveColor", props);
outline_Sampler = FindProperty(ShaderProp_Outline_Sampler, props, false); outline_Sampler = FindProperty(ShaderProp_Outline_Sampler, props, false);
@@ -630,7 +646,9 @@ namespace UnityEditor.Rendering.Toon
public static readonly GUIContent shaderFoldout = EditorGUIUtility.TrTextContent("Shader Settings", "Shader Settings provides basic settings that are not specific to cel-shading but are needed for general CG."); public static readonly GUIContent shaderFoldout = EditorGUIUtility.TrTextContent("Shader Settings", "Shader Settings provides basic settings that are not specific to cel-shading but are needed for general CG.");
public static readonly GUIContent basicColorFoldout = EditorGUIUtility.TrTextContent("Shading Color Settings", "Three Color Map and Control Map Settings provide very basic settings for cel-shading in Unity Toon Shader."); public static readonly GUIContent basicColorFoldout = EditorGUIUtility.TrTextContent("Shading Color Settings", "Three Color Map and Control Map Settings provide very basic settings for cel-shading in Unity Toon Shader.");
public static readonly GUIContent shadingStepAndFeatherFoldout = EditorGUIUtility.TrTextContent("Shading Step and Feather Settings", "Basic 3 color step and feather settings."); public static readonly GUIContent shadingStepAndFeatherFoldout = EditorGUIUtility.TrTextContent("Shading Step and Feather Settings", "Basic 3 color step and feather settings.");
public static readonly GUIContent normalMapFoldout = EditorGUIUtility.TrTextContent("PBR Settings", "PBR settings. The settings for PBR effect, such as specular and IBL."); public static readonly GUIContent materialFeatureFoldout = EditorGUIUtility.TrTextContent("Material Feature", "Material Feature Setting. The settings for special material feature like hair shadow, hair blending, etc");
public static readonly GUIContent pbrFoldout = EditorGUIUtility.TrTextContent("PBR Settings", "PBR settings. The settings for PBR effect, such as specular and IBL.");
public static readonly GUIContent ambientModeFoldout = EditorGUIUtility.TrTextContent("Ambient Settings", "Ambient settings. The settings for ambient lighting like IBL, Matcap, etc.");
public static readonly GUIContent highlightFoldout = EditorGUIUtility.TrTextContent("Highlight Settings", "Highlight settings. Such as power, show or hide, light shape and so on."); public static readonly GUIContent highlightFoldout = EditorGUIUtility.TrTextContent("Highlight Settings", "Highlight settings. Such as power, show or hide, light shape and so on.");
public static readonly GUIContent rimLightFoldout = EditorGUIUtility.TrTextContent("Rim Light Settings", "Rim Light Settings. Such as color, direction, inverted rim light and so on."); public static readonly GUIContent rimLightFoldout = EditorGUIUtility.TrTextContent("Rim Light Settings", "Rim Light Settings. Such as color, direction, inverted rim light and so on.");
public static readonly GUIContent matCapFoldout = EditorGUIUtility.TrTextContent("Material Capture (MatCap) Settings", "MatCap settings. Sphere maps for metallic or unusual expressions."); public static readonly GUIContent matCapFoldout = EditorGUIUtility.TrTextContent("Material Capture (MatCap) Settings", "MatCap settings. Sphere maps for metallic or unusual expressions.");
@@ -650,10 +668,14 @@ namespace UnityEditor.Rendering.Toon
public static readonly GUIContent SDFShadowText = new GUIContent("SDF Shadow Map", "Specify SDF shadow map"); public static readonly GUIContent SDFShadowText = new GUIContent("SDF Shadow Map", "Specify SDF shadow map");
public static readonly GUIContent firstShadeColorText = new GUIContent("1st Shading Map", "The map used for the brighter portions of the shadow."); public static readonly GUIContent firstShadeColorText = new GUIContent("1st Shading Map", "The map used for the brighter portions of the shadow.");
public static readonly GUIContent secondShadeColorText = new GUIContent("2nd Shading Map", "The map used for the darker portions of the shadow."); public static readonly GUIContent secondShadeColorText = new GUIContent("2nd Shading Map", "The map used for the darker portions of the shadow.");
public static readonly GUIContent materialTypeText = new GUIContent("Material Type", "Specifies the material type.");
public static readonly GUIContent hairBlendingTargetMapText = new GUIContent("Blending Map", "Specifies the texture to blend with hair.");
public static readonly GUIContent normalMapText = new GUIContent("Normal Map", "A texture that dictates the bumpiness of the material."); public static readonly GUIContent normalMapText = new GUIContent("Normal Map", "A texture that dictates the bumpiness of the material.");
public static readonly GUIContent pbrModeText = new GUIContent("PBR Mode", "Specifies PBR model mode."); public static readonly GUIContent pbrModeText = new GUIContent("PBR Mode", "Specifies PBR model mode.");
public static readonly GUIContent indirectDiffuseModeText = new GUIContent("Indirect Diffuse Mode", "Specifies indirect diffuse mode.");
public static readonly GUIContent indirectSpecularText = new GUIContent("Indirect Specular Mode", "Specifies indirect specular mode.");
public static readonly GUIContent highColorText = new GUIContent("Highlight", "Highlight : Texture(sRGB) x Color(RGB) Default:White"); public static readonly GUIContent highColorText = new GUIContent("Highlight", "Highlight : Texture(sRGB) x Color(RGB) Default:White");
public static readonly GUIContent highColorMaskText = new GUIContent("Highlight Mask", "A grayscale texture which utilises its brightness to control intensity."); public static readonly GUIContent highColorMaskText = new GUIContent("Highlight Mask", "A grayscale texture which utilizes its brightness to control intensity.");
public static readonly GUIContent rimLightMaskText = new GUIContent("Rim Light Mask", "Rim Light Mask : Texture(linear). The white part of the texture is displayed as Rim Light, and the black part is masked and not displayed."); public static readonly GUIContent rimLightMaskText = new GUIContent("Rim Light Mask", "Rim Light Mask : Texture(linear). The white part of the texture is displayed as Rim Light, and the black part is masked and not displayed.");
public static readonly GUIContent matCapSamplerText = new GUIContent("MatCap Map", "MatCap Color : Texture(sRGB) x Color(RGB) Default:White"); public static readonly GUIContent matCapSamplerText = new GUIContent("MatCap Map", "MatCap Color : Texture(sRGB) x Color(RGB) Default:White");
public static readonly GUIContent matCapMaskText = new GUIContent("MatCap Mask", "The MatCap mask is positioned with respect to the UV coordinates of the mesh onto which the MatCap is projected, and the pixels on black areas are hidden."); public static readonly GUIContent matCapMaskText = new GUIContent("MatCap Mask", "The MatCap mask is positioned with respect to the UV coordinates of the mesh onto which the MatCap is projected, and the pixels on black areas are hidden.");
@@ -665,7 +687,7 @@ namespace UnityEditor.Rendering.Toon
public static readonly GUIContent outlineSamplerText = new GUIContent("Outline Width Map", "Outline Width Map as Grayscale Texture : Texture(linear). In the case of white, the Outline Width is displayed as it is. In black, the width is 0."); public static readonly GUIContent outlineSamplerText = new GUIContent("Outline Width Map", "Outline Width Map as Grayscale Texture : Texture(linear). In the case of white, the Outline Width is displayed as it is. In black, the width is 0.");
public static readonly GUIContent outlineTexText = new GUIContent("Outline Color Map", "Outline texture : Texture(sRGB) Default:White"); public static readonly GUIContent outlineTexText = new GUIContent("Outline Color Map", "Outline texture : Texture(sRGB) Default:White");
public static readonly GUIContent bakedNormalOutlineText = new GUIContent("Baked Normal Map for Outline", "Unpacked Normal Map : Texture(linear) .Note that this is not a standard NORMAL MAP."); public static readonly GUIContent bakedNormalOutlineText = new GUIContent("Baked Normal Map for Outline", "Unpacked Normal Map : Texture(linear) .Note that this is not a standard NORMAL MAP.");
public static readonly GUIContent clippingMaskText = new GUIContent("Clipping Mask", "A grayscale texture which utilises its brightness to control transparency."); public static readonly GUIContent clippingMaskText = new GUIContent("Clipping Mask", "A grayscale texture which utilizes its brightness to control transparency.");
public static readonly GUIContent specularModeText = new GUIContent("Specular Mode", "Specular light mode. Hard or Soft."); public static readonly GUIContent specularModeText = new GUIContent("Specular Mode", "Specular light mode. Hard or Soft.");
public static readonly GUIContent specularBlendModeText = new GUIContent("Color Blending Mode", "Specular color blending mode. Multiply or Add."); public static readonly GUIContent specularBlendModeText = new GUIContent("Color Blending Mode", "Specular color blending mode. Multiply or Add.");
@@ -675,7 +697,6 @@ namespace UnityEditor.Rendering.Toon
public static readonly GUIContent transparentModeText = new GUIContent("Transparency", "Enable different modes that allow the simulation of a variety of transparent objects. "); public static readonly GUIContent transparentModeText = new GUIContent("Transparency", "Enable different modes that allow the simulation of a variety of transparent objects. ");
public static readonly GUIContent stencilVauleText = new GUIContent("Stencil Value", "Stencil value that is submitted to the stencil buffer for controlling the per-pixel drawing."); public static readonly GUIContent stencilVauleText = new GUIContent("Stencil Value", "Stencil value that is submitted to the stencil buffer for controlling the per-pixel drawing.");
public static readonly GUIContent workflowModeText = new GUIContent("Mode", "The UTS mode that controls what settings are exposed in the shader."); public static readonly GUIContent workflowModeText = new GUIContent("Mode", "The UTS mode that controls what settings are exposed in the shader.");
public static readonly GUIContent materialTypeText = new GUIContent("Material Type", "The PBR model type of the material");
// ----------------------------------------------------- // -----------------------------------------------------
public static readonly GUIContent clippingmodeModeText = new GUIContent("Trans Clipping", "Select trans clipping mode that fits your purpose. "); public static readonly GUIContent clippingmodeModeText = new GUIContent("Trans Clipping", "Select trans clipping mode that fits your purpose. ");
@@ -699,7 +720,9 @@ namespace UnityEditor.Rendering.Toon
public static readonly GUIContent highlightOnShadowText = new GUIContent("Highlight Blending on Shadows", "Control the blending for the highlights in shadows, this also control the rim light."); public static readonly GUIContent highlightOnShadowText = new GUIContent("Highlight Blending on Shadows", "Control the blending for the highlights in shadows, this also control the rim light.");
public static readonly GUIContent lightColorEffectiveness = EditorGUIUtility.TrTextContent("Light Color Effectiveness", "light color effectiveness to each parameter."); public static readonly GUIContent lightColorEffectiveness = EditorGUIUtility.TrTextContent("Light Color Effectiveness", "light color effectiveness to each parameter.");
public static readonly GUIContent receiveHairShadowText = new GUIContent("Receive Hair Shadow", "Do you want this material to receive hair shadow"); public static readonly GUIContent hairShadowCasterText = new GUIContent("Hair Shadow Caster", "Enable to cast hair shadow");
public static readonly GUIContent receiveHairShadowText = new GUIContent("Receive Hair Shadow", "Enable to receive shadow from hair shadow caster");
public static readonly GUIContent hairBlendingTargetShadowText = new GUIContent("Hair Blending Target", "Enable to be blended with hair");
public static readonly GUIContent eyeParallaxText = new GUIContent("Eye Parallax Correction", "Enables parallax correction for eye material"); public static readonly GUIContent eyeParallaxText = new GUIContent("Eye Parallax Correction", "Enables parallax correction for eye material");
public static readonly GUIContent eyebrowSeethroughText = new GUIContent("Eyebrow Seethrough", "Enable for eyebrow material to be blended with hair. Must configure HairShadowPass to work."); public static readonly GUIContent eyebrowSeethroughText = new GUIContent("Eyebrow Seethrough", "Enable for eyebrow material to be blended with hair. Must configure HairShadowPass to work.");
@@ -836,9 +859,9 @@ namespace UnityEditor.Rendering.Toon
label: "Eye Parallax Amount", tooltip: "Distance of parallax correction", label: "Eye Parallax Amount", tooltip: "Distance of parallax correction",
propName: "_EyeParallaxAmount", defaultValue: 0.1f, min: 0.0f, max: 0.4f); propName: "_EyeParallaxAmount", defaultValue: 0.1f, min: 0.0f, max: 0.4f);
public static readonly RangeProperty eyeBrowBlendingFactor = new RangeProperty( public static readonly RangeProperty hairBlendingFactor = new RangeProperty(
label: "Eyebrow Blending Factor", tooltip: "Blend Factor of Eyebrows on Hair", label: "Hair Blending Factor", tooltip: "Blend Factor of Hair Blending Target on Hair",
propName: "_EyeBrowBlendingFactor", defaultValue: 0.5f, min: 0.0f, max: 1.0f); propName: "_HairBlendingFactor", defaultValue: 0.5f, min: 0.0f, max: 1.0f);
public static readonly RangeProperty shaderPropStepOffsetText = new RangeProperty( public static readonly RangeProperty shaderPropStepOffsetText = new RangeProperty(
label: "Step Offset", tooltip: "Fine tunes light steps (boundaries) added in the ForwardAdd pass, such as real-time point lights.", label: "Step Offset", tooltip: "Fine tunes light steps (boundaries) added in the ForwardAdd pass, such as real-time point lights.",
@@ -944,12 +967,12 @@ namespace UnityEditor.Rendering.Toon
propName: "_RimLight_InsideMask", defaultValue: 0.0001f, min: 0.0001f, max: 1); propName: "_RimLight_InsideMask", defaultValue: 0.0001f, min: 0.0001f, max: 1);
public static readonly RangeProperty SSAOFactorText = new RangeProperty( public static readonly RangeProperty SSAOFactorText = new RangeProperty(
label: "SSAO Minimum", "The minimum value of SSAO.", label: "SSAO Factor", "The weight of SSAO.",
propName: "_AOMin", defaultValue: 0.0f, min: 0, max: 1); propName: "_AO_Factor", defaultValue: 0.0f, min: 0, max: 1);
public static readonly RangeProperty SSGIFactorText = new RangeProperty( public static readonly RangeProperty SSGIFactorText = new RangeProperty(
label: "SSGI Factor", "The multiplier of SSGI.", label: "SSGI Factor", "The weight of SSGI.",
propName: "_GIMultiplier", defaultValue: 1.0f, min: 1, max: 10); propName: "_GI_Factor", defaultValue: 1.0f, min: 1, max: 10);
public static readonly RangeProperty BSDFContribution = new RangeProperty( public static readonly RangeProperty BSDFContribution = new RangeProperty(
label: "BSDF Contribution", "BSDF smoothness contribution, 1 means KK Hair smoothness will fully contribute bsdf calculation", label: "BSDF Contribution", "BSDF smoothness contribution, 1 means KK Hair smoothness will fully contribute bsdf calculation",
@@ -1012,23 +1035,14 @@ namespace UnityEditor.Rendering.Toon
} }
// -------------------------------- // --------------------------------
public UTS3GUI()
{
}
public override void OnClosed(Material material)
{
base.OnClosed(material);
}
void OnOpenGUI(Material material, MaterialEditor materialEditor, MaterialProperty[] props) void OnOpenGUI(Material material, MaterialEditor materialEditor, MaterialProperty[] props)
{ {
m_MaterialScopeList.RegisterHeaderScope(Styles.shaderFoldout, Expandable.Shader, DrawShaderOptions, (uint)UTS_TransparentMode.Off, isTessellation: 0); m_MaterialScopeList.RegisterHeaderScope(Styles.shaderFoldout, Expandable.Shader, DrawShaderOptions, (uint)UTS_TransparentMode.Off, isTessellation: 0);
m_MaterialScopeList.RegisterHeaderScope(Styles.basicColorFoldout, Expandable.Basic, GUI_BasicThreeColors, (uint)UTS_TransparentMode.Off, isTessellation: 0); m_MaterialScopeList.RegisterHeaderScope(Styles.basicColorFoldout, Expandable.Basic, GUI_BasicThreeColors, (uint)UTS_TransparentMode.Off, isTessellation: 0);
m_MaterialScopeList.RegisterHeaderScope(Styles.shadingStepAndFeatherFoldout, Expandable.ShadingStepAndFeather, GUI_StepAndFeather, (uint)UTS_TransparentMode.Off, isTessellation: 0); m_MaterialScopeList.RegisterHeaderScope(Styles.shadingStepAndFeatherFoldout, Expandable.ShadingStepAndFeather, GUI_StepAndFeather, (uint)UTS_TransparentMode.Off, isTessellation: 0);
m_MaterialScopeList.RegisterHeaderScope(Styles.normalMapFoldout, Expandable.NormalMap, GUI_PBRSettings, (uint)UTS_TransparentMode.Off, isTessellation: 0); m_MaterialScopeList.RegisterHeaderScope(Styles.materialFeatureFoldout, Expandable.MaterialFeature, GUI_MaterialFeature, (uint)UTS_TransparentMode.Off, isTessellation: 0);
m_MaterialScopeList.RegisterHeaderScope(Styles.pbrFoldout, Expandable.PBR, GUI_PBRSettings, (uint)UTS_TransparentMode.Off, isTessellation: 0);
m_MaterialScopeList.RegisterHeaderScope(Styles.ambientModeFoldout, Expandable.AmbientMode, GUI_AmbientMode, (uint)UTS_TransparentMode.Off, isTessellation: 0);
m_MaterialScopeList.RegisterHeaderScope(Styles.highlightFoldout, Expandable.Highlight, GUI_HighlightSettings, (uint)UTS_TransparentMode.Off, isTessellation: 0); m_MaterialScopeList.RegisterHeaderScope(Styles.highlightFoldout, Expandable.Highlight, GUI_HighlightSettings, (uint)UTS_TransparentMode.Off, isTessellation: 0);
m_MaterialScopeList.RegisterHeaderScope(Styles.rimLightFoldout, Expandable.Rimlight, GUI_RimLight, (uint)UTS_TransparentMode.Off, isTessellation: 0); m_MaterialScopeList.RegisterHeaderScope(Styles.rimLightFoldout, Expandable.Rimlight, GUI_RimLight, (uint)UTS_TransparentMode.Off, isTessellation: 0);
m_MaterialScopeList.RegisterHeaderScope(Styles.matCapFoldout, Expandable.MatCap, GUI_MatCap, (uint)UTS_TransparentMode.Off, isTessellation: 0); m_MaterialScopeList.RegisterHeaderScope(Styles.matCapFoldout, Expandable.MatCap, GUI_MatCap, (uint)UTS_TransparentMode.Off, isTessellation: 0);
@@ -1199,7 +1213,7 @@ namespace UnityEditor.Rendering.Toon
EditorGUILayout.Space(10); EditorGUILayout.Space(10);
var headerStyle = new GUIStyle() { fontSize = 25, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter }; var headerStyle = new GUIStyle() { fontSize = 25, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter };
headerStyle.normal.textColor = GUI.skin.label.normal.textColor; headerStyle.normal.textColor = GUI.skin.label.normal.textColor;
EditorGUILayout.LabelField("Unity Toon Shader", headerStyle); EditorGUILayout.LabelField("HDRP Toon Shader", headerStyle);
EditorGUILayout.Space(20); EditorGUILayout.Space(20);
if (transparencyEnabled != UTS_TransparentMode.On) if (transparencyEnabled != UTS_TransparentMode.On)
@@ -1383,22 +1397,8 @@ namespace UnityEditor.Rendering.Toon
//If the value changes, write to the material. //If the value changes, write to the material.
if (_CullMode_Setting != (int)m_cullingMode) if (_CullMode_Setting != (int)m_cullingMode)
{ {
switch (m_cullingMode) MaterialSetInt(material, _CullMode, (int)m_cullingMode);
{
case CullingMode.Off:
MaterialSetInt(material, _CullMode, 0);
break;
case CullingMode.Frontface:
MaterialSetInt(material, _CullMode, 1);
break;
default:
MaterialSetInt(material, _CullMode, 2);
break;
}
} }
} }
void GUI_Tranparent(Material material) void GUI_Tranparent(Material material)
{ {
@@ -1533,13 +1533,6 @@ namespace UnityEditor.Rendering.Toon
{ {
GUI_AdditionalLookdevs(material); GUI_AdditionalLookdevs(material);
} }
EditorGUILayout.Separator();
GUI_HairShadow(material);
GUI_EyeParallax(material);
GUI_EyebrowSeethrough(material);
} }
void GUI_SystemShadows(Material material) void GUI_SystemShadows(Material material)
@@ -1557,74 +1550,6 @@ namespace UnityEditor.Rendering.Toon
EditorGUI.EndDisabledGroup(); EditorGUI.EndDisabledGroup();
} }
void GUI_HairShadow(Material material)
{
var isEnabled = GUI_Toggle(material, Styles.receiveHairShadowText, ShaderPropReceiveHairShadow,
MaterialGetInt(material, ShaderPropReceiveHairShadow) != 0);
if (isEnabled)
{
material.EnableKeyword(new LocalKeyword(material.shader, "_RECEIVE_HAIR_SHADOW"));
}
else
{
material.DisableKeyword(new LocalKeyword(material.shader, "_RECEIVE_HAIR_SHADOW"));
}
}
void GUI_EyeParallax(Material material)
{
var isEnabled = GUI_Toggle(material, Styles.eyeParallaxText, ShaderPropEyeParallax,
MaterialGetInt(material, ShaderPropEyeParallax) != 0);
EditorGUI.BeginDisabledGroup(!isEnabled);
{
EditorGUI.indentLevel++;
GUI_RangeProperty(material, Styles.eyeParallaxAmount);
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
EditorGUI.EndDisabledGroup();
if (isEnabled)
{
material.EnableKeyword(new LocalKeyword(material.shader, "_EYE_PARALLAX"));
}
else
{
material.DisableKeyword(new LocalKeyword(material.shader, "_EYE_PARALLAX"));
}
}
void GUI_EyebrowSeethrough(Material material)
{
var isEnabled = GUI_Toggle(material, Styles.eyebrowSeethroughText, ShaderPropEyebrowSeethrough,
MaterialGetInt(material, ShaderPropEyebrowSeethrough) != 0);
EditorGUI.BeginDisabledGroup(!isEnabled);
{
EditorGUI.indentLevel++;
GUI_RangeProperty(material, Styles.eyeBrowBlendingFactor);
EditorGUI.indentLevel--;
EditorGUILayout.Space();
}
EditorGUI.EndDisabledGroup();
if (isEnabled)
{
material.EnableKeyword(new LocalKeyword(material.shader, "_EYEBROW_SEETHROUGH"));
}
else
{
material.DisableKeyword(new LocalKeyword(material.shader, "_EYEBROW_SEETHROUGH"));
}
}
void GUI_ShadingStepAndFeatherSettings(Material material) void GUI_ShadingStepAndFeatherSettings(Material material)
{ {
var shadowMode_Setting = MaterialGetInt(material, ShaderPropShadowMode); var shadowMode_Setting = MaterialGetInt(material, ShaderPropShadowMode);
@@ -1648,7 +1573,7 @@ namespace UnityEditor.Rendering.Toon
case ShadowMode.Normal: case ShadowMode.Normal:
{ {
material.SetFloat(ShaderPropShadowMode, (int)ShadowMode.Normal); material.SetFloat(ShaderPropShadowMode, (int)ShadowMode.Normal);
material.DisableKeyword(new LocalKeyword(material.shader, "_SDFShadow")); material.DisableKeyword(new LocalKeyword(material.shader, "_SHADOW_MODE_SDF"));
GUI_RangeProperty(material, Styles.shaderProp1st_ShadeColor_StepText); GUI_RangeProperty(material, Styles.shaderProp1st_ShadeColor_StepText);
GUI_RangeProperty(material, Styles.shaderProp1st_ShadeColor_FeatherText); GUI_RangeProperty(material, Styles.shaderProp1st_ShadeColor_FeatherText);
@@ -1666,7 +1591,7 @@ namespace UnityEditor.Rendering.Toon
case ShadowMode.SDF: case ShadowMode.SDF:
{ {
material.SetFloat(ShaderPropShadowMode, (int)ShadowMode.SDF); material.SetFloat(ShaderPropShadowMode, (int)ShadowMode.SDF);
material.EnableKeyword(new LocalKeyword(material.shader, "_SDFShadow")); material.EnableKeyword(new LocalKeyword(material.shader, "_SHADOW_MODE_SDF"));
m_MaterialEditor.TexturePropertySingleLine(Styles.SDFShadowText, SDFShadowMap); m_MaterialEditor.TexturePropertySingleLine(Styles.SDFShadowText, SDFShadowMap);
GUI_RangeProperty(material, Styles.SDFShadowLevelText); GUI_RangeProperty(material, Styles.SDFShadowLevelText);
GUI_RangeProperty(material, Styles.SDFSmoothGammaText); GUI_RangeProperty(material, Styles.SDFSmoothGammaText);
@@ -1690,101 +1615,106 @@ namespace UnityEditor.Rendering.Toon
EditorGUILayout.Space(); EditorGUILayout.Space();
} }
void GUI_PBRSettings(Material material) void GUI_MaterialFeature(Material material)
{ {
var PBRMode_Setting = MaterialGetInt(material, ShaderPropPBR); var materialTypeSetting = MaterialGetInt(material, ShaderPropMaterialType);
//Convert it to Enum format and store it in the offlineMode variable. m_materialType = (MaterialType)materialTypeSetting;
switch (PBRMode_Setting) m_materialType = (MaterialType)EditorGUILayout.EnumPopup(Styles.materialTypeText, m_materialType);
EditorGUI.indentLevel++;
switch (m_materialType)
{ {
case (int)PBRMode.Off: case MaterialType.FrontHair:
m_pbrMode = PBRMode.Off; GUI_FrontHair(material);
break; break;
case (int)PBRMode.Standard: case MaterialType.Eye:
m_pbrMode = PBRMode.Standard; GUI_EyeParallax(material);
break; break;
case (int)PBRMode.Anisotropy: default:
m_pbrMode = PBRMode.Anisotropy;
break;
case (int)PBRMode.KKHair:
m_pbrMode = PBRMode.KKHair;
break;
case (int)PBRMode.Toon:
m_pbrMode = PBRMode.Toon;
break; break;
} }
EditorGUI.indentLevel--;
EditorGUILayout.Space();
//GUI description with EnumPopup. var isReceiveHairShadowEnabled = GUI_Toggle(material, Styles.receiveHairShadowText, ShaderPropReceiveHairShadow,
MaterialGetInt(material, ShaderPropReceiveHairShadow) != 0);
material.SetKeyword(new LocalKeyword(material.shader, "_RECEIVE_HAIR_SHADOW_ON"), isReceiveHairShadowEnabled);
var isHairBlendingTargetEnabled = GUI_Toggle(material, Styles.hairBlendingTargetShadowText, ShaderPropHairBlendingTarget,
MaterialGetInt(material, ShaderPropHairBlendingTarget) != 0);
if (isHairBlendingTargetEnabled)
{
EditorGUI.indentLevel++;
m_MaterialEditor.TexturePropertySingleLine(Styles.hairBlendingTargetMapText, hairBlendingMap);
EditorGUI.indentLevel--;
}
material.SetShaderPassEnabled(UtsShaderPassName.HAIR_BLENDING_TARGET_PASS_NAME, isHairBlendingTargetEnabled);
SwitchKeyword(m_materialType);
material.SetFloat(ShaderPropMaterialType, (float)m_materialType);
material.SetShaderPassEnabled(UtsShaderPassName.HAIR_SHADOW_CASTER_PASS_NAME, m_materialType == MaterialType.FrontHair);
void SwitchKeyword(MaterialType target)
{
for (var i = 0; i < materialTypeDefines.Length; i++)
{
var localKeyword = new LocalKeyword(material.shader, materialTypeDefines[i]);
if ((int)target == i)
{
material.EnableKeyword(localKeyword);
}
else
{
material.DisableKeyword(localKeyword);
}
}
}
}
void GUI_FrontHair(Material material)
{
GUI_RangeProperty(material, Styles.hairBlendingFactor);
}
void GUI_EyeParallax(Material material)
{
GUI_RangeProperty(material, Styles.eyeParallaxAmount);
}
void SwitchKeywrod(Material material, string targetKeywrod, string[] sources)
{
foreach (var keywrod in sources)
{
if (targetKeywrod == keywrod)
{
material.EnableKeyword(keywrod);
}
else
{
material.DisableKeyword(keywrod);
}
}
}
void GUI_PBRSettings(Material material)
{
m_pbrMode = (PBRMode)MaterialGetInt(material, ShaderPropPBR);
m_pbrMode = (PBRMode)EditorGUILayout.EnumPopup(Styles.pbrModeText, m_pbrMode); m_pbrMode = (PBRMode)EditorGUILayout.EnumPopup(Styles.pbrModeText, m_pbrMode);
EditorGUILayout.Space(); EditorGUILayout.Space();
switch (m_pbrMode) material.SetFloat(ShaderPropPBR, (int)m_pbrMode);
{ SwitchKeywrod(material, PbrModeDefines[(int)m_pbrMode], PbrModeDefines);
case PBRMode.Off:
{
material.SetFloat(ShaderPropPBR, (int)PBRMode.Off);
material.EnableKeyword("_PBR_Mode_OFF");
material.DisableKeyword("_PBR_Mode_ST");
material.DisableKeyword("_PBR_Mode_ANISO");
material.DisableKeyword("_PBR_Mode_KK");
material.DisableKeyword("_PBR_Mode_TOON");
}
break;
case PBRMode.Standard:
{
material.SetFloat(ShaderPropPBR, (int)PBRMode.Standard);
material.DisableKeyword("_PBR_Mode_OFF");
material.EnableKeyword("_PBR_Mode_ST");
material.DisableKeyword("_PBR_Mode_ANISO");
material.DisableKeyword("_PBR_Mode_KK");
material.DisableKeyword("_PBR_Mode_TOON");
}
break;
case PBRMode.Anisotropy:
{
material.SetFloat(ShaderPropPBR, (int)PBRMode.Anisotropy);
material.DisableKeyword("_PBR_Mode_OFF");
material.DisableKeyword("_PBR_Mode_ST");
material.EnableKeyword("_PBR_Mode_ANISO");
material.DisableKeyword("_PBR_Mode_KK");
material.DisableKeyword("_PBR_Mode_TOON");
}
break;
case PBRMode.KKHair:
{
material.SetFloat(ShaderPropPBR, (int)PBRMode.KKHair);
material.DisableKeyword("_PBR_Mode_OFF");
material.DisableKeyword("_PBR_Mode_ST");
material.DisableKeyword("_PBR_Mode_ANISO");
material.EnableKeyword("_PBR_Mode_KK");
material.DisableKeyword("_PBR_Mode_TOON");
}
break;
case PBRMode.Toon:
{
material.SetFloat(ShaderPropPBR, (int)PBRMode.Toon);
material.DisableKeyword("_PBR_Mode_OFF");
material.DisableKeyword("_PBR_Mode_ST");
material.DisableKeyword("_PBR_Mode_ANISO");
material.DisableKeyword("_PBR_Mode_KK");
material.EnableKeyword("_PBR_Mode_TOON");
}
break;
}
m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, normalMap, normalScale); m_MaterialEditor.TexturePropertySingleLine(Styles.normalMapText, normalMap, normalScale);
material.SetKeyword(new LocalKeyword(material.shader, "_NORMAL_MAP"), normalMap.textureValue != null);
if (m_pbrMode != PBRMode.Off) if (m_pbrMode != PBRMode.Off)
{ {
m_MaterialEditor.TexturePropertySingleLine(Styles.MaskMapText, Mask); m_MaterialEditor.TexturePropertySingleLine(Styles.MaskMapText, Mask);
if (Mask.textureValue == null) if (Mask.textureValue == null)
{ {
material.DisableKeyword(new LocalKeyword(material.shader, "_MASKMAP")); material.DisableKeyword(new LocalKeyword(material.shader, "_MASK_MAP"));
if (m_pbrMode != PBRMode.KKHair) if (m_pbrMode != PBRMode.KKHair)
{ {
GUI_RangeProperty(material, Styles.MetallicText); GUI_RangeProperty(material, Styles.MetallicText);
@@ -1793,7 +1723,7 @@ namespace UnityEditor.Rendering.Toon
} }
else else
{ {
material.EnableKeyword(new LocalKeyword(material.shader, "_MASKMAP")); material.EnableKeyword(new LocalKeyword(material.shader, "_MASK_MAP"));
m_MaterialEditor.MinMaxShaderProperty(MetallicRemapMin, MetallicRemapMax, minLimit: 0, 1, Styles.MetallicRemap); m_MaterialEditor.MinMaxShaderProperty(MetallicRemapMin, MetallicRemapMax, minLimit: 0, 1, Styles.MetallicRemap);
m_MaterialEditor.MinMaxShaderProperty(AORemapMin, AORemapMax, 0, 1, Styles.AORemap); m_MaterialEditor.MinMaxShaderProperty(AORemapMin, AORemapMax, 0, 1, Styles.AORemap);
m_MaterialEditor.MinMaxShaderProperty(RoughnessRemapMin, RoughnessRemapMax, 0, 1, Styles.RoughnessRemap); m_MaterialEditor.MinMaxShaderProperty(RoughnessRemapMin, RoughnessRemapMax, 0, 1, Styles.RoughnessRemap);
@@ -1801,9 +1731,9 @@ namespace UnityEditor.Rendering.Toon
} }
else else
{ {
material.DisableKeyword(new LocalKeyword(material.shader, "_MASKMAP")); material.DisableKeyword(new LocalKeyword(material.shader, "_MASK_MAP"));
material.DisableKeyword(new LocalKeyword(material.shader, "_ANISOTROPYMAP")); material.DisableKeyword(new LocalKeyword(material.shader, "_ANISOTROPY_MAP"));
material.DisableKeyword(new LocalKeyword(material.shader, "_SPECULARCOLORMAP")); material.DisableKeyword(new LocalKeyword(material.shader, "_SPECULAR_COLOR_MAP"));
} }
@@ -1822,11 +1752,11 @@ namespace UnityEditor.Rendering.Toon
if (AnisotropyMap.textureValue == null) if (AnisotropyMap.textureValue == null)
{ {
material.DisableKeyword(new LocalKeyword(material.shader, "_ANISOTROPYMAP")); material.DisableKeyword(new LocalKeyword(material.shader, "_ANISOTROPY_MAP"));
} }
else else
{ {
material.EnableKeyword(new LocalKeyword(material.shader, "_ANISOTROPYMAP")); material.EnableKeyword(new LocalKeyword(material.shader, "_ANISOTROPY_MAP"));
} }
} }
@@ -1835,11 +1765,11 @@ namespace UnityEditor.Rendering.Toon
m_MaterialEditor.TexturePropertySingleLine(new GUIContent("Specular Color Map"), SpecColorMap, SpecColor); m_MaterialEditor.TexturePropertySingleLine(new GUIContent("Specular Color Map"), SpecColorMap, SpecColor);
if (SpecColorMap.textureValue == null) if (SpecColorMap.textureValue == null)
{ {
material.DisableKeyword(new LocalKeyword(material.shader, "_SPECULARCOLORMAP")); material.DisableKeyword(new LocalKeyword(material.shader, "_SPECULAR_COLOR_MAP"));
} }
else else
{ {
material.EnableKeyword(new LocalKeyword(material.shader, "_SPECULARCOLORMAP")); material.EnableKeyword(new LocalKeyword(material.shader, "_SPECULAR_COLOR_MAP"));
} }
m_MaterialEditor.MinMaxShaderProperty(SpecFeather, SpecStep, 0, 1, Styles.SpecRemap); m_MaterialEditor.MinMaxShaderProperty(SpecFeather, SpecStep, 0, 1, Styles.SpecRemap);
} }
@@ -1885,6 +1815,22 @@ namespace UnityEditor.Rendering.Toon
MaterialSetInt(material, "_Use_SSSLut", 0); MaterialSetInt(material, "_Use_SSSLut", 0);
} }
} }
void GUI_AmbientMode(Material material)
{
m_IndirectDiffuseMode = (IndirectDiffuseMode)MaterialGetInt(material, ShaderPropIDMode);
m_IndirectDiffuseMode = (IndirectDiffuseMode)EditorGUILayout.EnumPopup(Styles.indirectDiffuseModeText, m_IndirectDiffuseMode);
material.SetFloat(ShaderPropIDMode, (int)m_IndirectDiffuseMode);
SwitchKeywrod(material, IndirectDiffuseModeDefines[(int)m_IndirectDiffuseMode], IndirectDiffuseModeDefines);
m_IndirectSpecularMode = (IndirectSpecularMode)MaterialGetInt(material, ShaderPropISMode);
m_IndirectSpecularMode = (IndirectSpecularMode)EditorGUILayout.EnumPopup(Styles.indirectSpecularText, m_IndirectSpecularMode);
material.SetFloat(ShaderPropISMode, (int)m_IndirectSpecularMode);
SwitchKeywrod(material, IndirectSpecularModeDefines[(int)m_IndirectSpecularMode], IndirectSpecularModeDefines);
}
void GUI_HighlightSettings(Material material) void GUI_HighlightSettings(Material material)
{ {
m_MaterialEditor.TexturePropertySingleLine(Styles.highColorText, highColor_Tex, highColor); m_MaterialEditor.TexturePropertySingleLine(Styles.highColorText, highColor_Tex, highColor);
@@ -1963,7 +1909,6 @@ namespace UnityEditor.Rendering.Toon
void GUI_RimLight(Material material) void GUI_RimLight(Material material)
{ {
EditorGUILayout.BeginHorizontal(); EditorGUILayout.BeginHorizontal();
var rimLightEnabled = GUI_Toggle(material, Styles.rimlightText, ShaderPropRimLight, MaterialGetInt(material, ShaderPropRimLight) != 0); var rimLightEnabled = GUI_Toggle(material, Styles.rimlightText, ShaderPropRimLight, MaterialGetInt(material, ShaderPropRimLight) != 0);
EditorGUILayout.EndHorizontal(); EditorGUILayout.EndHorizontal();
@@ -2043,10 +1988,6 @@ namespace UnityEditor.Rendering.Toon
EditorGUILayout.Space(); EditorGUILayout.Space();
EditorGUI.EndDisabledGroup(); EditorGUI.EndDisabledGroup();
} }
void GUI_MatCap(Material material) void GUI_MatCap(Material material)
@@ -2056,9 +1997,9 @@ namespace UnityEditor.Rendering.Toon
EditorGUILayout.EndHorizontal(); EditorGUILayout.EndHorizontal();
EditorGUI.BeginDisabledGroup(!matcapEnabled); EditorGUI.BeginDisabledGroup(!matcapEnabled);
m_MaterialEditor.TexturePropertySingleLine(Styles.matCapSamplerText, matCap_Sampler, matCapColor); m_MaterialEditor.TexturePropertySingleLine(Styles.matCapSamplerText, matCapMap, matCapColor);
EditorGUI.indentLevel++; EditorGUI.indentLevel++;
m_MaterialEditor.TextureScaleOffsetProperty(matCap_Sampler); m_MaterialEditor.TextureScaleOffsetProperty(matCapMap);
if (!_SimpleUI) if (!_SimpleUI)
{ {
@@ -2302,9 +2243,9 @@ namespace UnityEditor.Rendering.Toon
void GUI_Emissive(Material material) void GUI_Emissive(Material material)
{ {
m_MaterialEditor.TexturePropertySingleLine(Styles.emissiveTexText, emissive_Tex, emissive_Color); m_MaterialEditor.TexturePropertySingleLine(Styles.emissiveTexText, emissive_Tex, emissive_Color);
m_MaterialEditor.TextureScaleOffsetProperty(emissive_Tex); m_MaterialEditor.TextureScaleOffsetProperty(emissive_Tex);
material.SetKeyword(new LocalKeyword(material.shader, "_EMISSIVE_COLOR_MAP"), emissive_Tex.textureValue != null);
var _EmissiveMode_Setting = MaterialGetInt(material, "_EMISSIVE"); var _EmissiveMode_Setting = MaterialGetInt(material, "_EMISSIVE");
if ((int)EmissionMode.SimpleEmissive == _EmissiveMode_Setting) if ((int)EmissionMode.SimpleEmissive == _EmissiveMode_Setting)
@@ -2406,18 +2347,18 @@ namespace UnityEditor.Rendering.Toon
internal static void SetupOverDrawTransparentObject(Material material) internal static void SetupOverDrawTransparentObject(Material material)
{ {
var srpDefaultLightModeTag = material.GetTag("LightMode", false, OutlineLightingModeName); var srpDefaultLightModeTag = material.GetTag("LightMode", false, UtsShaderPassName.OUTLINE_PASS_NAME);
if (srpDefaultLightModeTag == OutlineLightingModeName) if (srpDefaultLightModeTag == UtsShaderPassName.OUTLINE_PASS_NAME)
{ {
material.SetShaderPassEnabled(OutlineLightingModeName, true); material.SetShaderPassEnabled(UtsShaderPassName.OUTLINE_PASS_NAME, true);
MaterialSetInt(material, srpDefaultColorMask, 0); MaterialSetInt(material, srpDefaultColorMask, 0);
MaterialSetInt(material, srpDefaultCullMode, (int)CullingMode.Backface); MaterialSetInt(material, srpDefaultCullMode, (int)CullingMode.Backface);
} }
} }
internal static void SetupOutline(Material material) internal static void SetupOutline(Material material)
{ {
var srpDefaultLightModeTag = material.GetTag("LightMode", false, OutlineLightingModeName); var srpDefaultLightModeTag = material.GetTag("LightMode", false, UtsShaderPassName.OUTLINE_PASS_NAME);
if (srpDefaultLightModeTag == OutlineLightingModeName) if (srpDefaultLightModeTag == UtsShaderPassName.OUTLINE_PASS_NAME)
{ {
MaterialSetInt(material, srpDefaultColorMask, 15); MaterialSetInt(material, srpDefaultColorMask, 15);
MaterialSetInt(material, srpDefaultCullMode, (int)CullingMode.Frontface); MaterialSetInt(material, srpDefaultCullMode, (int)CullingMode.Frontface);
@@ -2427,15 +2368,12 @@ namespace UnityEditor.Rendering.Toon
{ {
EditorGUILayout.HelpBox("You need to add OutlinePass in custom pass to make outline work properly", MessageType.Warning); EditorGUILayout.HelpBox("You need to add OutlinePass in custom pass to make outline work properly", MessageType.Warning);
const string kDisableOutlineKeyword = "_DISABLE_OUTLINE"; var srpDefaultLightModeTag = material.GetTag("LightMode", false, UtsShaderPassName.OUTLINE_PASS_NAME);
var isLegacy = (OutlineLightingModeName == "Always");
var srpDefaultLightModeTag = material.GetTag("LightMode", false, OutlineLightingModeName);
var isOutlineEnabled = true; var isOutlineEnabled = true;
if (srpDefaultLightModeTag == OutlineLightingModeName) if (srpDefaultLightModeTag == UtsShaderPassName.OUTLINE_PASS_NAME)
{ {
const string kOutline = "Outline"; const string kOutline = "Outline";
isOutlineEnabled = material.GetShaderPassEnabled(OutlineLightingModeName); isOutlineEnabled = material.GetShaderPassEnabled(UtsShaderPassName.OUTLINE_PASS_NAME);
EditorGUI.BeginChangeCheck(); EditorGUI.BeginChangeCheck();
isOutlineEnabled = EditorGUILayout.Toggle(kOutline, isOutlineEnabled); isOutlineEnabled = EditorGUILayout.Toggle(kOutline, isOutlineEnabled);
@@ -2444,20 +2382,11 @@ namespace UnityEditor.Rendering.Toon
m_MaterialEditor.RegisterPropertyChangeUndo(kOutline); m_MaterialEditor.RegisterPropertyChangeUndo(kOutline);
if (isOutlineEnabled) if (isOutlineEnabled)
{ {
if (isLegacy) material.SetShaderPassEnabled(UtsShaderPassName.OUTLINE_PASS_NAME, true);
{
material.DisableKeyword(kDisableOutlineKeyword);
}
material.SetShaderPassEnabled(OutlineLightingModeName, true);
} }
else else
{ {
if (isLegacy) material.SetShaderPassEnabled(UtsShaderPassName.OUTLINE_PASS_NAME, false);
{
material.EnableKeyword(kDisableOutlineKeyword);
}
material.SetShaderPassEnabled(OutlineLightingModeName, false);
} }
} }
} }
@@ -2484,14 +2413,14 @@ namespace UnityEditor.Rendering.Toon
{ {
material.SetFloat(ShaderPropOutline, 0); material.SetFloat(ShaderPropOutline, 0);
//The keywords on the UTCS_Outline.cginc side are also toggled around. //The keywords on the UTCS_Outline.cginc side are also toggled around.
material.EnableKeyword("_OUTLINE_NML"); material.EnableKeyword("_OUTLINE_MODE_NML");
material.DisableKeyword("_OUTLINE_POS"); material.DisableKeyword("_OUTLINE_MODE_POS");
} }
else if (m_outlineMode == OutlineMode.PositionScaling) else if (m_outlineMode == OutlineMode.PositionScaling)
{ {
material.SetFloat(ShaderPropOutline, 1); material.SetFloat(ShaderPropOutline, 1);
material.EnableKeyword("_OUTLINE_POS"); material.EnableKeyword("_OUTLINE_MODE_POS");
material.DisableKeyword("_OUTLINE_NML"); material.DisableKeyword("_OUTLINE_MODE_NML");
} }
GUI_FloatProperty(material, Styles.outlineWidthText); GUI_FloatProperty(material, Styles.outlineWidthText);

View File

@@ -0,0 +1,40 @@
using Misaki.ShaderGUI;
using UnityEditor;
using UnityEngine;
namespace Misaki.HdrpToon.Editor
{
public class UTSShaderGUI : ScopedShaderGUI
{
private GUIStyle _headerStyle;
public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
{
if (!initialized)
{
OnInitialize(materialEditor, properties);
}
EditorGUILayout.Space(10);
EditorGUILayout.LabelField("HDRP Toon Shader", _headerStyle);
EditorGUILayout.Space(20);
DrawShaderGUI(properties);
}
private void OnInitialize(MaterialEditor materialEditor, MaterialProperty[] properties)
{
AddUIScope(new SurfaceOptionsScope());
AddUIScope(new ShadingColorScope());
AddUIScope(new PBRScope());
AddUIScope(new RimLightScope());
AddUIScope(new AngelRingScope());
AddUIScope(new OutlineScope());
Initialize(materialEditor, properties);
_headerStyle = new GUIStyle() { fontSize = 25, fontStyle = FontStyle.Bold, alignment = TextAnchor.MiddleCenter };
_headerStyle.normal.textColor = GUI.skin.label.normal.textColor;
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 41e8a43d8ee32f04cbf2ac4d1db45948

View File

@@ -1,13 +1,14 @@
{ {
"name": "Unity.Toonshader.Editor", "name": "Misaki.HdrpToon.Editor",
"rootNamespace": "Unity.Toonshader.Editor", "rootNamespace": "Misaki.HdrpToon.Editor",
"references": [ "references": [
"Unity.Toonshader", "Misaki.HdrpToon",
"Unity.RenderPipelines.Core.Runtime", "Unity.RenderPipelines.Core.Runtime",
"Unity.RenderPipelines.Core.Editor", "Unity.RenderPipelines.Core.Editor",
"Unity.RenderPipelines.HighDefinition.Runtime", "Unity.RenderPipelines.HighDefinition.Runtime",
"Unity.RenderPipelines.HighDefinition.Editor", "Unity.RenderPipelines.HighDefinition.Editor",
"Unity.Collections" "Unity.Collections",
"Misaki.ShaderGUI"
], ],
"includePlatforms": [ "includePlatforms": [
"Editor" "Editor"
@@ -29,11 +30,6 @@
"expression": "", "expression": "",
"define": "SRPCORE_IS_INSTALLED_FOR_UTS" "define": "SRPCORE_IS_INSTALLED_FOR_UTS"
}, },
{
"name": "com.unity.render-pipelines.universal",
"expression": "",
"define": "URP_IS_INSTALLED_FOR_UTS"
},
{ {
"name": "com.unity.render-pipelines.core", "name": "com.unity.render-pipelines.core",
"expression": "12.0.0", "expression": "12.0.0",

View File

@@ -6,7 +6,7 @@ using UnityEngine;
// Todo: Change this into a editor window // Todo: Change this into a editor window
namespace Unity.Toonshader.Editor namespace Misaki.HdrpToon.Editor
{ {
public class ModelOutlineJobs public class ModelOutlineJobs
{ {

View File

@@ -4,7 +4,7 @@ using UnityEditor.UIElements;
using UnityEngine; using UnityEngine;
using UnityEngine.UIElements; using UnityEngine.UIElements;
namespace Unity.Toonshader.Editor namespace Misaki.HdrpToon.Editor
{ {
public class SmoothNormalBakerWindow : EditorWindow public class SmoothNormalBakerWindow : EditorWindow
{ {

View File

@@ -3,18 +3,23 @@ using UnityEditor;
using UnityEngine; using UnityEngine;
using UnityEngine.UIElements; using UnityEngine.UIElements;
namespace Unity.Toonshader.Editor namespace Misaki.HdrpToon.Editor
{ {
public class UTSRendererSettingProvider : SettingsProvider public class UTSRendererSettingProvider : SettingsProvider
{ {
class Styles class Styles
{ {
public static GUIContent outline = new GUIContent("Outline Setting"); public static GUIContent hairShadow = new("Hair Shadow");
public static GUIContent hairShadow = new GUIContent("Hair Shadow Setting"); public static GUIContent hairBlending = new("Hair Blending");
public static GUIContent outline = new("Outline");
} }
private SerializedObject _customSettings; private SerializedObject _customSettings;
private SerializedProperty _hairShadowSetting;
private SerializedProperty _hairBlendingSetting;
private SerializedProperty _outlineSetting;
public UTSRendererSettingProvider(string path, SettingsScope scopes, IEnumerable<string> keywords = null) : base(path, scopes, keywords) public UTSRendererSettingProvider(string path, SettingsScope scopes, IEnumerable<string> keywords = null) : base(path, scopes, keywords)
{ {
} }
@@ -22,20 +27,26 @@ namespace Unity.Toonshader.Editor
public override void OnActivate(string searchContext, VisualElement rootElement) public override void OnActivate(string searchContext, VisualElement rootElement)
{ {
_customSettings = UTSRenderPassSettings.GetSerializedSettings(); _customSettings = UTSRenderPassSettings.GetSerializedSettings();
_hairShadowSetting = _customSettings.FindProperty("hairShadowSetting");
_hairBlendingSetting = _customSettings.FindProperty("hairBlendingSetting");
_outlineSetting = _customSettings.FindProperty("outlineSetting");
} }
public override void OnGUI(string searchContext) public override void OnGUI(string searchContext)
{ {
EditorGUI.BeginChangeCheck(); EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(_customSettings.FindProperty("outlineSetting"), Styles.outline); EditorGUILayout.PropertyField(_hairShadowSetting, Styles.hairShadow);
EditorGUILayout.PropertyField(_customSettings.FindProperty("hairShadowSetting"), Styles.hairShadow); EditorGUILayout.PropertyField(_hairBlendingSetting, Styles.hairBlending);
EditorGUILayout.PropertyField(_outlineSetting, Styles.outline);
_customSettings.ApplyModifiedPropertiesWithoutUndo(); _customSettings.ApplyModifiedPropertiesWithoutUndo();
if (EditorGUI.EndChangeCheck()) if (EditorGUI.EndChangeCheck())
{ {
RegisterUTSRenderPass.NotifyRendererSettingChanged(); UTSRenderPassRegistrar.NotifyRendererSettingChanged();
} }
} }
public static bool IsSettingsAvailable() public static bool IsSettingsAvailable()

View File

@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) <year> <copyright holders> Copyright (c) 2024 Enjie Huang
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

View File

@@ -42,7 +42,7 @@ The HDRP Toon Shader is designed to provide a high-quality toon shading effect f
Here are some examples of the HDRP Toon Shader in action: Here are some examples of the HDRP Toon Shader in action:
![Example 1](ReadmeAssets/preview-01.png) ![preview-01.png](https://s2.loli.net/2024/12/26/zHdfSXho4csURyx.png)
## Contributing ## Contributing

View File

@@ -1,8 +1,2 @@
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Unity.ToonShader.Editor")] [assembly: InternalsVisibleTo("Misaki.HdrpToon.Editor")]
[assembly: InternalsVisibleTo("Unity.VisualCompositor")]
[assembly: InternalsVisibleTo("Unity.VisualCompositor.Tests")]
[assembly: InternalsVisibleTo("Unity.VisualCompositor.Editor")]
[assembly: InternalsVisibleTo("Unity.VisualCompositor.EditorTests")]

View File

@@ -7,29 +7,31 @@ using UnityEditor;
using UnityEngine.Rendering.HighDefinition; using UnityEngine.Rendering.HighDefinition;
using Unity.Properties; using Unity.Properties;
namespace Unity.Rendering.HighDefinition.Toon namespace Misaki.HdrpToon
{ {
[ExecuteAlways] [ExecuteAlways]
[DisallowMultipleComponent] [DisallowMultipleComponent]
[RequireComponent(typeof(Light))] [RequireComponent(typeof(Light))]
internal class BoxLightAdjustment : MonoBehaviour public class BoxLightAdjustment : MonoBehaviour
{ {
private bool _initialized = false; private bool _initialized = false;
private bool _srpCallbackInitialized = false; private bool _srpCallbackInitialized = false;
[SerializeField]
private HDAdditionalLightData _bindingSourceLightData; private HDAdditionalLightData _bindingSourceLightData;
[SerializeField]
private HDAdditionalLightData _targetBoxLightData; private HDAdditionalLightData _targetBoxLightData;
[SerializeField]
private uint _layerMask; private uint _layerMask;
[SerializeField]
private Light _bindingSourceLight; private Light _bindingSourceLight;
[SerializeField]
private Light _targetBoxLight; private Light _targetBoxLight;
public Transform trackedTransform; public Transform trackedTransform;
public bool followGameObjectPosition = false; public bool followGameObjectPosition = false;
public bool followGameObjectRotation = false; public float distanceOffset = 20.0f;
public Vector3 positionOffset;
public Quaternion rotationOffset;
[CreateProperty] [CreateProperty]
public Light BindingSourceLight public Light BindingSourceLight
@@ -64,8 +66,8 @@ namespace Unity.Rendering.HighDefinition.Toon
return; return;
} }
UpdateShadowLayer(_bindingSourceLightData, _layerMask, value); UpdateShadowLayer(_bindingSourceLightData, value);
UpdateShadowLayer(_targetBoxLightData, _layerMask, value); UpdateShadowLayer(_targetBoxLightData, value);
_layerMask = value; _layerMask = value;
} }
@@ -92,13 +94,9 @@ namespace Unity.Rendering.HighDefinition.Toon
{ {
Initialize(); Initialize();
} }
// Start is called before the first frame update
private void Start()
{
}
// Update is called once per frame // Update is called once per frame
private void LateUpdate() private void Update()
{ {
Initialize(); Initialize();
@@ -125,16 +123,12 @@ namespace Unity.Rendering.HighDefinition.Toon
_targetBoxLight.enabled = _bindingSourceLight.enabled; _targetBoxLight.enabled = _bindingSourceLight.enabled;
_targetBoxLight.intensity = _bindingSourceLight.intensity; _targetBoxLight.intensity = _bindingSourceLight.intensity;
if (trackedTransform != null) if (trackedTransform != null && followGameObjectPosition)
{ {
if (followGameObjectPosition) var desiredPosition = trackedTransform.position - _bindingSourceLight.transform.forward * distanceOffset;
{
_targetBoxLight.transform.position = trackedTransform.transform.position + positionOffset; _targetBoxLight.transform.position = desiredPosition;
} _targetBoxLight.transform.rotation = _bindingSourceLight.transform.rotation;
if (followGameObjectRotation)
{
_targetBoxLight.transform.rotation = trackedTransform.transform.rotation * rotationOffset;
}
} }
} }
@@ -170,11 +164,6 @@ namespace Unity.Rendering.HighDefinition.Toon
Release(); Release();
} }
private void UpdateObjectLightLayers()
{
Initialize();
}
internal static GameObject CreateBoxLight(Transform transform) internal static GameObject CreateBoxLight(Transform transform)
{ {
if (transform == null) if (transform == null)
@@ -187,7 +176,7 @@ namespace Unity.Rendering.HighDefinition.Toon
#if UNITY_EDITOR #if UNITY_EDITOR
Undo.RegisterCreatedObjectUndo(lightGameObject, "Created Boxlight adjustment"); Undo.RegisterCreatedObjectUndo(lightGameObject, "Created Boxlight adjustment");
#endif #endif
var hdLightData = lightGameObject.AddHDLight(LightType.Box); var hdLightData = lightGameObject.AddHDLight(UnityEngine.LightType.Box);
// light size // light size
hdLightData.SetBoxSpotSize(new Vector2(10.0f, 10.0f)); // Size should be culculated with more acculacy? hdLightData.SetBoxSpotSize(new Vector2(10.0f, 10.0f)); // Size should be culculated with more acculacy?
var boxLightAdjustment = lightGameObject.GetComponent<BoxLightAdjustment>(); var boxLightAdjustment = lightGameObject.GetComponent<BoxLightAdjustment>();
@@ -228,12 +217,11 @@ namespace Unity.Rendering.HighDefinition.Toon
return lightGameObject; return lightGameObject;
} }
private void UpdateShadowLayer(HDAdditionalLightData lightData, uint oldValue, uint newValue) private void UpdateShadowLayer(HDAdditionalLightData lightData, uint newValue)
{ {
lightData.linkShadowLayers = false; lightData.linkShadowLayers = false;
var oldShadowLayer = lightData.GetShadowLayers(); var lightLayer = lightData.GetLightLayers();
oldShadowLayer &= ~oldValue; var newShadowLayer = lightLayer | newValue | UnityEngine.RenderingLayerMask.defaultRenderingLayerMask;
var newShadowLayer = oldShadowLayer | newValue;
lightData.SetShadowLightLayer((UnityEngine.Rendering.HighDefinition.RenderingLayerMask)newShadowLayer); lightData.SetShadowLightLayer((UnityEngine.Rendering.HighDefinition.RenderingLayerMask)newShadowLayer);
} }
@@ -256,8 +244,7 @@ namespace Unity.Rendering.HighDefinition.Toon
if (_targetBoxLight != null) if (_targetBoxLight != null)
{ {
positionOffset = _targetBoxLight.transform.position - trackedTransform.transform.position; distanceOffset = Mathf.Abs(Vector3.Distance(_targetBoxLight.transform.position, trackedTransform.transform.position));
rotationOffset = Quaternion.Inverse(trackedTransform.transform.rotation) * _targetBoxLight.transform.rotation;
} }
_initialized = true; _initialized = true;

8
Runtime/Constants.meta Normal file
View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 6987e5a46707b5240a0ec0d6c7374656
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,15 @@
using UnityEngine.Rendering;
namespace Misaki.HdrpToon
{
public static class UtsShaderPassName
{
public const string OUTLINE_PASS_NAME = "Outline";
public const string HAIR_SHADOW_CASTER_PASS_NAME = "HairShadowCaster";
public const string HAIR_BLENDING_TARGET_PASS_NAME = "HairBlendingTarget";
public static readonly ShaderTagId outlinePassId = new(OUTLINE_PASS_NAME);
public static readonly ShaderTagId hairShadowCasterPassId = new(HAIR_SHADOW_CASTER_PASS_NAME);
public static readonly ShaderTagId hairBlendingTargetPassId = new(HAIR_BLENDING_TARGET_PASS_NAME);
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8a2b199311606f54a9585b9b3ea31e7d

View File

@@ -2,24 +2,20 @@ using UnityEngine;
#if UNITY_EDITOR #if UNITY_EDITOR
using UnityEditor; using UnityEditor;
#endif #endif
namespace Unity.Rendering.Toon namespace Misaki.HdrpToon
{ {
[ExecuteAlways] [ExecuteAlways]
[DisallowMultipleComponent] [DisallowMultipleComponent]
[RequireComponent(typeof(Camera))] [RequireComponent(typeof(Camera))]
internal class DebugShadowmap : MonoBehaviour public class DebugShadowmap : MonoBehaviour
{ {
// flags // flags
bool m_initialized = false; bool m_initialized = false;
bool m_srpCallbackInitialized = false; bool m_srpCallbackInitialized = false;
[SerializeField] public bool m_enableShadowmapDebugging = false;
internal bool m_enableShadowmapDebugging = false; public bool m_enableSelfShadowDebugging = false;
[SerializeField] public bool m_enableBinalization = false;
internal bool m_enableSelfShadowDebugging = false; public bool m_enableOutlineDebugging = false;
[SerializeField]
internal bool m_enableBinalization = false;
[SerializeField]
internal bool m_enableOutlineDebugging = false;

View File

@@ -1,272 +0,0 @@
#ifndef UNITY_DEBUG_DISPLAY_INCLUDED
#define UNITY_DEBUG_DISPLAY_INCLUDED
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Debug.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.cs.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Debug/MaterialDebug.cs.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Debug/LightingDebug.cs.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Debug/MipMapDebug.cs.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Debug/ColorPickerDebug.cs.hlsl"
CBUFFER_START(UnityDebugDisplay)
// Set of parameters available when switching to debug shader mode
int _DebugLightingMode; // Match enum DebugLightingMode
int _DebugShadowMapMode;
float _DebugViewMaterialArray[11]; // Contain the id (define in various materialXXX.cs.hlsl) of the property to display
int _DebugMipMapMode; // Match enum DebugMipMapMode
int _DebugMipMapModeTerrainTexture; // Match enum DebugMipMapModeTerrainTexture
int _ColorPickerMode; // Match enum ColorPickerDebugMode
int _DebugStep;
int _DebugDepthPyramidMip;
int _DebugFullScreenMode;
float _DebugTransparencyOverdrawWeight;
float4 _DebugLightingAlbedo; // x == bool override, yzw = albedo for diffuse
float4 _DebugLightingSmoothness; // x == bool override, y == override value
float4 _DebugLightingNormal; // x == bool override
float4 _DebugLightingAmbientOcclusion; // x == bool override, y == override value
float4 _DebugLightingSpecularColor; // x == bool override, yzw = specular color
float4 _DebugLightingEmissiveColor; // x == bool override, yzw = emissive color
float4 _DebugLightingMaterialValidateHighColor; // user can specific the colors for the validator error conditions
float4 _DebugLightingMaterialValidateLowColor;
float4 _DebugLightingMaterialValidatePureMetalColor;
float4 _MousePixelCoord; // xy unorm, zw norm
float4 _MouseClickPixelCoord; // xy unorm, zw norm
int _MatcapMixAlbedo;
int _MatcapViewScale;
uint _DebugContactShadowLightIndex;
CBUFFER_END
// Local shader variables
static DirectionalShadowType g_DebugShadowAttenuation = 0;
StructuredBuffer<int2> _DebugDepthPyramidOffsets;
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Debug/PBRValidator.hlsl"
// When displaying lux meter we compress the light in order to be able to display value higher than 65504
// The sun is between 100 000 and 150 000, so we use 4 to be able to cover such a range (4 * 65504)
#define LUXMETER_COMPRESSION_RATIO 4
TEXTURE2D(_DebugFont); // Debug font to write string in shader
TEXTURE2D(_DebugMatCapTexture);
void GetPropertiesDataDebug(uint paramId, inout float3 result, inout bool needLinearToSRGB)
{
switch (paramId)
{
case DEBUGVIEWPROPERTIES_TESSELLATION:
#ifdef TESSELLATION_ON
result = float3(1.0, 0.0, 0.0);
#else
result = float3(0.0, 0.0, 0.0);
#endif
break;
case DEBUGVIEWPROPERTIES_PIXEL_DISPLACEMENT:
#ifdef _PIXEL_DISPLACEMENT // Caution: This define is related to a shader features (But it may become a standard features for HD)
result = float3(1.0, 0.0, 0.0);
#else
result = float3(0.0, 0.0, 0.0);
#endif
break;
case DEBUGVIEWPROPERTIES_VERTEX_DISPLACEMENT:
#ifdef _VERTEX_DISPLACEMENT // Caution: This define is related to a shader features (But it may become a standard features for HD)
result = float3(1.0, 0.0, 0.0);
#else
result = float3(0.0, 0.0, 0.0);
#endif
break;
case DEBUGVIEWPROPERTIES_TESSELLATION_DISPLACEMENT:
#ifdef _TESSELLATION_DISPLACEMENT // Caution: This define is related to a shader features (But it may become a standard features for HD)
result = float3(1.0, 0.0, 0.0);
#else
result = float3(0.0, 0.0, 0.0);
#endif
break;
case DEBUGVIEWPROPERTIES_DEPTH_OFFSET:
#ifdef _DEPTHOFFSET_ON // Caution: This define is related to a shader features (But it may become a standard features for HD)
result = float3(1.0, 0.0, 0.0);
#else
result = float3(0.0, 0.0, 0.0);
#endif
break;
case DEBUGVIEWPROPERTIES_LIGHTMAP:
#if defined(LIGHTMAP_ON) || defined (DIRLIGHTMAP_COMBINED) || defined(DYNAMICLIGHTMAP_ON)
result = float3(1.0, 0.0, 0.0);
#else
result = float3(0.0, 0.0, 0.0);
#endif
break;
case DEBUGVIEWPROPERTIES_INSTANCING:
#if defined(UNITY_INSTANCING_ENABLED)
result = float3(1.0, 0.0, 0.0);
#else
result = float3(0.0, 0.0, 0.0);
#endif
break;
}
}
float3 GetTextureDataDebug(uint paramId, float2 uv, Texture2D tex, float4 texelSize, float4 mipInfo, float3 originalColor)
{
float3 outColor = originalColor;
switch (paramId)
{
case DEBUGMIPMAPMODE_MIP_RATIO:
outColor = GetDebugMipColorIncludingMipReduction(originalColor, tex, texelSize, uv, mipInfo);
break;
case DEBUGMIPMAPMODE_MIP_COUNT:
outColor = GetDebugMipCountColor(originalColor, tex);
break;
case DEBUGMIPMAPMODE_MIP_COUNT_REDUCTION:
outColor = GetDebugMipReductionColor(tex, mipInfo);
break;
case DEBUGMIPMAPMODE_STREAMING_MIP_BUDGET:
outColor = GetDebugStreamingMipColor(tex, mipInfo);
break;
case DEBUGMIPMAPMODE_STREAMING_MIP:
outColor = GetDebugStreamingMipColorBlended(originalColor, tex, mipInfo);
break;
}
return outColor;
}
// DebugFont code assume black and white font with texture size 256x128 with bloc of 16x16
#define DEBUG_FONT_TEXT_WIDTH 16
#define DEBUG_FONT_TEXT_HEIGHT 16
#define DEBUG_FONT_TEXT_COUNT_X 16
#define DEBUG_FONT_TEXT_COUNT_Y 8
#define DEBUG_FONT_TEXT_ASCII_START 32
#define DEBUG_FONT_TEXT_SCALE_WIDTH 10 // This control the spacing between characters (if a character fill the text block it will overlap).
// Only support ASCII symbol from DEBUG_FONT_TEXT_ASCII_START to 126
// return black or white depends if we hit font character or not
// currentUnormCoord is current unormalized screen position
// fixedUnormCoord is the position where we want to draw something, this will be incremented by block font size in provided direction
// color is current screen color
// color of the font to use
// direction is 1 or -1 and indicate fixedUnormCoord block shift
void DrawCharacter(uint asciiValue, float3 fontColor, uint2 currentUnormCoord, inout uint2 fixedUnormCoord, inout float3 color, int direction)
{
// Are we inside a font display block on the screen ?
uint2 localCharCoord = currentUnormCoord - fixedUnormCoord;
if (localCharCoord.x >= 0 && localCharCoord.x < DEBUG_FONT_TEXT_WIDTH && localCharCoord.y >= 0 && localCharCoord.y < DEBUG_FONT_TEXT_HEIGHT)
{
localCharCoord.y = DEBUG_FONT_TEXT_HEIGHT - localCharCoord.y;
asciiValue -= DEBUG_FONT_TEXT_ASCII_START; // Our font start at ASCII table 32;
uint2 asciiCoord = uint2(asciiValue % DEBUG_FONT_TEXT_COUNT_X, asciiValue / DEBUG_FONT_TEXT_COUNT_X);
// Unorm coordinate inside the font texture
uint2 unormTexCoord = asciiCoord * uint2(DEBUG_FONT_TEXT_WIDTH, DEBUG_FONT_TEXT_HEIGHT) + localCharCoord;
// normalized coordinate
float2 normTexCoord = float2(unormTexCoord) / float2(DEBUG_FONT_TEXT_WIDTH * DEBUG_FONT_TEXT_COUNT_X, DEBUG_FONT_TEXT_HEIGHT * DEBUG_FONT_TEXT_COUNT_Y);
#if UNITY_UV_STARTS_AT_TOP
normTexCoord.y = 1.0 - normTexCoord.y;
#endif
float charColor = SAMPLE_TEXTURE2D_LOD(_DebugFont, s_point_clamp_sampler, normTexCoord, 0).r;
color = color * (1.0 - charColor) + charColor * fontColor;
}
fixedUnormCoord.x += DEBUG_FONT_TEXT_SCALE_WIDTH * direction;
}
// Shortcut to not have to file direction
void DrawCharacter(uint asciiValue, float3 fontColor, uint2 currentUnormCoord, inout uint2 fixedUnormCoord, inout float3 color)
{
DrawCharacter(asciiValue, fontColor, currentUnormCoord, fixedUnormCoord, color, 1);
}
// Draw a signed integer
// Can't display more than 16 digit
// The two following parameter are for float representation
// leading0 is used when drawing frac part of a float to draw the leading 0 (call is in charge of it)
// forceNegativeSign is used to force to display a negative sign as -0 is not recognize
void DrawInteger(int intValue, float3 fontColor, uint2 currentUnormCoord, inout uint2 fixedUnormCoord, inout float3 color, int leading0, bool forceNegativeSign)
{
const uint maxStringSize = 16;
uint absIntValue = abs(intValue);
// 1. Get size of the number of display
int numEntries = min((intValue == 0 ? 0 : log10(absIntValue)) + ((intValue < 0 || forceNegativeSign) ? 1 : 0) + leading0, maxStringSize);
// 2. Shift curseur to last location as we will go reverse
fixedUnormCoord.x += numEntries * DEBUG_FONT_TEXT_SCALE_WIDTH;
// 3. Display the number
for (uint j = 0; j < maxStringSize; ++j)
{
// Numeric value incurrent font start on the second row at 0
DrawCharacter((absIntValue % 10) + '0', fontColor, currentUnormCoord, fixedUnormCoord, color, -1);
if (absIntValue < 10)
break;
absIntValue /= 10;
}
// 4. Display leading 0
if (leading0 > 0)
{
for (int i = 0; i < leading0; ++i)
{
DrawCharacter('0', fontColor, currentUnormCoord, fixedUnormCoord, color, -1);
}
}
// 5. Display sign
if (intValue < 0 || forceNegativeSign)
{
DrawCharacter('-', fontColor, currentUnormCoord, fixedUnormCoord, color, -1);
}
// 6. Reset cursor at end location
fixedUnormCoord.x += (numEntries + 2) * DEBUG_FONT_TEXT_SCALE_WIDTH;
}
void DrawInteger(int intValue, float3 fontColor, uint2 currentUnormCoord, inout uint2 fixedUnormCoord, inout float3 color)
{
DrawInteger(intValue, fontColor, currentUnormCoord, fixedUnormCoord, color, 0, false);
}
void DrawFloat(float floatValue, float3 fontColor, uint2 currentUnormCoord, inout uint2 fixedUnormCoord, inout float3 color)
{
if (IsNaN(floatValue))
{
DrawCharacter('N', fontColor, currentUnormCoord, fixedUnormCoord, color);
DrawCharacter('a', fontColor, currentUnormCoord, fixedUnormCoord, color);
DrawCharacter('N', fontColor, currentUnormCoord, fixedUnormCoord, color);
}
else
{
int intValue = int(floatValue);
bool forceNegativeSign = floatValue >= 0.0f ? false : true;
DrawInteger(intValue, fontColor, currentUnormCoord, fixedUnormCoord, color, 0, forceNegativeSign);
DrawCharacter('.', fontColor, currentUnormCoord, fixedUnormCoord, color);
int fracValue = int(frac(abs(floatValue)) * 1e6); // 6 digit
int leading0 = 6 - (int(log10(fracValue)) + 1); // Counting leading0 to add in front of the float
DrawInteger(fracValue, fontColor, currentUnormCoord, fixedUnormCoord, color, leading0, false);
}
}
// Debug rendering is performed at the end of the frame (after post-processing).
// Debug textures are never flipped upside-down automatically. Therefore, we must always flip manually.
bool ShouldFlipDebugTexture()
{
#if UNITY_UV_STARTS_AT_TOP
return (_ProjectionParams.x > 0);
#else
return (_ProjectionParams.x < 0);
#endif
}
#endif

View File

@@ -1,27 +0,0 @@
//#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/NormalBuffer.hlsl"
#ifndef DECODEDEPTHNORMALS_INCLUDED
#define DECODEDEPTHNORMALS_INCLUDED
inline float DecodeFloatRG(float2 enc) {
float2 kDecodeDot = float2(1.0, 1 / 255.0);
return dot(enc, kDecodeDot);
}
inline float3 DecodeViewNormalStereo(float4 enc4) {
float kScale = 1.7777;
float3 nn = enc4.xyz * float3(2 * kScale, 2 * kScale, 0) + float3(-kScale, -kScale, 1);
float g = 2.0 / dot(nn.xyz, nn.xyz);
float3 n;
n.xy = g * nn.xy;
n.z = g - 1;
return n;
}
inline void DecodeDepthNormal(float4 enc, out float depth, out float3 normal) {
depth = DecodeFloatRG(enc.zw);
normal = DecodeViewNormalStereo(enc);
}
#endif

View File

@@ -1,298 +0,0 @@
//Unity Toon Shader/HDRP
//nobuyuki@unity3d.com
//toshiyuki@unity3d.com (Universal RP/HDRP)
float3 UTS_MainLight(LightLoopContext lightLoopContext, FragInputs input, float3 mainLihgtDirection, float3 mainLightColor, out float inverseClipping, out float channelOutAlpha, out UTSData utsData)
{
channelOutAlpha = 1.0f;
uint2 tileIndex = uint2(input.positionSS.xy) / GetTileSize();
inverseClipping = 0;
// input.positionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS.xyz, tileIndex);
#ifdef VARYINGS_NEED_POSITION_WS
float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS);
#else
// Unused
float3 V = float3(1.0, 1.0, 1.0); // Avoid the division by 0
#endif
SurfaceData surfaceData;
BuiltinData builtinData;
GetSurfaceAndBuiltinData(input, V, posInput, surfaceData, builtinData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
PreLightData preLightData = GetPreLightData(V, posInput, bsdfData);
/* todo. these should be put int a struct */
float4 Set_UV0 = input.texCoord0;
float3x3 tangentTransform = input.tangentToWorld;
//UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoords))
float4 n = SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, Set_UV0.xy);
// float3 _NormalMap_var = UnpackNormalScale(tex2D(_NormalMap, TRANSFORM_TEX(Set_UV0, _NormalMap)), _BumpScale);
float3 _NormalMap_var = UnpackNormalScale(n, _BumpScale);
float3 normalLocal = _NormalMap_var.rgb;
utsData.normalDirection = normalize(mul(normalLocal, tangentTransform)); // Perturbed normals
float4 _BaseColorMap_var = SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, TRANSFORM_TEX(Set_UV0, _BaseColorMap));
float3 i_normalDir = surfaceData.normalWS;
utsData.viewDirection = V;
/* to here todo. these should be put int a struct */
//v.2.0.4
#if defined(_IS_CLIPPING_MODE)
//DoubleShadeWithFeather_Clipping
float4 _ClippingMask_var = SAMPLE_TEXTURE2D(_ClippingMask, sampler_BaseColorMap, TRANSFORM_TEX(Set_UV0, _ClippingMask));
float Set_Clipping = saturate((lerp(_ClippingMask_var.r, (1.0 - _ClippingMask_var.r), _Inverse_Clipping) + _Clipping_Level));
clip(Set_Clipping - 0.5);
#elif defined(_IS_CLIPPING_TRANSMODE) || defined(_IS_TRANSCLIPPING_ON)
//DoubleShadeWithFeather_TransClipping
float4 _ClippingMask_var = SAMPLE_TEXTURE2D(_ClippingMask, sampler_BaseColorMap, TRANSFORM_TEX(Set_UV0, _ClippingMask));
float Set_BaseColorMapAlpha = _BaseColorMap_var.a;
float _IsBaseMapAlphaAsClippingMask_var = lerp(_ClippingMask_var.r, Set_BaseColorMapAlpha, _IsBaseMapAlphaAsClippingMask);
float _Inverse_Clipping_var = lerp(_IsBaseMapAlphaAsClippingMask_var, (1.0 - _IsBaseMapAlphaAsClippingMask_var), _Inverse_Clipping);
float Set_Clipping = saturate((_Inverse_Clipping_var + _Clipping_Level));
clip(Set_Clipping - 0.5);
inverseClipping = _Inverse_Clipping_var;
#elif defined(_IS_CLIPPING_OFF) || defined(_IS_TRANSCLIPPING_OFF)
//DoubleShadeWithFeather
#endif
float shadowAttenuation = (float)lightLoopContext.shadowValue;
// float4 tmpColor = EvaluateLight_Directional(context, posInput, _DirectionalLightDatas[mainLightIndex]);
// float3 mainLightColor = tmpColor.xyz;
float3 defaultLightDirection = normalize(UNITY_MATRIX_V[2].xyz + UNITY_MATRIX_V[1].xyz);
float3 defaultLightColor = saturate(max(float3(0.05, 0.05, 0.05) * _Unlit_Intensity, max(ShadeSH9(float4(0.0, 0.0, 0.0, 1.0)), ShadeSH9(float4(0.0, -1.0, 0.0, 1.0)).rgb) * _Unlit_Intensity));
float3 customLightDirection = normalize(mul(UNITY_MATRIX_M, float4(((float3(1.0, 0.0, 0.0) * _Offset_X_Axis_BLD * 10) + (float3(0.0, 1.0, 0.0) * _Offset_Y_Axis_BLD * 10) + (float3(0.0, 0.0, -1.0) * lerp(-1.0, 1.0, _Inverse_Z_Axis_BLD))), 0)).xyz);
float3 lightDirection = normalize(lerp(defaultLightDirection, mainLihgtDirection.xyz, any(mainLihgtDirection.xyz)));
lightDirection = lerp(lightDirection, customLightDirection, _Is_BLD);
float3 originalLightColor = mainLightColor;
originalLightColor = lerp(originalLightColor, clamp(originalLightColor, ConvertFromEV100(_ToonEvAdjustmentValueMin ), ConvertFromEV100(_ToonEvAdjustmentValueMax)), _ToonEvAdjustmentCurve);
float3 lightColor = lerp(max(defaultLightColor, originalLightColor), max(defaultLightColor, saturate(originalLightColor)), max(_Is_Filter_LightColor, _ToonLightHiCutFilter));
////// Lighting:
float3 halfDirection = normalize(utsData.viewDirection + lightDirection);
//v.2.0.5
_Color = _BaseColor;
float3 Set_LightColor = lightColor.rgb;
float3 Set_BaseColor = lerp((_BaseColorMap_var.rgb * _BaseColor.rgb), ((_BaseColorMap_var.rgb * _BaseColor.rgb) * Set_LightColor), _Is_LightColor_Base);
float3 clippingColor = float3(1.0f, 1.0f, 1.0f);
#ifdef _IS_CLIPPING_MATTE
if (_ClippingMatteMode == 5)
{
clippingColor = float3(0.0f, 0.0f, 0.0f);
return clippingColor;
}
#endif // _IS_CLIPPING_MATTE
#ifdef _IS_CLIPPING_MATTE
if (_ClippingMatteMode == 1)
{
clippingColor = Set_BaseColor;
return clippingColor;
}
#endif // _IS_CLIPPING_MATTE
#ifdef UTS_LAYER_VISIBILITY
float3 overridingColor = lerp(_BaseColorMaskColor, float4(_BaseColorMaskColor.w, _BaseColorMaskColor.w, _BaseColorMaskColor.w, 1.0f), _ComposerMaskMode).xyz;
float maskEnabled = max(_BaseColorOverridden, _ComposerMaskMode);
Set_BaseColor = lerp(Set_BaseColor, overridingColor, maskEnabled);
Set_BaseColor *= _BaseColorVisible;
float Set_BaseColorAlpha = _BaseColorVisible;
#endif //#ifdef UTS_LAYER_VISIBILITY
//v.2.0.5
float4 _1st_ShadeMap_var = lerp(SAMPLE_TEXTURE2D(_1st_ShadeMap, sampler_BaseColorMap,TRANSFORM_TEX(Set_UV0, _1st_ShadeMap)), _BaseColorMap_var, _Use_BaseAs1st);
float3 Set_1st_ShadeColor = lerp((_1st_ShadeColor.rgb * _1st_ShadeMap_var.rgb), ((_1st_ShadeColor.rgb * _1st_ShadeMap_var.rgb) * Set_LightColor), _Is_LightColor_1st_Shade);
#ifdef _IS_CLIPPING_MATTE
if (_ClippingMatteMode == 2)
{
clippingColor = Set_1st_ShadeColor;
return clippingColor;
}
#endif // _IS_CLIPPING_MATTE
#ifdef UTS_LAYER_VISIBILITY
{
float4 overridingColor = lerp(_FirstShadeMaskColor, float4(_FirstShadeMaskColor.w, _FirstShadeMaskColor.w, _FirstShadeMaskColor.w, 1.0f), _ComposerMaskMode);
float maskEnabled = max(_FirstShadeOverridden, _ComposerMaskMode);
Set_1st_ShadeColor = lerp(Set_1st_ShadeColor, overridingColor.xyz, maskEnabled);
Set_1st_ShadeColor = lerp(Set_1st_ShadeColor, Set_BaseColor, 1.0f - _FirstShadeVisible);
}
float Set_1st_ShadeAlpha = _FirstShadeVisible;
#endif //#ifdef UTS_LAYER_VISIBILITY
//v.2.0.5
float4 _2nd_ShadeMap_var = lerp(SAMPLE_TEXTURE2D(_2nd_ShadeMap, sampler_BaseColorMap,TRANSFORM_TEX(Set_UV0, _2nd_ShadeMap)), _1st_ShadeMap_var, _Use_1stAs2nd);
float3 Set_2nd_ShadeColor = lerp((_2nd_ShadeColor.rgb * _2nd_ShadeMap_var.rgb), ((_2nd_ShadeColor.rgb * _2nd_ShadeMap_var.rgb) * Set_LightColor), _Is_LightColor_2nd_Shade);
float _HalfLambert_var = 0.5 * dot(lerp(i_normalDir, utsData.normalDirection, _Is_NormalMapToBase), lightDirection) + 0.5;
float4 _Set_2nd_ShadePosition_var = tex2D(_Set_2nd_ShadePosition, TRANSFORM_TEX(Set_UV0, _Set_2nd_ShadePosition));
float4 _Set_1st_ShadePosition_var = tex2D(_Set_1st_ShadePosition, TRANSFORM_TEX(Set_UV0, _Set_1st_ShadePosition));
float _1stColorFeatherForMask = lerp(_BaseShade_Feather, 0.0f, max(_FirstShadeOverridden, _ComposerMaskMode));
float _2ndColorFeatherForMask = lerp(_1st2nd_Shades_Feather, 0.0f, max(_SecondShadeOverridden, _ComposerMaskMode));
//v.2.0.6
//Minmimum value is same as the Minimum Feather's value with the Minimum Step's value as threshold.
float _SystemShadowsLevel_var = (shadowAttenuation * 0.5) + 0.5 + _Tweak_SystemShadowsLevel > 0.001 ? (shadowAttenuation * 0.5) + 0.5 + _Tweak_SystemShadowsLevel : 0.0001;
float Set_FinalShadowMask = saturate((1.0 + ((lerp(_HalfLambert_var, _HalfLambert_var * saturate(_SystemShadowsLevel_var), _Set_SystemShadowsToBase) - (_BaseColor_Step - _1stColorFeatherForMask)) * ((1.0 - _Set_1st_ShadePosition_var.rgb).r - 1.0)) / (_BaseColor_Step - (_BaseColor_Step - _1stColorFeatherForMask))));
//
//Composition: 3 Basic Colors as Set_FinalBaseColor
#ifdef _IS_CLIPPING_MATTE
if (_ClippingMatteMode == 3)
{
clippingColor = Set_2nd_ShadeColor;
return clippingColor;
}
#endif // _IS_CLIPPING_MATTE
#ifdef UTS_LAYER_VISIBILITY
{
float4 overridingColor = lerp(_SecondShadeMaskColor, float4(_SecondShadeMaskColor.w, _SecondShadeMaskColor.w, _SecondShadeMaskColor.w, 1.0f), _ComposerMaskMode);
float maskEnabled = max(_SecondShadeOverridden, _ComposerMaskMode);
Set_2nd_ShadeColor = lerp(Set_2nd_ShadeColor, overridingColor.xyz, maskEnabled);
Set_2nd_ShadeColor = lerp(Set_2nd_ShadeColor, Set_BaseColor, 1.0f - _SecondShadeVisible);
}
float Set_2nd_ShadeAlpha = _SecondShadeVisible;
#endif //#ifdef UTS_LAYER_VISIBILITY
float3 Set_FinalBaseColor = lerp(Set_BaseColor, lerp(Set_1st_ShadeColor, Set_2nd_ShadeColor, saturate((1.0 + ((_HalfLambert_var - (_ShadeColor_Step - _2ndColorFeatherForMask)) * ((1.0 - _Set_2nd_ShadePosition_var.rgb).r - 1.0)) / (_ShadeColor_Step - (_ShadeColor_Step - _2ndColorFeatherForMask))))), Set_FinalShadowMask); // Final Color
channelOutAlpha = lerp(Set_BaseColorAlpha, lerp(Set_1st_ShadeAlpha, Set_2nd_ShadeAlpha, saturate((1.0 + ((_HalfLambert_var - (_ShadeColor_Step - _2ndColorFeatherForMask)) * ((1.0 - _Set_2nd_ShadePosition_var.rgb).r - 1.0)) / (_ShadeColor_Step - (_ShadeColor_Step - _2ndColorFeatherForMask))))), Set_FinalShadowMask);
float4 _Set_HighColorMask_var = tex2D(_Set_HighColorMask, TRANSFORM_TEX(Set_UV0, _Set_HighColorMask));
float _Specular_var = 0.5 * dot(halfDirection, lerp(i_normalDir, utsData.normalDirection, _Is_NormalMapToHighColor)) + 0.5; // Specular
float _TweakHighColorMask_var = (saturate((_Set_HighColorMask_var.g + _Tweak_HighColorMaskLevel)) * lerp((1.0 - step(_Specular_var, (1.0 - pow(_HighColor_Power, 5)))), pow(abs(_Specular_var), exp2(lerp(11, 1, _HighColor_Power))), _Is_SpecularToHighColor));
float4 _HighColor_Tex_var = tex2D(_HighColor_Tex, TRANSFORM_TEX(Set_UV0, _HighColor_Tex));
float3 _HighColorWithOutTweak_var = lerp((_HighColor_Tex_var.rgb * _HighColor.rgb), ((_HighColor_Tex_var.rgb * _HighColor.rgb) * Set_LightColor), _Is_LightColor_HighColor);
float3 _HighColor_var = _HighColorWithOutTweak_var * _TweakHighColorMask_var;
#ifdef _IS_CLIPPING_MATTE
if (_ClippingMatteMode == 4)
{
clippingColor = _HighColorWithOutTweak_var;
return clippingColor;
}
#endif // _IS_CLIPPING_MATTE
//Composition: 3 Basic Colors and HighColor as Set_HighColor
#ifdef UTS_LAYER_VISIBILITY
float3 Set_HighColor;
{
float4 overridingColor = lerp(_HighlightMaskColor, float4(_HighlightMaskColor.w, _HighlightMaskColor.w, _HighlightMaskColor.w, 1.0f), _ComposerMaskMode);
float maskEnabled = max(_HighlightOverridden, _ComposerMaskMode);
_HighColor_var *= _HighlightVisible;
Set_HighColor =
lerp(SATURATE_IF_SDR(Set_FinalBaseColor - _TweakHighColorMask_var), Set_FinalBaseColor,
lerp(_Is_BlendAddToHiColor, 1.0
, _Is_SpecularToHighColor));
float3 addColor =
lerp(_HighColor_var, (_HighColor_var * ((1.0 - Set_FinalShadowMask) + (Set_FinalShadowMask * _TweakHighColorOnShadow)))
, _Is_UseTweakHighColorOnShadow);
Set_HighColor += addColor;
if (any(addColor))
{
Set_HighColor = lerp(Set_HighColor, overridingColor.xyz, maskEnabled);
channelOutAlpha = _HighlightVisible;
}
}
#else
float3 Set_HighColor = (lerp(SATURATE_IF_SDR((Set_FinalBaseColor - _TweakHighColorMask_var)), Set_FinalBaseColor, lerp(_Is_BlendAddToHiColor, 1.0, _Is_SpecularToHighColor)) + lerp(_HighColor_var, (_HighColor_var * ((1.0 - Set_FinalShadowMask) + (Set_FinalShadowMask * _TweakHighColorOnShadow))), _Is_UseTweakHighColorOnShadow));
#endif
float4 _Set_RimLightMask_var = tex2D(_Set_RimLightMask, TRANSFORM_TEX(Set_UV0, _Set_RimLightMask));
float3 _Is_LightColor_RimLight_var = lerp(_RimLightColor.rgb, (_RimLightColor.rgb * Set_LightColor), _Is_LightColor_RimLight);
float _RimArea_var = abs((1.0 - dot(lerp(i_normalDir, utsData.normalDirection, _Is_NormalMapToRimLight), utsData.viewDirection)));
float _RimLightPower_var = pow(_RimArea_var, exp2(lerp(3, 0, _RimLight_Power)));
float _Rimlight_InsideMask_var = saturate(lerp((0.0 + ((_RimLightPower_var - _RimLight_InsideMask) * (1.0 - 0.0)) / (1.0 - _RimLight_InsideMask)), step(_RimLight_InsideMask, _RimLightPower_var), _RimLight_FeatherOff));
float _VertHalfLambert_var = 0.5 * dot(i_normalDir, lightDirection) + 0.5;
float3 _LightDirection_MaskOn_var = lerp((_Is_LightColor_RimLight_var * _Rimlight_InsideMask_var), (_Is_LightColor_RimLight_var * saturate((_Rimlight_InsideMask_var - ((1.0 - _VertHalfLambert_var) + _Tweak_LightDirection_MaskLevel)))), _LightDirection_MaskOn);
float _ApRimLightPower_var = pow(_RimArea_var, exp2(lerp(3, 0, _Ap_RimLight_Power)));
#ifdef UTS_LAYER_VISIBILITY
float4 overridingRimColor = lerp(_RimLightMaskColor, float4(_RimLightMaskColor.w, _RimLightMaskColor.w, _RimLightMaskColor.w, 1.0f), _ComposerMaskMode);
float maskRimEnabled = max(_RimLightOverridden, _ComposerMaskMode);
float Set_RimLightAlpha = _RimLightVisible;
float3 Set_RimLight = (saturate((_Set_RimLightMask_var.g + _Tweak_RimLightMaskLevel)) * lerp(_LightDirection_MaskOn_var, (_LightDirection_MaskOn_var + (lerp(_Ap_RimLightColor.rgb, (_Ap_RimLightColor.rgb * Set_LightColor), _Is_LightColor_Ap_RimLight) * saturate((lerp((0.0 + ((_ApRimLightPower_var - _RimLight_InsideMask) * (1.0 - 0.0)) / (1.0 - _RimLight_InsideMask)), step(_RimLight_InsideMask, _ApRimLightPower_var), _Ap_RimLight_FeatherOff) - (saturate(_VertHalfLambert_var) + _Tweak_LightDirection_MaskLevel))))), _Add_Antipodean_RimLight));
Set_RimLight *= _RimLightVisible;
float3 _RimLight_var = lerp(Set_HighColor, (Set_HighColor + Set_RimLight), _RimLight);
if (any(Set_RimLight) * maskRimEnabled)
{
_RimLight_var = overridingRimColor.xyz;
channelOutAlpha = Set_RimLightAlpha;
}
#else
float3 Set_RimLight = (saturate((_Set_RimLightMask_var.g + _Tweak_RimLightMaskLevel)) * lerp(_LightDirection_MaskOn_var, (_LightDirection_MaskOn_var + (lerp(_Ap_RimLightColor.rgb, (_Ap_RimLightColor.rgb * Set_LightColor), _Is_LightColor_Ap_RimLight) * saturate((lerp((0.0 + ((_ApRimLightPower_var - _RimLight_InsideMask) * (1.0 - 0.0)) / (1.0 - _RimLight_InsideMask)), step(_RimLight_InsideMask, _ApRimLightPower_var), _Ap_RimLight_FeatherOff) - (saturate(_VertHalfLambert_var) + _Tweak_LightDirection_MaskLevel))))), _Add_Antipodean_RimLight));
//Composition: HighColor and RimLight as _RimLight_var
float3 _RimLight_var = lerp(Set_HighColor, (Set_HighColor + Set_RimLight), _RimLight);
#endif
//Matcap
//v.2.0.6 : CameraRolling Stabilizer
//Mirror Script Determination: if sign_Mirror = -1, determine "Inside the mirror".
//v.2.0.7
utsData.signMirror = 0.0; // i.mirrorFlag; todo.
float3 _Camera_Right = UNITY_MATRIX_V[0].xyz;
float3 _Camera_Front = UNITY_MATRIX_V[2].xyz;
float3 _Up_Unit = float3(0, 1, 0);
float3 _Right_Axis = cross(_Camera_Front, _Up_Unit);
//Invert if it's "inside the mirror".
if (utsData.signMirror < 0) {
_Right_Axis = -1 * _Right_Axis;
_Rotate_MatCapUV = -1 * _Rotate_MatCapUV;
}
else {
_Right_Axis = _Right_Axis;
}
float _Camera_Right_Magnitude = sqrt(_Camera_Right.x * _Camera_Right.x + _Camera_Right.y * _Camera_Right.y + _Camera_Right.z * _Camera_Right.z);
float _Right_Axis_Magnitude = sqrt(_Right_Axis.x * _Right_Axis.x + _Right_Axis.y * _Right_Axis.y + _Right_Axis.z * _Right_Axis.z);
float _Camera_Roll_Cos = dot(_Right_Axis, _Camera_Right) / (_Right_Axis_Magnitude * _Camera_Right_Magnitude);
utsData.cameraRoll = acos(clamp(_Camera_Roll_Cos, -1, 1));
utsData.cameraDir = _Camera_Right.y < 0 ? -1 : 1;
float _Rot_MatCapUV_var_ang = (_Rotate_MatCapUV * 3.141592654) - utsData.cameraDir * utsData.cameraRoll * _CameraRolling_Stabilizer;
//v.2.0.7
float2 _Rot_MatCapNmUV_var = RotateUV(Set_UV0.xy, (_Rotate_NormalMapForMatCapUV * 3.141592654f), float2(0.5, 0.5), 1.0);
//V.2.0.6
float3 _NormalMapForMatCap_var = UnpackNormalScale(tex2D(_NormalMapForMatCap, TRANSFORM_TEX(_Rot_MatCapNmUV_var, _NormalMapForMatCap)), _BumpScaleMatcap);
//v.2.0.5: MatCap with camera skew correction
float3 viewNormal = (mul(UNITY_MATRIX_V, float4(lerp(i_normalDir, mul(_NormalMapForMatCap_var.rgb, tangentTransform).rgb, _Is_NormalMapForMatCap), 0))).rgb;
float3 NormalBlend_MatcapUV_Detail = viewNormal.rgb * float3(-1, -1, 1);
float3 NormalBlend_MatcapUV_Base = (mul(UNITY_MATRIX_V, float4(utsData.viewDirection, 0)).rgb * float3(-1, -1, 1)) + float3(0, 0, 1);
float3 noSknewViewNormal = NormalBlend_MatcapUV_Base * dot(NormalBlend_MatcapUV_Base, NormalBlend_MatcapUV_Detail) / NormalBlend_MatcapUV_Base.b - NormalBlend_MatcapUV_Detail;
float2 _ViewNormalAsMatCapUV = (lerp(noSknewViewNormal, viewNormal, _Is_Ortho).rg * 0.5) + 0.5;
//v.2.0.7
float2 _Rot_MatCapUV_var = RotateUV((0.0 + ((_ViewNormalAsMatCapUV - (0.0 + _Tweak_MatCapUV)) * (1.0 - 0.0)) / ((1.0 - _Tweak_MatCapUV) - (0.0 + _Tweak_MatCapUV))), _Rot_MatCapUV_var_ang, float2(0.5, 0.5), 1.0);
//Invert if it's "inside the mirror".
if (utsData.signMirror < 0) {
_Rot_MatCapUV_var.x = 1 - _Rot_MatCapUV_var.x;
}
else {
_Rot_MatCapUV_var = _Rot_MatCapUV_var;
}
//v.2.0.6 : LOD of Matcap
//
//MatcapMask
float4 _MatCap_Sampler_var = tex2Dlod(_MatCap_Sampler, float4(TRANSFORM_TEX(_Rot_MatCapUV_var, _MatCap_Sampler), 0.0, _BlurLevelMatcap));
float4 _Set_MatcapMask_var = tex2D(_Set_MatcapMask, TRANSFORM_TEX(Set_UV0, _Set_MatcapMask));
float _Tweak_MatcapMaskLevel_var = saturate(lerp(_Set_MatcapMask_var.g, (1.0 - _Set_MatcapMask_var.g), _Inverse_MatcapMask) + _Tweak_MatcapMaskLevel);
//
float3 _Is_LightColor_MatCap_var = lerp((_MatCap_Sampler_var.rgb * _MatCapColor.rgb), ((_MatCap_Sampler_var.rgb * _MatCapColor.rgb) * Set_LightColor), _Is_LightColor_MatCap);
//v.2.0.6 : ShadowMask on Matcap in Blend mode : multiply
float3 Set_MatCap = lerp(_Is_LightColor_MatCap_var, (_Is_LightColor_MatCap_var * ((1.0 - Set_FinalShadowMask) + (Set_FinalShadowMask * _TweakMatCapOnShadow)) + lerp(Set_HighColor * Set_FinalShadowMask * (1.0 - _TweakMatCapOnShadow), float3(0.0, 0.0, 0.0), _Is_BlendAddToMatCap)), _Is_UseTweakMatCapOnShadow);
//
//Composition: RimLight and MatCap as finalColor
//Broke down finalColor composition
float3 matCapColorOnAddMode = _RimLight_var + Set_MatCap * _Tweak_MatcapMaskLevel_var;
float _Tweak_MatcapMaskLevel_var_MultiplyMode = _Tweak_MatcapMaskLevel_var * lerp(1.0, (1.0 - (Set_FinalShadowMask) * (1.0 - _TweakMatCapOnShadow)), _Is_UseTweakMatCapOnShadow);
float3 matCapColorOnMultiplyMode = Set_HighColor * (1 - _Tweak_MatcapMaskLevel_var_MultiplyMode) + Set_HighColor * Set_MatCap * _Tweak_MatcapMaskLevel_var_MultiplyMode + lerp(float3(0, 0, 0), Set_RimLight, _RimLight);
float3 matCapColorFinal = lerp(matCapColorOnMultiplyMode, matCapColorOnAddMode, _Is_BlendAddToMatCap);
float3 finalColor = lerp(_RimLight_var, matCapColorFinal, _MatCap);// Final Composition before Emissive
//
//v.2.0.6: GI_Intensity with Intensity Multiplier Filter
float3 envLightColor = DecodeLightProbe(utsData.normalDirection) < float3(1, 1, 1) ? DecodeLightProbe(utsData.normalDirection) : float3(1, 1, 1);
float envLightIntensity = 0.299 * envLightColor.r + 0.587 * envLightColor.g + 0.114 * envLightColor.b < 1 ? (0.299 * envLightColor.r + 0.587 * envLightColor.g + 0.114 * envLightColor.b) : 1;
finalColor = SATURATE_IF_SDR(finalColor) + (envLightColor * envLightIntensity * _GI_Intensity * smoothstep(1, 0, envLightIntensity / 2)) + emissive;
return finalColor;
}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 8f3d7136d29e4e94694ab0df05f6a94c
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,143 +0,0 @@
//Unity Toon Shader/HDRP
//nobuyuki@unity3d.com
//toshiyuki@unity3d.com (Universal RP/HDRP)
float3 UTS_OtherLights(FragInputs input, float3 i_normalDir,
float3 additionalLightColor, float3 lightDirection, float notDirectional, out float channelOutAlpha)
{
channelOutAlpha = 1.0f;
#ifdef _IS_CLIPPING_MATTE
if (_ClippingMatteMode != 0)
{
return float3(0.0f, 0.0f, 0.0f);
}
#endif // _IS_CLIPPING_MATTE
/* todo. these should be put into struct */
#ifdef VARYINGS_NEED_POSITION_WS
float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS);
#else
// Unused
float3 V = float3(1.0, 1.0, 1.0); // Avoid the division by 0
#endif
float4 Set_UV0 = input.texCoord0;
float3x3 tangentTransform = input.tangentToWorld;
//UnpackNormalmapRGorAG(SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, texCoords))
float4 n = SAMPLE_TEXTURE2D_LOD(_NormalMap, sampler_NormalMap, Set_UV0.xy, 0);
// float3 _NormalMap_var = UnpackNormalScale(tex2D(_NormalMap, TRANSFORM_TEX(Set_UV0, _NormalMap)), _BumpScale);
float3 _NormalMap_var = UnpackNormalScale(n, _BumpScale);
float3 normalLocal = _NormalMap_var.rgb;
float3 normalDirection = normalize(mul(normalLocal, tangentTransform)); // Perturbed normals
// float3 i_normalDir = surfaceData.normalWS;
float3 viewDirection = V;
float4 _MainTex_var = SAMPLE_TEXTURE2D_LOD(_MainTex, sampler_MainTex, TRANSFORM_TEX(Set_UV0, _MainTex), 0.0f);
/* end of todo.*/
//v.2.0.5:
float3 addPassLightColor = (0.5 * dot(lerp(i_normalDir, normalDirection, _Is_NormalMapToBase), lightDirection) + 0.5) * additionalLightColor.rgb;
float pureIntencity = max(0.001, (0.299 * additionalLightColor.r + 0.587 * additionalLightColor.g + 0.114 * additionalLightColor.b));
float3 lightColor = max(0, lerp(addPassLightColor, lerp(0, min(addPassLightColor, addPassLightColor / pureIntencity), notDirectional), _Is_Filter_LightColor));
float3 halfDirection = normalize(viewDirection + lightDirection); // has to be recalced here.
//v.2.0.5:
_BaseColor_Step = saturate(_BaseColor_Step + _StepOffset);
_ShadeColor_Step = saturate(_ShadeColor_Step + _StepOffset);
//
//v.2.0.5: If Added lights is directional, set 0 as _LightIntensity
float _LightIntensity = lerp(0, (0.299 * additionalLightColor.r + 0.587 * additionalLightColor.g + 0.114 * additionalLightColor.b), notDirectional);
//v.2.0.5: Filtering the high intensity zone of PointLights
float3 Set_LightColor = lightColor;
//
float3 Set_BaseColor = lerp((_BaseColor.rgb * _MainTex_var.rgb * _LightIntensity), ((_BaseColor.rgb * _MainTex_var.rgb) * Set_LightColor), _Is_LightColor_Base);
#ifdef UTS_LAYER_VISIBILITY
float4 overridingColor = lerp(_BaseColorMaskColor, float4(_BaseColorMaskColor.w, _BaseColorMaskColor.w, _BaseColorMaskColor.w, 1.0f), _ComposerMaskMode);
float maskEnabled = max(_BaseColorOverridden, _ComposerMaskMode);
Set_BaseColor = lerp(Set_BaseColor, overridingColor.xyz, maskEnabled);
Set_BaseColor *= _BaseColorVisible;
float Set_BaseColorAlpha = _BaseColorVisible;
#endif //#ifdef UTS_LAYER_VISIBILITY //v.2.0.5
float4 _1st_ShadeMap_var = lerp(SAMPLE_TEXTURE2D_LOD(_1st_ShadeMap, sampler_MainTex, TRANSFORM_TEX(Set_UV0, _1st_ShadeMap),0.0f), _MainTex_var, _Use_BaseAs1st);
float3 Set_1st_ShadeColor = lerp((_1st_ShadeColor.rgb * _1st_ShadeMap_var.rgb * _LightIntensity), ((_1st_ShadeColor.rgb * _1st_ShadeMap_var.rgb) * Set_LightColor), _Is_LightColor_1st_Shade);
#ifdef UTS_LAYER_VISIBILITY
{
float4 overridingColor = lerp(_FirstShadeMaskColor, float4(_FirstShadeMaskColor.w, _FirstShadeMaskColor.w, _FirstShadeMaskColor.w, 1.0f), _ComposerMaskMode);
float maskEnabled = max(_FirstShadeOverridden, _ComposerMaskMode);
Set_1st_ShadeColor = lerp(Set_1st_ShadeColor, overridingColor.xyz, maskEnabled);
Set_1st_ShadeColor = lerp(Set_1st_ShadeColor, Set_BaseColor, 1.0f - _FirstShadeVisible);
}
float Set_1st_ShadeAlpha = _FirstShadeVisible;
#endif //#ifdef UTS_LAYER_VISIBILITY //v.2.0.5
float4 _2nd_ShadeMap_var = lerp(SAMPLE_TEXTURE2D_LOD(_2nd_ShadeMap, sampler_MainTex, TRANSFORM_TEX(Set_UV0, _2nd_ShadeMap), 0.0), _1st_ShadeMap_var, _Use_1stAs2nd);
float3 Set_2nd_ShadeColor = lerp((_2nd_ShadeColor.rgb * _2nd_ShadeMap_var.rgb * _LightIntensity), ((_2nd_ShadeColor.rgb * _2nd_ShadeMap_var.rgb) * Set_LightColor), _Is_LightColor_2nd_Shade);
float _HalfLambert_var = 0.5 * dot(lerp(i_normalDir, normalDirection, _Is_NormalMapToBase), lightDirection) + 0.5;
float4 _Set_2nd_ShadePosition_var = tex2Dlod(_Set_2nd_ShadePosition, float4(TRANSFORM_TEX(Set_UV0, _Set_2nd_ShadePosition),0.0f,0.0f));
float4 _Set_1st_ShadePosition_var = tex2Dlod(_Set_1st_ShadePosition, float4(TRANSFORM_TEX(Set_UV0, _Set_1st_ShadePosition),0.0f, 0.0f));
//v.2.0.5:
float _1stColorFeatherForMask = lerp(_BaseShade_Feather, 0.0f, max(_FirstShadeOverridden, _ComposerMaskMode));
float _2ndColorFeatherForMask = lerp(_1st2nd_Shades_Feather, 0.0f, max(_SecondShadeOverridden, _ComposerMaskMode));
float Set_FinalShadowMask = saturate((1.0 + ((lerp(_HalfLambert_var, (_HalfLambert_var * saturate(1.0 + _Tweak_SystemShadowsLevel)), _Set_SystemShadowsToBase) - (_BaseColor_Step - _1stColorFeatherForMask)) * ((1.0 - _Set_1st_ShadePosition_var.rgb).r - 1.0)) / (_BaseColor_Step - (_BaseColor_Step - _1stColorFeatherForMask))));
//Composition: 3 Basic Colors as finalColor
#ifdef UTS_LAYER_VISIBILITY
{
float4 overridingColor = lerp(_SecondShadeMaskColor, float4(_SecondShadeMaskColor.w, _SecondShadeMaskColor.w, _SecondShadeMaskColor.w, 1.0f), _ComposerMaskMode);
float maskEnabled = max(_SecondShadeOverridden, _ComposerMaskMode);
Set_2nd_ShadeColor = lerp(Set_2nd_ShadeColor, overridingColor.xyz, maskEnabled);
Set_2nd_ShadeColor = lerp(Set_2nd_ShadeColor, Set_BaseColor, 1.0f - _SecondShadeVisible);
}
#endif //#ifdef UTS_LAYER_VISIBILITY
float3 finalColor = lerp(Set_BaseColor, lerp(Set_1st_ShadeColor, Set_2nd_ShadeColor, saturate((1.0 + ((_HalfLambert_var - (_ShadeColor_Step - _2ndColorFeatherForMask)) * ((1.0 - _Set_2nd_ShadePosition_var.rgb).r - 1.0)) / (_ShadeColor_Step - (_ShadeColor_Step - _2ndColorFeatherForMask))))), Set_FinalShadowMask); // Final Color
#ifdef UTS_LAYER_VISIBILITY
float Set_2nd_ShadeAlpha = _SecondShadeVisible;
channelOutAlpha = lerp(Set_BaseColorAlpha, lerp(Set_1st_ShadeAlpha, Set_2nd_ShadeAlpha, saturate((1.0 + ((_HalfLambert_var - (_ShadeColor_Step - _2ndColorFeatherForMask)) * ((1.0 - _Set_2nd_ShadePosition_var.rgb).r - 1.0)) / (_ShadeColor_Step - (_ShadeColor_Step - _2ndColorFeatherForMask))))), Set_FinalShadowMask);
#endif
//v.2.0.6: Add HighColor if _Is_Filter_HiCutPointLightColor is False
float4 _Set_HighColorMask_var = tex2Dlod(_Set_HighColorMask, float4(TRANSFORM_TEX(Set_UV0, _Set_HighColorMask),0.0f,0.0f));
float _Specular_var = 0.5 * dot(halfDirection, lerp(i_normalDir, normalDirection, _Is_NormalMapToHighColor)) + 0.5; // Specular
float _TweakHighColorMask_var = (saturate((_Set_HighColorMask_var.g + _Tweak_HighColorMaskLevel)) * lerp((1.0 - step(_Specular_var, (1.0 - pow(abs(_HighColor_Power), 5)))), pow(abs(_Specular_var), exp2(lerp(11, 1, _HighColor_Power))), _Is_SpecularToHighColor));
float4 _HighColor_Tex_var = tex2Dlod(_HighColor_Tex, float4( TRANSFORM_TEX(Set_UV0, _HighColor_Tex),0.0f,0.0f));
float3 _HighColor_var = lerp((_HighColor_Tex_var.rgb * _HighColor.rgb), ((_HighColor_Tex_var.rgb * _HighColor.rgb) * Set_LightColor), _Is_LightColor_HighColor);
#ifdef UTS_LAYER_VISIBILITY
{
float4 overridingColor = lerp(_HighlightMaskColor, float4(_HighlightMaskColor.w, _HighlightMaskColor.w, _HighlightMaskColor.w, 1.0f), _ComposerMaskMode);
float maskEnabled = max(_HighlightOverridden, _ComposerMaskMode);
_HighColor_var *= _TweakHighColorMask_var;
_HighColor_var *= _HighlightVisible;
finalColor =
lerp(saturate(finalColor - _TweakHighColorMask_var), finalColor,
lerp(_Is_BlendAddToHiColor, 1.0
, _Is_SpecularToHighColor));
float3 addColor =
lerp(_HighColor_var, (_HighColor_var * ((1.0 - Set_FinalShadowMask) + (Set_FinalShadowMask * _TweakHighColorOnShadow)))
, _Is_UseTweakHighColorOnShadow);
finalColor += addColor;
if (any(addColor))
{
finalColor = lerp(finalColor, overridingColor.xyz, maskEnabled);
channelOutAlpha = _HighlightVisible;
}
}
#else
_HighColor_var *= _TweakHighColorMask_var;
finalColor = finalColor + lerp(lerp(_HighColor_var, (_HighColor_var * ((1.0 - Set_FinalShadowMask) + (Set_FinalShadowMask * _TweakHighColorOnShadow))), _Is_UseTweakHighColorOnShadow), float3(0, 0, 0), _Is_Filter_HiCutPointLightColor);
#endif //#ifdef UTS_LAYER_VISIBILITY
//
finalColor = SATURATE_IF_SDR(finalColor);
// pointLightColor += finalColor;
return finalColor;
}

View File

@@ -1,237 +0,0 @@
// _preIntegratedFGD and _CubemapLD are unique for each BRDF
IndirectLighting EvaluateBSDF_Env(LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, EnvLightData lightData, BSDFData bsdfData,
int influenceShapeType,
inout float hierarchyWeight)
{
IndirectLighting lighting;
ZERO_INITIALIZE(IndirectLighting, lighting);
float3 envLighting;
float weight = 1.0;
float3 R = reflect(-V, bsdfData.normalWS);
EvaluateLight_EnvIntersection(posInput.positionWS, bsdfData.normalWS, lightData, influenceShapeType, R, weight);
// 31 bit index, 1 bit cache type
uint cacheType = IsEnvIndexCubemap(lightData.envIndex) ? ENVCACHETYPE_CUBEMAP : ENVCACHETYPE_TEXTURE2D;
// Index start at 1, because -0 == 0, so we can't known which cache to sample for that index. Thus it is invalid.
int index = abs(lightData.envIndex) - 1;
float lod = PerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness) * lightData.roughReflections;
float2 atlasCoords = GetReflectionAtlasCoordsCube(CUBE_SCALE_OFFSET[index], R, lod);
// No distance based roughness for simple lit
float4 preLD = SampleEnv(lightLoopContext, lightData.envIndex, R, PerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness) * lightData.roughReflections, lightData.rangeCompressionFactorCompensation, posInput.positionNDC);
weight *= preLD.a; // Used by planar reflection to discard pixel
//envLighting = F_Schlick(bsdfData.fresnel0, dot(bsdfData.normalWS, V)) * preLD.rgb;
envLighting = preLD.rgb;
UpdateLightingHierarchyWeights(hierarchyWeight, weight);
envLighting *= weight * lightData.multiplier;
lighting.specularReflected = envLighting;
return lighting;
}
float4 ComputeReflection(LightLoopContext context, PositionInputs posInput, PreLightData preLightData, BuiltinData builtinData, float3 V, float lod, BSDFData bsdfData)
{
float3 refcolor = 0;
float reflectionHierarchyWeight = 0.0; // Max: 1.0
uint envLightStart, envLightCount;
// Fetch first env light to provide the scene proxy for screen space computation
#ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER
GetCountAndStart(posInput, LIGHTCATEGORY_ENV, envLightStart, envLightCount);
#else // LIGHTLOOP_DISABLE_TILE_AND_CLUSTER
envLightCount = _EnvLightCount;
envLightStart = 0;
#endif
bool fastPath = false;
#if SCALARIZE_LIGHT_LOOP
uint envStartFirstLane;
fastPath = IsFastPath(envLightStart, envStartFirstLane);
#endif
context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES;
#if SCALARIZE_LIGHT_LOOP
if (fastPath)
{
envLightStart = envStartFirstLane;
}
#endif
// Scalarized loop, same rationale of the punctual light version
uint v_envLightListOffset = 0;
uint v_envLightIdx = envLightStart;
#if NEED_TO_CHECK_HELPER_LANE
// On some platform helper lanes don't behave as we'd expect, therefore we prevent them from entering the loop altogether.
// IMPORTANT! This has implications if ddx/ddy is used on results derived from lighting, however given Lightloop is called in compute we should be
// sure it will not happen.
bool isHelperLane = WaveIsHelperLane();
while (!isHelperLane && v_envLightListOffset < envLightCount)
#else
while (v_envLightListOffset < envLightCount)
#endif
{
v_envLightIdx = FetchIndex(envLightStart, v_envLightListOffset);
#if SCALARIZE_LIGHT_LOOP
uint s_envLightIdx = ScalarizeElementIndex(v_envLightIdx, fastPath);
#else
uint s_envLightIdx = v_envLightIdx;
#endif
if (s_envLightIdx == -1)
break;
EnvLightData s_envLightData = FetchEnvLight(s_envLightIdx); // Scalar load.
// If current scalar and vector light index match, we process the light. The v_envLightListOffset for current thread is increased.
// Note that the following should really be ==, however, since helper lanes are not considered by WaveActiveMin, such helper lanes could
// end up with a unique v_envLightIdx value that is smaller than s_envLightIdx hence being stuck in a loop. All the active lanes will not have this problem.
if (s_envLightIdx >= v_envLightIdx)
{
v_envLightListOffset++;
if (reflectionHierarchyWeight < 1.0)
{
if (IsMatchingLightLayer(s_envLightData.lightLayers, builtinData.renderingLayers))
{
IndirectLighting lighting = EvaluateBSDF_Env(context, V, posInput, preLightData, s_envLightData, bsdfData, s_envLightData.influenceShapeType, reflectionHierarchyWeight);
#if defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2)
float3 lightInReflDir = float3(-1, -1, -1);
if (s_envLightData.normalizeWithAPV > 0 && all(lightInReflDir >= 0))
{
float factor = GetReflectionProbeNormalizationFactor(lightInReflDir, bsdfData.normalWS, s_envLightData.L0L1, s_envLightData.L2_1, s_envLightData.L2_2);
lighting.specularReflected *= factor;
}
#endif
refcolor += lighting.specularReflected;
}
}
}
}
return float4(refcolor.r, refcolor.g, refcolor.b, reflectionHierarchyWeight);
}
float3 ComputeFresnelLerp(float3 c0, float3 c1, float cosA)
{
float t = pow(1 - cosA, 5);
return lerp(c0, c1, t);
}
float3 ComputeIndirectDiffuse(PositionInputs posInput, BSDFData bsdfData, float3 V)
{
float3 indirectDiffuse = 0.0;
if(_ID_Intensity > 0)
{
#ifdef _PBR_Mode_ANISO
GetGGXAnisotropicModifiedNormalAndRoughness(bsdfData.bitangentWS, bsdfData.tangentWS , bsdfData.normalWS, V, bsdfData.anisotropy, bsdfData.perceptualRoughness, bsdfData.normalWS, bsdfData.perceptualRoughness);
#endif
float NdotV = saturate(dot(bsdfData.normalWS, V));
#if defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2)
BuiltinData apvBuiltinData;
ZERO_INITIALIZE(BuiltinData, apvBuiltinData);
#if defined(_PBR_Mode_OFF) || defined(_PBR_Mode_TOON)
EvaluateAdaptiveProbeVolume(GetAbsolutePositionWS(posInput.positionWS), 0.0, 0.0, V, posInput.positionSS, apvBuiltinData.bakeDiffuseLighting, apvBuiltinData.backBakeDiffuseLighting);
#else
EvaluateAdaptiveProbeVolume(GetAbsolutePositionWS(posInput.positionWS), bsdfData.normalWS, -bsdfData.normalWS, V, posInput.positionSS, apvBuiltinData.bakeDiffuseLighting, apvBuiltinData.backBakeDiffuseLighting);
#endif
float3 probeDiffuse = apvBuiltinData.bakeDiffuseLighting * GetCurrentExposureMultiplier();
indirectDiffuse = probeDiffuse;
#else
#if defined(_PBR_Mode_OFF) || defined(_PBR_Mode_TOON)
indirectDiffuse = EvaluateAmbientProbe(0.0) * GetCurrentExposureMultiplier();
#else
indirectDiffuse = EvaluateAmbientProbe(bsdfData.normalWS) * GetCurrentExposureMultiplier();
#endif
#endif
//SSGI
if(_ReceivesSSGI == 1)
{
float4 ssgiLighting = LOAD_TEXTURE2D_X(_IndirectDiffuseTexture, posInput.positionSS);
ssgiLighting *= _GIMultiplier;
indirectDiffuse = lerp(indirectDiffuse, ssgiLighting.rgb, ssgiLighting.a);
}
//Compelete the indirect lighting
indirectDiffuse = indirectDiffuse * bsdfData.diffuseColor.rgb * _BaseColor.rgb;
//SSAO
if(_ReceivesSSAO == 1)
{
AmbientOcclusionFactor aoFactor;
GetScreenSpaceAmbientOcclusionMultibounce(posInput.positionSS, NdotV, bsdfData.perceptualRoughness, bsdfData.ambientOcclusion, bsdfData.specularOcclusion, bsdfData.diffuseColor, bsdfData.fresnel0, aoFactor);
indirectDiffuse *= lerp(_AOMin, 1, aoFactor.indirectAmbientOcclusion);
}
indirectDiffuse = indirectDiffuse * bsdfData.ambientOcclusion;
}
return indirectDiffuse;
}
float3 ComputeIndirectSpecular(LightLoopContext lightLoopContext, PositionInputs posInput, PreLightData preLightData, BSDFData bsdfData, SurfaceData surfaceData, BuiltinData builtinData, float3 V)
{
#if defined(_PBR_Mode_OFF) || defined(_PBR_Mode_TOON)
return 0;
#else
float3 indirectSpecular = 0;
if(_IR_Intensity > 0)
{
#ifdef _PBR_Mode_ANISO
GetGGXAnisotropicModifiedNormalAndRoughness(bsdfData.bitangentWS, bsdfData.tangentWS , bsdfData.normalWS, V, bsdfData.anisotropy, bsdfData.perceptualRoughness, bsdfData.normalWS, bsdfData.perceptualRoughness);
#endif
float3 albedo = _BaseColor.rgb * surfaceData.baseColor;
float mip = PerceptualRoughnessToMipmapLevel(bsdfData.perceptualRoughness);
float NdotV = saturate(dot(bsdfData.normalWS, V));
indirectSpecular = SampleSkyTexture(reflect(-V, bsdfData.normalWS), mip, 0).rgb;
float3 specColor = lerp(ColorSpaceDielectricSpec.rgb, albedo, surfaceData.metallic);
float oneMinusReflectivity = ColorSpaceDielectricSpec.a * (1 - surfaceData.metallic);
float grazingTerm = saturate((1 - bsdfData.perceptualRoughness) + (1 - oneMinusReflectivity));
//Reflection Probe
float4 refProbe = ComputeReflection(lightLoopContext, posInput, preLightData, builtinData, V, mip, bsdfData);
indirectSpecular = lerp(indirectSpecular, refProbe.rgb, refProbe.a);
//SSR
if(_ReceivesSSR == 1)
{
float4 ssrLighting = LOAD_TEXTURE2D_X(_SsrLightingTexture, posInput.positionSS);
InversePreExposeSsrLighting(ssrLighting);
ApplyScreenSpaceReflectionWeight(ssrLighting);
indirectSpecular = lerp(indirectSpecular, ssrLighting.rgb, ssrLighting.a);
}
//Compelete the indirect lighting
indirectSpecular = indirectSpecular * ComputeFresnelLerp(specColor, grazingTerm, NdotV) * GetCurrentExposureMultiplier();
// Occlusion
if(_ReceivesSSAO == 1)
{
AmbientOcclusionFactor aoFactor;
GetScreenSpaceAmbientOcclusionMultibounce(posInput.positionSS, NdotV, bsdfData.perceptualRoughness, bsdfData.ambientOcclusion, bsdfData.specularOcclusion, bsdfData.diffuseColor, bsdfData.fresnel0, aoFactor);
indirectSpecular *= lerp(_AOMin, 1, aoFactor.indirectSpecularOcclusion);
}
indirectSpecular = indirectSpecular * bsdfData.specularOcclusion;
}
return indirectSpecular;
#endif
}

View File

@@ -1,23 +0,0 @@
float StepAntiAliasing(float x, float y)
{
float v = x - y;
return saturate(v / (fwidth(v)+HALF_MIN));//fwidth(x) = abs(ddx(x) + ddy(x))
}
float Remap(float In, float2 InMinMax, float2 OutMinMax)
{
return OutMinMax.x + (In - InMinMax.x) * (OutMinMax.y - OutMinMax.x) / (InMinMax.y - InMinMax.x);
}
float3 ToonMaping(float3 x)
{
x = x * (2.51 * x + 0.03) / (x * (2.43 * x + 0.59) + 0.14);
return x;
}
float3 GetSmoothedWorldNormal(float2 uv, float3x3 t_tbn)
{
float3 normal = float3(uv, 0);
normal.z = sqrt(1.0 - saturate(dot(normal.xy, normal.xy)));
return mul(normal, t_tbn);
}

View File

@@ -1,352 +0,0 @@
//Unity Toon Shader/HDRP
//nobuyuki@unity3d.com
//toshiyuki@unity3d.com (Universal RP/HDRP)
#ifndef UCTS_HDRP_INCLUDED
#define UCTS_HDRP_INCLUDED
#define UCTS_HDRP 1
#define UTS_LAYER_VISIBILITY
#ifndef DIRECTIONAL
# define DIRECTIONAL
#endif
#define FP_BUFFER 1
#if FP_BUFFER
#define SATURATE_IF_SDR(x) (x)
#define SATURATE_BASE_COLOR_IF_SDR(x) (x)
#else
#define SATURATE_IF_SDR(x) saturate(x)
#define SATURATE_BASE_COLOR_IF_SDR(x) saturate(x)
#endif
struct UTSData
{
float3 viewDirection;
float3 normalDirection;
fixed cameraDir;
float cameraRoll;
fixed signMirror;
};
//#define UTSDATA_ZERO_INITIALIZE (UTSData)
struct UTSLightData
{
float3 lightDirection;
float3 lightColor;
float diffuseDimmer;
float specularDimmer;
float3 shadowTint;
float penumbraTint;
float shadowValue;
};
struct UTSAggregateLighting
{
float3 directDiffuse;
float3 directSpecular;
float3 indirectDiffuse;
float3 indirectSpecular;
};
float3 AccumulateAggregateLighting(UTSAggregateLighting aggregateLighting)
{
return SATURATE_IF_SDR(aggregateLighting.directDiffuse + aggregateLighting.directSpecular) + aggregateLighting.indirectDiffuse + aggregateLighting.indirectSpecular;
}
#if defined(UNITY_PASS_PREPASSBASE) || defined(UNITY_PASS_DEFERRED) || defined(UNITY_PASS_SHADOWCASTER)
#undef FOG_LINEAR
#undef FOG_EXP
#undef FOG_EXP2
#endif
#if 1
// Legacy for compatibility with existing shaders
inline bool IsGammaSpace()
{
#ifdef UNITY_COLORSPACE_GAMMA
return true;
#else
return false;
#endif
}
// normal should be normalized, w=1.0
half3 SHEvalLinearL0L1(half4 normal)
{
half3 x;
// Linear (L1) + constant (L0) polynomial terms
x.r = dot(unity_SHAr, normal);
x.g = dot(unity_SHAg, normal);
x.b = dot(unity_SHAb, normal);
return x;
}
// normal should be normalized, w=1.0
half3 SHEvalLinearL2(half4 normal)
{
half3 x1, x2;
// 4 of the quadratic (L2) polynomials
half4 vB = normal.xyzz * normal.yzzx;
x1.r = dot(unity_SHBr, vB);
x1.g = dot(unity_SHBg, vB);
x1.b = dot(unity_SHBb, vB);
// Final (5th) quadratic (L2) polynomial
half vC = normal.x * normal.x - normal.y * normal.y;
x2 = unity_SHC.rgb * vC;
return x1 + x2;
}
// normal should be normalized, w=1.0
// output in active color space
half3 ShadeSH9(half4 normal)
{
// Linear + constant polynomial terms
half3 res = SHEvalLinearL0L1(normal);
// Quadratic polynomials
res += SHEvalLinearL2(normal);
# ifdef UNITY_COLORSPACE_GAMMA
res = LinearToGammaSpace(res);
# endif
return res;
}
float3 DecodeLightProbe(float3 N) {
return ShadeSH9(float4(N, 1));
}
inline float GammaToLinearSpaceExact(float value)
{
if (value <= 0.04045F)
return value / 12.92F;
else if (value < 1.0F)
return pow((value + 0.055F) / 1.055F, 2.4F);
else
return pow(value, 2.2F);
}
inline float3 GammaToLinearSpace(float3 sRGB)
{
// Approximate version from http://chilliant.blogspot.com.au/2012/08/srgb-approximations-for-hlsl.html?m=1
return sRGB * (sRGB * (sRGB * 0.305306011h + 0.682171111h) + 0.012522878h);
// Precise version, useful for debugging.
//return half3(GammaToLinearSpaceExact(sRGB.r), GammaToLinearSpaceExact(sRGB.g), GammaToLinearSpaceExact(sRGB.b));
}
inline float LinearToGammaSpaceExact(float value)
{
if (value <= 0.0F)
return 0.0F;
else if (value <= 0.0031308F)
return 12.92F * value;
else if (value < 1.0F)
return 1.055F * pow(value, 0.4166667F) - 0.055F;
else
return pow(value, 0.45454545F);
}
inline float3 LinearToGammaSpace(float3 linRGB)
{
linRGB = max(linRGB, float3(0.h, 0.h, 0.h));
// An almost-perfect approximation from http://chilliant.blogspot.com.au/2012/08/srgb-approximations-for-hlsl.html?m=1
return max(1.055h * pow(linRGB, 0.416666667h) - 0.055h, 0.h);
// Exact version, useful for debugging.
//return half3(LinearToGammaSpaceExact(linRGB.r), LinearToGammaSpaceExact(linRGB.g), LinearToGammaSpaceExact(linRGB.b));
}
#if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)
#define UNITY_FOG_COORDS(idx) UNITY_FOG_COORDS_PACKED(idx, float1)
#if (SHADER_TARGET < 30) || defined(SHADER_API_MOBILE)
// mobile or SM2.0: calculate fog factor per-vertex
#define UNITY_TRANSFER_FOG(o,outpos) UNITY_CALC_FOG_FACTOR((outpos).z); o.fogCoord.x = unityFogFactor
#else
// SM3.0 and PC/console: calculate fog distance per-vertex, and fog factor per-pixel
#define UNITY_TRANSFER_FOG(o,outpos) o.fogCoord.x = (outpos).z
#endif
#else
#define UNITY_FOG_COORDS(idx)
#define UNITY_TRANSFER_FOG(o,outpos)
#endif
#define UNITY_FOG_LERP_COLOR(col,fogCol,fogFac) col.rgb = lerp((fogCol).rgb, (col).rgb, saturate(fogFac))
#if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)
#if (SHADER_TARGET < 30) || defined(SHADER_API_MOBILE)
// mobile or SM2.0: fog factor was already calculated per-vertex, so just lerp the color
#define UNITY_APPLY_FOG_COLOR(coord,col,fogCol) UNITY_FOG_LERP_COLOR(col,fogCol,(coord).x)
#else
// SM3.0 and PC/console: calculate fog factor and lerp fog color
#define UNITY_APPLY_FOG_COLOR(coord,col,fogCol) UNITY_CALC_FOG_FACTOR((coord).x); UNITY_FOG_LERP_COLOR(col,fogCol,unityFogFactor)
#endif
#else
#define UNITY_APPLY_FOG_COLOR(coord,col,fogCol)
#endif
#ifdef UNITY_PASS_FORWARDADD
#define UNITY_APPLY_FOG(coord,col) UNITY_APPLY_FOG_COLOR(coord,col,fixed4(0,0,0,0))
#else
#define UNITY_APPLY_FOG(coord,col) UNITY_APPLY_FOG_COLOR(coord,col,unity_FogColor)
#endif
#endif //#if false
#ifdef DIRECTIONAL
#define LIGHTING_COORDS(idx1,idx2) SHADOW_COORDS(idx1)
#define TRANSFER_VERTEX_TO_FRAGMENT(a) TRANSFER_SHADOW(a)
#define LIGHT_ATTENUATION(a) SHADOW_ATTENUATION(a)
#endif
// Transforms 2D UV by scale/bias property
//#define TRANSFORM_TEX(tex,name) (tex.xy * name##_ST.xy + name##_ST.zw)
#define UCTS_TEXTURE2D(tex,name) SAMPLE_TEXTURE2D(tex,sampler##tex,TRANSFORM_TEX(name, tex));
inline float4 UnityObjectToClipPosInstanced(in float3 pos)
{
// return mul(UNITY_MATRIX_VP, mul(unity_ObjectToWorldArray[unity_InstanceID], float4(pos, 1.0)));
// todo. right?
return mul(UNITY_MATRIX_VP, mul(UNITY_MATRIX_M, float4(pos, 1.0)));
}
inline float4 UnityObjectToClipPosInstanced(float4 pos)
{
return UnityObjectToClipPosInstanced(pos.xyz);
}
#define UnityObjectToClipPos UnityObjectToClipPosInstanced
inline float3 UnityObjectToWorldNormal( in float3 norm )
{
#ifdef UNITY_ASSUME_UNIFORM_SCALING
return UnityObjectToWorldDir(norm);
#else
// mul(IT_M, norm) => mul(norm, I_M) => {dot(norm, I_M.col0), dot(norm, I_M.col1), dot(norm, I_M.col2)}
return normalize(mul(norm, (float3x3)UNITY_MATRIX_M));
#endif
}
// normal should be normalized, w=1.0
float3 SHEvalLinearL0L1 (float4 normal)
{
float3 x;
// Linear (L1) + constant (L0) polynomial terms
x.r = dot(unity_SHAr,normal);
x.g = dot(unity_SHAg,normal);
x.b = dot(unity_SHAb,normal);
return x;
}
// normal should be normalized, w=1.0
float3 SHEvalLinearL2 (float4 normal)
{
float3 x1, x2;
// 4 of the quadratic (L2) polynomials
float4 vB = normal.xyzz * normal.yzzx;
x1.r = dot(unity_SHBr,vB);
x1.g = dot(unity_SHBg,vB);
x1.b = dot(unity_SHBb,vB);
// Final (5th) quadratic (L2) polynomial
half vC = normal.x*normal.x - normal.y*normal.y;
x2 = unity_SHC.rgb * vC;
return x1 + x2;
}
// normal should be normalized, w=1.0
// output in active color space
float3 ShadeSH9 (float4 normal)
{
// Linear + constant polynomial terms
float3 res = SHEvalLinearL0L1 (normal);
// Quadratic polynomials
res += SHEvalLinearL2 (normal);
# ifdef UNITY_COLORSPACE_GAMMA
res = LinearToGammaSpace (res);
# endif
return res;
}
float rateR = 0.299;
float rateG = 0.587;
float rateB = 0.114;
float3 SampleBakedGI_UTS(float3 positionRWS, float3 normalWS, float2 uvStaticLightmap, float2 uvDynamicLightmap, bool needToIncludeAPV = false)
{
float3 bakeDiffuseLighting = float3(0, 0, 0);
float3 backBakeDiffuseLighting = float3(0, 0, 0);
float3 backNormalWS = float3(0, 0, 0);
#if !defined(_SURFACE_TYPE_TRANSPARENT) && (SHADERPASS != SHADERPASS_RAYTRACING_INDIRECT) && (SHADERPASS != SHADERPASS_RAYTRACING_GBUFFER)
if (_IndirectDiffuseMode != INDIRECTDIFFUSEMODE_OFF
#if (SHADERPASS == SHADERPASS_GBUFER)
&& _IndirectDiffuseMode != INDIRECTDIFFUSEMODE_MIXED && _ReflectionsMode != REFLECTIONSMODE_MIXED
#endif
)
return bakeDiffuseLighting;
#endif
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
EvaluateLightmap(positionRWS, normalWS, backNormalWS, uvStaticLightmap, uvDynamicLightmap, bakeDiffuseLighting, backBakeDiffuseLighting);
#elif (defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2))
if (needToIncludeAPV)
{
EvaluateAdaptiveProbeVolume(GetAbsolutePositionWS(positionRWS), normalWS, backNormalWS, GetWorldSpaceNormalizeViewDir(positionRWS), 0.0, bakeDiffuseLighting, backBakeDiffuseLighting);
}
#else
EvaluateLightProbeBuiltin(positionRWS, normalWS, backNormalWS, bakeDiffuseLighting, backBakeDiffuseLighting);
#if defined(SHADER_STAGE_RAY_TRACING)
bakeDiffuseLighting *= _RayTracingAmbientProbeDimmer;
backBakeDiffuseLighting *= _RayTracingAmbientProbeDimmer;
#endif
#endif
return bakeDiffuseLighting;
}
float3 SampleBakedGI_UTS_OutLine(float3 positionRWS, float3 normalWS, float2 uvStaticLightmap, float2 uvDynamicLightmap)
{
float3 bakeDiffuseLighting = float3(0, 0, 0);
float3 backBakeDiffuseLighting = float3(0, 0, 0);
float3 backNormalWS = float3(0, 0, 0);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
EvaluateLightmap(positionRWS, normalWS, backNormalWS, uvStaticLightmap, uvDynamicLightmap, bakeDiffuseLighting, backBakeDiffuseLighting);
#elif (defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2))
EvaluateAdaptiveProbeVolume(GetAbsolutePositionWS(positionRWS), normalWS, backNormalWS, GetWorldSpaceNormalizeViewDir(positionRWS), 0.0, bakeDiffuseLighting, backBakeDiffuseLighting);
#else
EvaluateLightProbeBuiltin(positionRWS, normalWS, backNormalWS, bakeDiffuseLighting, backBakeDiffuseLighting);
#if defined(SHADER_STAGE_RAY_TRACING)
bakeDiffuseLighting *= _RayTracingAmbientProbeDimmer;
backBakeDiffuseLighting *= _RayTracingAmbientProbeDimmer;
#endif
#endif
return bakeDiffuseLighting;
}
#endif //#ifndef UCTS_HDRP_INCLUDED

View File

@@ -1,65 +0,0 @@
//Unity Toon Shader/HDRP
//nobuyuki@unity3d.com
//toshiyuki@unity3d.com (Universal RP/HDRP)
#if 1
float4 objPos = mul(unity_ObjectToWorld, float4(0, 0, 0, 1));
float2 Set_UV0 = inputMesh.uv0;
float4 _Outline_Sampler_var = tex2Dlod(_Outline_Sampler, float4(TRANSFORM_TEX(Set_UV0, _Outline_Sampler), 0.0, 0));
//v.2.0.4.3 baked Normal Texture for Outline
float3 normalDir = UnityObjectToWorldNormal(inputMesh.normalOS);
float3 tangentDir = normalize(mul(unity_ObjectToWorld, float4(inputMesh.tangentOS.xyz, 0.0)).xyz);
float3 bitangentDir = normalize(cross(normalDir, tangentDir) * inputMesh.tangentOS.w);
float3x3 tangentTransform = float3x3(tangentDir, bitangentDir, normalDir);
//UnpackNormal() can't be used, and so as follows. Do not specify a bump for the texture to be used.
float4 _BakedNormal_var = (tex2Dlod(_BakedNormal, float4(TRANSFORM_TEX(Set_UV0, _BakedNormal), 0.0, 0)) * 2 - 1);
float3 _BakedNormalDir = normalize(mul(_BakedNormal_var.rgb, tangentTransform));
//end
float Set_Outline_Width = (_Outline_Width * 0.01 * smoothstep(_Farthest_Distance, _Nearest_Distance, distance(objPos.rgb, _WorldSpaceCameraPos)) * _Outline_Sampler_var.rgb).r;
Set_Outline_Width *= (1.0f - _ZOverDrawMode);
//v.2.0.7.5
float4 _ClipCameraPos = mul(UNITY_MATRIX_VP, float4(_WorldSpaceCameraPos.xyz, 1));
//v.2.0.7
#if defined(UNITY_REVERSED_Z)
//v.2.0.4.2 (DX)
_Offset_Z = _Offset_Z * -0.01;
#else
//OpenGL
_Offset_Z = _Offset_Z * 0.01;
#endif
float3 FinalNormal;
if(_UseSmoothedNormal == 1)
{
float3 normal = float3(inputMesh.uv1, 0);
normal.z = sqrt(1.0 - saturate(dot(normal.xy, normal.xy)));
FinalNormal = mul(normal, tangentTransform);
}
else
{
FinalNormal = lerp(inputMesh.normalOS, _BakedNormalDir, _Is_BakedNormal);
}
//v2.0.4
#ifdef _OUTLINE_NML
//v.2.0.4.3 baked Normal Texture for Outline
float3 normal = mul((float3x3)transpose(mul(UNITY_MATRIX_I_M, UNITY_MATRIX_I_V)), FinalNormal);
#elif _OUTLINE_POS
Set_Outline_Width = Set_Outline_Width * 2;
float signVar = dot(normalize(inputMesh.positionOS), normalize(inputMesh.normalOS)) < 0 ? -1 : 1;
float3 normal = mul((float3x3)transpose(mul(UNITY_MATRIX_I_M, UNITY_MATRIX_I_V)), signVar * normalize(inputMesh.positionOS));
#endif
// screen space width
float2 extendDir = normalize(TransformWViewToHClip(normal).xy);
float4 clipPos = UnityObjectToClipPos(inputMesh.positionOS);
clipPos.xy += extendDir * min(_Outline_MaxWidth, (clipPos.w * Set_Outline_Width));
clipPos.z = clipPos.z + _Offset_Z * _ClipCameraPos.z;
float4 rws = mul(UNITY_MATRIX_I_P, clipPos); // use UNITY_MATRIX_I_P instead of unity_CameraInvProjection.
rws = mul(UNITY_MATRIX_I_V, rws); // use UNITY_MATRIX_I_V instead of unity_cameraToWorld.
#ifndef TESSELLATION_ON
varyingsType.vmesh.positionCS = clipPos;
#endif // TESSELLATION_ON
varyingsType.vmesh.positionRWS = rws.xyz;
#endif // #if 1

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 6499b7b5ccaae6944ae5fe89b016c50b
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,189 +0,0 @@
#define ColorSpaceDielectricSpec half4(0.22, 0.22, 0.22, 0.779)
float3 schlick(float f0, float hl) {
real x = 1.0 - hl;
real x2 = x * x;
real x5 = x * x2 * x2;
return (1.0 - f0) * x5 + f0;
}
float3 SpecularColor(float3 albedo, float metalic)
{
float3 specColor = lerp(ColorSpaceDielectricSpec.rgb, albedo, metalic);
return specColor;
}
float RoughnessToBlinnPhongSpecularExponent(float roughness)
{
return clamp(2 * rcp(roughness * roughness) - 2, FLT_EPS, rcp(FLT_EPS));
}
float StepFeatherToon(float value,float step,float feather)
{
return saturate((value - step + feather) / feather);
}
float3 ComputeSpecularTerm(float3 V, float3 L, BSDFData bsdfData)
{
float3 specTerm;
#ifdef _PBR_Mode_OFF
return 0;
#else
float3 N = bsdfData.normalWS;
float3 H = normalize(L + V);
float NdotL = dot(N, L);
float NdotV = dot(N, V);
float clampedNdotV = ClampNdotV(NdotV);
float clampedNdotL = saturate(NdotL);
float flippedNdotL = ComputeWrappedDiffuseLighting(-NdotL, TRANSMISSION_WRAP_LIGHT);
float diffuseNdotL = clampedNdotL;
float LdotV = dot(L, V);
float NdotH = saturate(dot(N, H));
float HdotL = saturate(dot(H, L));
float3 F = schlick(bsdfData.fresnel0.x, HdotL);
float partLambdaV;
float3 DV = 0;
#ifdef _PBR_Mode_ST
ConvertAnisotropyToRoughness(bsdfData.perceptualRoughness, 0, bsdfData.roughnessT, bsdfData.roughnessB);
partLambdaV = GetSmithJointGGXPartLambdaV(clampedNdotV, bsdfData.roughnessT);
// We use abs(NdotL) to handle the none case of double sided
DV = DV_SmithJointGGX(NdotH, abs(NdotL), clampedNdotV, bsdfData.roughnessT, partLambdaV);
#elif _PBR_Mode_ANISO
float TdotV = dot(bsdfData.tangentWS, V);
float BdotV = dot(bsdfData.bitangentWS, V);
ConvertAnisotropyToRoughness(bsdfData.perceptualRoughness, bsdfData.anisotropy, bsdfData.roughnessT, bsdfData.roughnessB);
partLambdaV = GetSmithJointGGXAnisoPartLambdaV(TdotV, BdotV, clampedNdotV, bsdfData.roughnessT, bsdfData.roughnessB);
// For anisotropy we must not saturate these values
float TdotH = dot(bsdfData.tangentWS, H);
float TdotL = dot(bsdfData.tangentWS, L);
float BdotH = dot(bsdfData.bitangentWS, H);
float BdotL = dot(bsdfData.bitangentWS, L);
// We use abs(NdotL) to handle the none case of double sided
DV = DV_SmithJointGGXAniso(TdotH, BdotH, NdotH, clampedNdotV, TdotL, BdotL, abs(NdotL), bsdfData.roughnessT, bsdfData.roughnessB, partLambdaV);
#elif _PBR_Mode_KK
float3 t = ShiftTangent(bsdfData.bitangentWS, N, bsdfData.anisotropy);
float specularExponent = RoughnessToBlinnPhongSpecularExponent(PerceptualRoughnessToRoughness(bsdfData.coatRoughness));
DV = D_KajiyaKay(t, H, specularExponent);
float normalizeSpec = DV * rcp(specularExponent + 2) * 2 * PI;
//DV *= StepFeatherToon(normalizeSpec,specularStep,specularFeather);
DV = DV * normalizeSpec * _KKColor.rgb;
#elif _PBR_Mode_TOON
float specularExponent = RoughnessToBlinnPhongSpecularExponent(PerceptualRoughnessToRoughness(bsdfData.perceptualRoughness));
specTerm = pow(NdotH, 5.0 * specularExponent);
specTerm = StepFeatherToon(specTerm, _ToonSpecularStep, _ToonSpecularFeather);
return specTerm * ColorSpaceDielectricSpec.rgb * clampedNdotL;
#endif
specTerm = DV * F;
specTerm = specTerm * clampedNdotL;
return specTerm;
#endif
}
half3 FitWithCurveApprox(half NdotL, half Curvature)
{
half curva = (1.0 / mad(Curvature, 0.5 - 0.0625, 0.0625) - 2.0) / (16.0 - 2.0);
half oneMinusCurva = 1.0 - curva;
half3 curve0;
{
half3 rangeMin = half3(0.0, 0.3, 0.3);
half3 rangeMax = half3(1.0, 0.7, 0.7);
half3 offset = half3(0.0, 0.06, 0.06);
half3 t = saturate(mad(NdotL, 1.0 / (rangeMax - rangeMin), (offset + rangeMin) / (rangeMin - rangeMax)));
half3 lowerLine = (t * t) * half3(0.65, 0.5, 0.9);
lowerLine.r += 0.045;
lowerLine.b *= t.b;
half3 m = half3(1.75, 2.0, 1.97);
half3 upperLine = mad(NdotL, m, half3(0.99, 0.99, 0.99) - m);
upperLine = saturate(upperLine);
half3 lerpMin = half3(0.0, 0.35, 0.35);
half3 lerpMax = half3(1.0, 0.7, 0.6);
half3 lerpT = saturate(mad(NdotL, 1.0 / (lerpMax - lerpMin), lerpMin / (lerpMin - lerpMax)));
curve0 = lerp(lowerLine, upperLine, lerpT * lerpT);
}
half3 curve1;
{
half3 m = half3(1.95, 2.0, 2.0);
half3 upperLine = mad(NdotL, m, half3(0.99, 0.99, 1.0) - m);
curve1 = saturate(upperLine);
}
float oneMinusCurva2 = oneMinusCurva * oneMinusCurva;
return lerp(curve0, curve1, mad(oneMinusCurva2, -1.0 * oneMinusCurva2, 1.0));
}
// Todo: SDF nose high light
// #if define(_SDFShadow) || define(_SDFNoiseHelight)
#ifdef _SDFShadow
// Use main light XZ direction & world Left/Forward Vector to sample character face SDF
void SDFSample(out float4 lSDF_Tex, out float4 rSDF_Tex, out float2 leftVector, out float2 forwardVector, float2 UV)
{
lSDF_Tex = SAMPLE_TEXTURE2D(_SDFShadowTex, sampler_SDFShadowTex, UV);
float2 right_uv = float2(1 - UV.x, UV.y);
rSDF_Tex = SAMPLE_TEXTURE2D(_SDFShadowTex, sampler_SDFShadowTex, right_uv);
leftVector = normalize(mul(UNITY_MATRIX_M, float4(1, 0, 0, 0)).xz);
forwardVector = normalize(mul(UNITY_MATRIX_M, float4(0, 0, 1, 0)).xz);
}
// Return 1 -> right side
bool SDFPickSide(out float angle, float2 Left, float2 Front, float2 lightDir)
{
// Remap [-1,1] tp [0,1] | 0 <- Face Toward Light ---- Back Toward Light -> 1
angle = 1- clamp(0 , 1, dot(Front, lightDir) * 0.5 + 0.5);
// Pick side
return dot(lightDir,Left) > 0;
}
// Output: readjusted angle between light and pixel facing direction (Represented by a projection length) [Out Param, angle]
// Output: SDF Texel Color [Return Value]
float4 SDFResult(inout bool rightside, out float angle, float3 L, float2 UV)
{
float4 left_SDFTex;
float4 right_SDFTex;
float2 Left;
float2 Front;
SDFSample(left_SDFTex, right_SDFTex, Left, Front, UV);
float2 light_Dir = normalize(L.xz);
rightside = SDFPickSide(angle, Left, Front, light_Dir);
return rightside ? right_SDFTex : left_SDFTex;
}
float SDFMask(float angle, float tex_direct)
{
float smoothGamma = _SDFSmoothGamma / 10.0f;
float shadowLevel = _SDFShadowLevel / 10.0f;
float SDFMask = smoothstep(tex_direct - smoothGamma, tex_direct + smoothGamma, angle - shadowLevel);
return SDFMask;
}
float SDFNoseHighlight(float angle,float tex_value, bool rightside, float2 UV)
{
// REF: https://zhuanlan.zhihu.com/p/411188212 3.2.1
float highlightValue = 0;
//float cutU = step(0.5, UV.x);
float cutU = UV.x;
float uvMask=lerp(cutU, 1 - cutU, rightside);//discard half of the sdf we sampled (Only one side of highlight wanted)
float lightAtten = pow(max(0, angle - (_SDFShadowLevel / 10.0f)), 0.8);
return smoothstep(lightAtten-_SDFNoseHighlightSmoothRange,lightAtten+_SDFNoseHighlightSmoothRange , uvMask * tex_value) * tex_value; // Safeguard, return 0 when tex_value = 0
}
#endif

View File

@@ -1,237 +0,0 @@
#if SHADERPASS != SHADERPASS_FORWARD
#error SHADERPASS_is_not_correctly_define
#endif
#ifdef _WRITE_TRANSPARENT_MOTION_VECTOR
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/MotionVectorVertexShaderCommon.hlsl"
PackedVaryingsType Vert(AttributesMesh inputMesh, AttributesPass inputPass)
{
VaryingsType varyingsType;
varyingsType.vmesh = VertMesh(inputMesh);
return MotionVectorVS(varyingsType, inputMesh, inputPass);
}
#ifdef TESSELLATION_ON
PackedVaryingsToPS VertTesselation(VaryingsToDS input)
{
VaryingsToPS output;
output.vmesh = VertMeshTesselation(input.vmesh);
MotionVectorPositionZBias(output);
output.vpass.positionCS = input.vpass.positionCS;
output.vpass.previousPositionCS = input.vpass.previousPositionCS;
return PackVaryingsToPS(output);
}
#endif // TESSELLATION_ON
#else // _WRITE_TRANSPARENT_MOTION_VECTOR
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/VertMesh.hlsl"
PackedVaryingsType Vert(AttributesMesh inputMesh)
{
VaryingsType varyingsType;
varyingsType.vmesh = VertMesh(inputMesh);
return PackVaryingsType(varyingsType);
}
#ifdef TESSELLATION_ON
PackedVaryingsToPS VertTesselation(VaryingsToDS input)
{
VaryingsToPS output;
output.vmesh = VertMeshTesselation(input.vmesh);
return PackVaryingsToPS(output);
}
#endif // TESSELLATION_ON
#endif // _WRITE_TRANSPARENT_MOTION_VECTOR
#ifdef TESSELLATION_ON
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/TessellationShare.hlsl"
#endif
void Frag(PackedVaryingsToPS packedInput,
#ifdef OUTPUT_SPLIT_LIGHTING
out float4 outColor : SV_Target0, // outSpecularLighting
out float4 outDiffuseLighting : SV_Target1,
OUTPUT_SSSBUFFER(outSSSBuffer)
#else
out float4 outColor : SV_Target0
#ifdef _WRITE_TRANSPARENT_MOTION_VECTOR
, out float4 outMotionVec : SV_Target1
#endif // _WRITE_TRANSPARENT_MOTION_VECTOR
#endif // OUTPUT_SPLIT_LIGHTING
#ifdef _DEPTHOFFSET_ON
, out float outputDepth : SV_Depth
#endif
)
{
#ifdef _WRITE_TRANSPARENT_MOTION_VECTOR
// Init outMotionVector here to solve compiler warning (potentially unitialized variable)
// It is init to the value of forceNoMotion (with 2.0)
outMotionVec = float4(2.0, 0.0, 0.0, 0.0);
#endif
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(packedInput);
FragInputs input = UnpackVaryingsMeshToFragInputs(packedInput.vmesh);
// We need to readapt the SS position as our screen space positions are for a low res buffer, but we try to access a full res buffer.
input.positionSS.xy = _OffScreenRendering > 0 ? (input.positionSS.xy * _OffScreenDownsampleFactor) : input.positionSS.xy;
uint2 tileIndex = uint2(input.positionSS.xy) / GetTileSize();
// input.positionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS.xyz, tileIndex);
#ifdef VARYINGS_NEED_POSITION_WS
float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS);
#else
// Unused
float3 V = float3(1.0, 1.0, 1.0); // Avoid the division by 0
#endif
SurfaceData surfaceData;
BuiltinData builtinData;
GetSurfaceAndBuiltinData(input, V, posInput, surfaceData, builtinData);
BSDFData bsdfData = ConvertSurfaceDataToBSDFData(input.positionSS.xy, surfaceData);
PreLightData preLightData = GetPreLightData(V, posInput, bsdfData);
outColor = float4(0.0, 0.0, 0.0, 0.0);
// We need to skip lighting when doing debug pass because the debug pass is done before lighting so some buffers may not be properly initialized potentially causing crashes on PS4.
#ifdef DEBUG_DISPLAY
// Init in debug display mode to quiet warning
#ifdef OUTPUT_SPLIT_LIGHTING
outDiffuseLighting = 0;
ENCODE_INTO_SSSBUFFER(surfaceData, posInput.positionSS, outSSSBuffer);
#endif
float4 Set_UV0 = input.texCoord0;
float4 _MainTex_var = SAMPLE_TEXTURE2D(_MainTex, sampler_MainTex, TRANSFORM_TEX(Set_UV0, _MainTex));
surfaceData.baseColor = _MainTex_var.xyz;
// Same code in ShaderPassForwardUnlit.shader
// Reminder: _DebugViewMaterialArray[i]
// i==0 -> the size used in the buffer
// i>0 -> the index used (0 value means nothing)
// The index stored in this buffer could either be
// - a gBufferIndex (always stored in _DebugViewMaterialArray[1] as only one supported)
// - a property index which is different for each kind of material even if reflecting the same thing (see MaterialSharedProperty)
bool viewMaterial = false;
int bufferSize = int(_DebugViewMaterialArray[0]);
if (bufferSize != 0)
{
bool needLinearToSRGB = false;
float3 result = float3(1.0, 0.0, 1.0);
// Loop through the whole buffer
// Works because GetSurfaceDataDebug will do nothing if the index is not a known one
for (int index = 1; index <= bufferSize; index++)
{
int indexMaterialProperty = int(_DebugViewMaterialArray[index]);
// skip if not really in use
if (indexMaterialProperty != 0)
{
viewMaterial = true;
GetPropertiesDataDebug(indexMaterialProperty, result, needLinearToSRGB);
GetVaryingsDataDebug(indexMaterialProperty, input, result, needLinearToSRGB);
GetBuiltinDataDebug(indexMaterialProperty, builtinData, result, needLinearToSRGB);
GetSurfaceDataDebug(indexMaterialProperty, surfaceData, result, needLinearToSRGB);
GetBSDFDataDebug(indexMaterialProperty, bsdfData, result, needLinearToSRGB);
}
}
// TEMP!
// For now, the final blit in the backbuffer performs an sRGB write
// So in the meantime we apply the inverse transform to linear data to compensate.
if (!needLinearToSRGB)
result = SRGBToLinear(max(0, result));
outColor = float4(result, 1.0);
}
if (!viewMaterial)
{
if (_DebugFullScreenMode == FULLSCREENDEBUGMODE_VALIDATE_DIFFUSE_COLOR || _DebugFullScreenMode == FULLSCREENDEBUGMODE_VALIDATE_SPECULAR_COLOR)
{
float3 result = float3(0.0, 0.0, 0.0);
GetPBRValidatorDebug(surfaceData, result);
outColor = float4(result, 1.0f);
}
else if (_DebugFullScreenMode == FULLSCREENDEBUGMODE_TRANSPARENCY_OVERDRAW)
{
float4 result = _DebugTransparencyOverdrawWeight * float4(TRANSPARENCY_OVERDRAW_COST, TRANSPARENCY_OVERDRAW_COST, TRANSPARENCY_OVERDRAW_COST, TRANSPARENCY_OVERDRAW_A);
outColor = result;
}
else
#endif
{
#ifdef _SURFACE_TYPE_TRANSPARENT
uint featureFlags = LIGHT_FEATURE_MASK_FLAGS_TRANSPARENT;
#else
uint featureFlags = LIGHT_FEATURE_MASK_FLAGS_OPAQUE;
#endif
float3 diffuseLighting;
float3 specularLighting;
LightLoop(V, posInput, preLightData, bsdfData, builtinData, featureFlags, diffuseLighting, specularLighting);
diffuseLighting *= GetCurrentExposureMultiplier();
specularLighting *= GetCurrentExposureMultiplier();
#ifdef OUTPUT_SPLIT_LIGHTING
if (_EnableSubsurfaceScattering != 0 && ShouldOutputSplitLighting(bsdfData))
{
outColor = float4(specularLighting, 1.0);
outDiffuseLighting = float4(TagLightingForSSS(diffuseLighting), 1.0);
}
else
{
outColor = float4(diffuseLighting + specularLighting, 1.0);
outDiffuseLighting = 0;
}
ENCODE_INTO_SSSBUFFER(surfaceData, posInput.positionSS, outSSSBuffer);
#else
outColor = ApplyBlendMode(diffuseLighting, specularLighting, builtinData.opacity);
outColor = EvaluateAtmosphericScattering(posInput, V, outColor);
#endif
#ifdef _WRITE_TRANSPARENT_MOTION_VECTOR
VaryingsPassToPS inputPass = UnpackVaryingsPassToPS(packedInput.vpass);
bool forceNoMotion = any(unity_MotionVectorsParams.yw == 0.0);
// outMotionVec is already initialize at the value of forceNoMotion (see above)
if (!forceNoMotion)
{
float2 motionVec = CalculateMotionVector(inputPass.positionCS, inputPass.previousPositionCS);
EncodeMotionVector(motionVec * 0.5, outMotionVec);
outMotionVec.zw = 1.0;
}
#endif
}
#ifdef DEBUG_DISPLAY
}
#endif
#ifdef _DEPTHOFFSET_ON
outputDepth = posInput.deviceDepth;
#endif
}

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: 1b4f1c7876302e04a81e6bd06cb9dd39
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,275 +0,0 @@
//Unity Toon Shader/HDRP
//nobuyuki@unity3d.com
//toshiyuki@unity3d.com (Universal RP/HDRP)
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Macros.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/PhysicalCamera.hlsl"
#include "HDRPToonHead.hlsl"
// Channel mask enum.
// this must be same to UI cs code
// HDRPToonGUI._ChannelEnum
int eBaseColor = 0;
int eFirstShade = 1;
int eSecondShade = 2;
int eHighlight = 3;
int eAngelRing = 4;
int eRimLight = 5;
int eOutline = 6;
// not in materials
int _ToonLightHiCutFilter;
int _ToonEvAdjustmentCurve;
float _ToonEvAdjustmentValueArray[128];
float _ToonEvAdjustmentValueMin;
float _ToonEvAdjustmentValueMax;
float _ToonEvAdjustmentCompensation;
float _ToonIgnoreExposureMultiplier;
// function to rotate the UV: RotateUV()
//float2 rotatedUV = RotateUV(i.uv0, (_angular_Verocity*3.141592654), float2(0.5, 0.5), _Time.g);
float2 RotateUV(float2 _uv, float _radian, float2 _piv, float _time)
{
float RotateUV_ang = _radian;
float RotateUV_cos = cos(_time*RotateUV_ang);
float RotateUV_sin = sin(_time*RotateUV_ang);
return (mul(_uv - _piv, float2x2(RotateUV_cos, -RotateUV_sin, RotateUV_sin, RotateUV_cos)) + _piv);
}
float3 ConvertFromEV100(float3 EV100)
{
#if 1
float3 value = pow(2, EV100) * 2.5f;
return value;
#else
float3 maxLuminance = 1.2f * pow(2.0f, EV100);
return 1.0f / maxLuminance;
#endif
}
float3 ConvertToEV100(float3 value)
{
#if 1
return log2(value*0.4f);
#else
return log2(1.0f / (1.2f * value));
#endif
}
float WeightSample(PositionInputs positionInput)
{
// Center-weighted
const float2 kCenter = _ScreenParams.xy * 0.5;
const float weight = pow(length((kCenter.xy - positionInput.positionSS.xy) / _ScreenParams.xy),1.0) ;
return 1.0 - saturate(weight);
}
float3 ApplyCompensation(float3 originalColor)
{
float3 ev100_Color = ConvertToEV100(originalColor) +_ToonEvAdjustmentCompensation * 0.5f;
float3 resultColor = max(0, ConvertFromEV100(ev100_Color));
return resultColor;
}
float3 ApplyCurrentExposureMultiplier(float3 color)
{
return color * lerp(GetCurrentExposureMultiplier(), 1, _ToonIgnoreExposureMultiplier);
}
float3 GetExposureAdjustedColor(float3 originalColor)
{
if (_ToonEvAdjustmentCurve != 0)
{
float3 ev100_Color = ConvertToEV100(originalColor);
ev100_Color = clamp(ev100_Color, _ToonEvAdjustmentValueMin, _ToonEvAdjustmentValueMax);
float3 ev100_remap = (ev100_Color - _ToonEvAdjustmentValueMin) * (128-1) / (_ToonEvAdjustmentValueMax - _ToonEvAdjustmentValueMin);
ev100_remap = clamp(ev100_remap, 0.0, 127.0);
int3 ev100_idx = (int3)ev100_remap;
float3 ev100_lerp = ev100_remap - ev100_idx;
float3 ev100_remapped;
ev100_remapped.r = _ToonEvAdjustmentValueArray[ev100_idx.r] +(_ToonEvAdjustmentValueArray[ev100_idx.r + 1] - _ToonEvAdjustmentValueArray[ev100_idx.r]) * ev100_lerp.r;
ev100_remapped.g = _ToonEvAdjustmentValueArray[ev100_idx.g] +(_ToonEvAdjustmentValueArray[ev100_idx.g + 1] - _ToonEvAdjustmentValueArray[ev100_idx.g]) * ev100_lerp.g;
ev100_remapped.b = _ToonEvAdjustmentValueArray[ev100_idx.b] +(_ToonEvAdjustmentValueArray[ev100_idx.b + 1] - _ToonEvAdjustmentValueArray[ev100_idx.b]) * ev100_lerp.b;
float3 resultColor = ConvertFromEV100(ev100_remapped);
return resultColor;
}
else // else is neccessary to avoid warrnings.
{
return originalColor;
}
}
float GetLightAttenuation(float3 lightColor)
{
float lightAttenuation = rateR *lightColor.r + rateG *lightColor.g + rateB *lightColor.b;
return lightAttenuation;
}
int GetNextDirectionalLightIndex(BuiltinData builtinData, int currentIndex, int mainLightIndex)
{
int i = 0; // Declare once to avoid the D3D11 compiler warning.
for (i = 0; i < (int)_DirectionalLightCount; ++i)
{
if (IsMatchingLightLayer(_DirectionalLightDatas[i].lightLayers, builtinData.renderingLayers))
{
if (mainLightIndex != i)
{
if (currentIndex < i)
{
return i;
}
}
}
}
return -1; // not found
}
int GetUtsMainLightIndex(BuiltinData builtinData)
{
int mainLightIndex = -1;
float3 lightColor = float3(0.0f, 0.0f, 0.0f);
float lightAttenuation = 0.0f;
uint i = 0; // Declare once to avoid the D3D11 compiler warning.
for (i = 0; i < _DirectionalLightCount; ++i)
{
if (IsMatchingLightLayer(_DirectionalLightDatas[i].lightLayers, builtinData.renderingLayers))
{
float3 currentLightColor = _DirectionalLightDatas[i].color;
float currentLightAttenuation = GetLightAttenuation(currentLightColor);
if (mainLightIndex == -1 || (currentLightAttenuation > lightAttenuation))
{
mainLightIndex = i;
lightAttenuation = currentLightAttenuation;
lightColor = currentLightColor;
}
}
}
return mainLightIndex;
}
// UTSLightData GetUTSMainPunctualLightData(BuiltinData builtinData, PositionInputs posInput)
// {
// UTSLightData mainPunctualLight;
// uint lightCount, lightStart;
// #ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER
// GetCountAndStart(posInput, LIGHTCATEGORY_PUNCTUAL, lightStart, lightCount);
// #else // LIGHTLOOP_DISABLE_TILE_AND_CLUSTER
// lightCount = _PunctualLightCount;
// lightStart = 0;
// #endif
// bool fastPath = false;
// #if SCALARIZE_LIGHT_LOOP
// uint lightStartLane0;
// fastPath = IsFastPath(lightStart, lightStartLane0);
// if (fastPath)
// {
// lightStart = lightStartLane0;
// }
// #endif
// uint v_lightListOffset = 0;
// uint v_lightIdx = lightStart;
// float channelAlpha = 0.0f;
// [loop] // vulkan shader compiler can not unroll.
// while (v_lightListOffset < lightCount)
// {
// v_lightIdx = FetchIndex(lightStart, v_lightListOffset);
// #if SCALARIZE_LIGHT_LOOP
// uint s_lightIdx = ScalarizeElementIndex(v_lightIdx, fastPath);
// #else
// uint s_lightIdx = v_lightIdx;
// #endif
// if (s_lightIdx == -1)
// break;
// LightData s_lightData = FetchLight(s_lightIdx);
// // If current scalar and vector light index match, we process the light. The v_lightListOffset for current thread is increased.
// // Note that the following should really be ==, however, since helper lanes are not considered by WaveActiveMin, such helper lanes could
// // end up with a unique v_lightIdx value that is smaller than s_lightIdx hence being stuck in a loop. All the active lanes will not have this problem.
// if (s_lightIdx >= v_lightIdx)
// {
// v_lightListOffset++;
// if (IsMatchingLightLayer(s_lightData.lightLayers, builtinData.renderingLayers))
// {
// float3 lightDirection;
// float4 distances; // {d, d^2, 1/d, d_proj}
// GetPunctualLightVectors(posInput.positionWS, s_lightData, lightDirection, distances);
// float4 lightColor = EvaluateLight_Punctual(context, posInput, s_lightData, lightDirection, distances);
// float3 additionalLightColor = ApplyCurrentExposureMultiplier(lightColor.rgb) * lightColor.a;
// const float notDirectional = 1.0f;
// UTSLightData utsLightData;
// utsLightData.lightColor = additionalLightColor;
// utsLightData.lightDirection = lightDirection;
// utsLightData.diffuseDimmer = s_lightData.diffuseDimmer;
// utsLightData.specularDimmer = s_lightData.specularDimmer;
// utsLightData.shadowTint = s_lightData.shadowTint;
// utsLightData.penumbraTint = s_lightData.penumbraTint;
// if(length(additionalLightColor) >= length(mainPunctualLight.lightColor))
// {
// mainPunctualLight = utsLightData;
// }
// }
// }
// }
// return mainPunctualLight;
// }
// Todo: calculate the acutal main lighboth dorectional and punctual)t based on the light attenuation, rather than using the main directional light
UTSLightData GetCustomMainLightData(BuiltinData builtinData, UTSLightData mainPunctualLight)
{
UTSLightData utsLightData;
int mainLightIndex;
mainLightIndex = GetUtsMainLightIndex(builtinData);
if (mainLightIndex == -1 || length(_DirectionalLightDatas[mainLightIndex].color) < length(mainPunctualLight.lightColor))
{
utsLightData = mainPunctualLight;
}
else
{
utsLightData.lightColor = ApplyCurrentExposureMultiplier(_DirectionalLightDatas[mainLightIndex].color);
utsLightData.lightDirection = -_DirectionalLightDatas[mainLightIndex].forward;
utsLightData.diffuseDimmer = _DirectionalLightDatas[mainLightIndex].diffuseDimmer;
utsLightData.specularDimmer = _DirectionalLightDatas[mainLightIndex].specularDimmer;
utsLightData.shadowTint = _DirectionalLightDatas[mainLightIndex].shadowTint;
utsLightData.penumbraTint = _DirectionalLightDatas[mainLightIndex].penumbraTint;
}
return utsLightData;
}
# include "ShadingOtherLight.hlsl"
# include "UtsSelfShadowMainLight.hlsl"
# include "ShadingMainLight.hlsl"

View File

@@ -1,27 +0,0 @@
// Unity Toon Shader
// sampler2D _MainTex;
// sampler2D _1st_ShadeMap;
// sampler2D _2nd_ShadeMap;
TEXTURE2D(_MainTex); SAMPLER(sampler_MainTex);
TEXTURE2D(_1st_ShadeMap);
TEXTURE2D(_2nd_ShadeMap);
sampler _Set_1st_ShadePosition;
sampler _Set_2nd_ShadePosition;
sampler _ShadingGradeMap;
sampler _HighColor_Tex;
sampler _Set_HighColorMask;
sampler _Set_RimLightMask;
sampler _MatCap_Sampler;
sampler _NormalMapForMatCap;
sampler _Set_MatcapMask;
sampler _Emissive_Tex;
// sampler2D _ClippingMask;
TEXTURE2D(_ClippingMask);
sampler _AngelRing_Sampler;
sampler _Outline_Sampler;
sampler _OutlineTex;
sampler _BakedNormal;

View File

@@ -1,108 +0,0 @@
using Unity.Toonshader;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using UnityEngine.Rendering.RendererUtils;
[HideInInspector]
public class UTSHairShadowPass : DrawRenderersCustomPass
{
private const string Hair_Shadow_Distance_Prop_Name = "_HairShadowDistance";
private const string Hair_Shadow_Distance_Scale_Prop_Name = "_HairShadowDistanceScaleFactor";
private const string Hair_Shadow_Depth_Bias_Prop_Name = "_HairShadowDepthBias";
private const string Hair_Shadow_FadeIn_Prop_Name = "_HairShadowFadeInDistance";
private const string Hair_Shadow_Fade_Out_Prop_Name = "_HairShadowFadeOutDistance";
private const string Output_RT_Name = "_HairShadowTex";
private RTHandle _outputRTHandle;
private bool _isEnable = false;
public UnityEngine.RenderingLayerMask renderingLayerMask;
protected override void Setup(ScriptableRenderContext renderContext, CommandBuffer cmd)
{
_outputRTHandle?.Release();
_outputRTHandle = RTHandles.Alloc(Screen.width, Screen.height, colorFormat: GraphicsFormat.D32_SFloat, filterMode: FilterMode.Bilinear, wrapMode: TextureWrapMode.Clamp, isShadowMap: true, name: Output_RT_Name);
SetEnable(true);
}
protected override void Execute(CustomPassContext ctx)
{
var utsRenderer = ctx.hdCamera.volumeStack.GetComponent<UTSRenderer>();
if (utsRenderer == null || !utsRenderer.enableHairShadow.value || !utsRenderer.enable.value)
{
SetEnable(false);
return;
}
if (!_isEnable)
{
return;
}
SetShadowProperty(utsRenderer);
if (_outputRTHandle != null)
{
Shader.SetGlobalTexture(Output_RT_Name, _outputRTHandle);
CoreUtils.SetRenderTarget(ctx.cmd, _outputRTHandle, ClearFlag.DepthStencil);
}
var mask = RenderStateMask.Nothing;
var stateBlock = new RenderStateBlock(mask)
{
depthState = new DepthState(true, CompareFunction.LessEqual),
};
var result = new RendererListDesc(HDShaderPassNames.s_DepthForwardOnlyName, ctx.cullingResults, ctx.hdCamera.camera)
{
renderQueueRange = GetRenderQueueRange(RenderQueueType.All),
sortingCriteria = SortingCriteria.CommonOpaque,
excludeObjectMotionVectors = false,
stateBlock = stateBlock,
renderingLayerMask = renderingLayerMask,
};
CoreUtils.DrawRendererList(ctx.renderContext, ctx.cmd, ctx.renderContext.CreateRendererList(result));
}
private static void SetShadowProperty(UTSRenderer utsRenderer)
{
Shader.SetGlobalFloat(Hair_Shadow_Distance_Prop_Name, utsRenderer.shadowDistance.value);
Shader.SetGlobalFloat(Hair_Shadow_Distance_Scale_Prop_Name, utsRenderer.shadowDistanceScale.value);
Shader.SetGlobalFloat(Hair_Shadow_Depth_Bias_Prop_Name, utsRenderer.shadowDepthBias.value);
Shader.SetGlobalFloat(Hair_Shadow_FadeIn_Prop_Name, utsRenderer.shadowFadeIn.value);
Shader.SetGlobalFloat(Hair_Shadow_Fade_Out_Prop_Name, utsRenderer.shadowFadeOut.value);
}
protected override void Cleanup()
{
Release();
}
public void Release()
{
SetEnable(false);
_outputRTHandle?.Release();
}
public void SetEnable(bool isEnable)
{
if (_isEnable != isEnable)
{
if (isEnable)
{
Shader.EnableKeyword("_HAIR_SHADOWS");
}
else
{
Shader.DisableKeyword("_HAIR_SHADOWS");
}
_isEnable = isEnable;
}
}
}

View File

@@ -1,2 +0,0 @@
fileFormatVersion: 2
guid: 7157c6dc91cee0d4aae565d1c8d66807

View File

@@ -1,41 +0,0 @@
using Unity.Toonshader;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
[HideInInspector]
public class UTSOutlinePass : DrawRenderersCustomPass
{
private ShaderTagId outlineTag = new("Outline");
protected override void Execute(CustomPassContext ctx)
{
var utsRenderer = ctx.hdCamera.volumeStack.GetComponent<UTSRenderer>();
if (utsRenderer == null)
return;
if (!utsRenderer.enableOutline.value || !utsRenderer.enable.value)
return;
Shader.SetGlobalFloat("_Outline_MaxWidth", utsRenderer.outlineMaxWidth.value * 0.01f);
var mask = RenderStateMask.Nothing;
var stateBlock = new RenderStateBlock(mask)
{
depthState = new DepthState(depthWrite, depthCompareFunction),
// We disable the stencil when the depth is overwritten but we don't write to it, to prevent writing to the stencil.
stencilState = new StencilState(false),
};
var renderConfig = HDUtils.GetRendererConfiguration(false, false);
var result = new UnityEngine.Rendering.RendererUtils.RendererListDesc(outlineTag, ctx.cullingResults, ctx.hdCamera.camera)
{
rendererConfiguration = renderConfig,
renderQueueRange = GetRenderQueueRange(RenderQueueType.All),
excludeObjectMotionVectors = false,
stateBlock = stateBlock,
};
CoreUtils.DrawRendererList(ctx.renderContext, ctx.cmd, ctx.renderContext.CreateRendererList(result));
}
}

View File

@@ -1,198 +0,0 @@
using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
namespace Unity.Toonshader
{
[Serializable, VolumeComponentMenu("Rendering/Unity Toon Shader")]
public class UTSRenderer : VolumeComponent
{
// flags
bool _initialized = false;
const int kAdjustmentCurvePrecision = 128;
const string kCompensationPropName = "_ToonEvAdjustmentCompensation";
const string kExposureAdjustmentPropName = "_ToonEvAdjustmentCurve";
const string kExposureArrayPropName = "_ToonEvAdjustmentValueArray";
const string kExposureMinPropName = "_ToonEvAdjustmentValueMin";
const string kExposureMaxPropName = "_ToonEvAdjustmentValueMax";
const string kToonLightFilterPropName = "_ToonLightHiCutFilter";
const string kIgnoreVolumeExposurePropName = "_ToonIgnoreExposureMultiplier";
[SerializeField]
internal float[] _ExposureArray;
[SerializeField]
internal float _Max, _Min;
//CustomPassVolume customPassVolume = new();
//UTSOutlinePass outlinePass = new();
#if UNITY_EDITOR
#pragma warning restore CS0414
bool m_isCompiling = false;
#endif
public BoolParameter enable = new BoolParameter(false, BoolParameter.DisplayType.EnumPopup);
[Space]
[Header("Outline")]
public BoolParameter enableOutline = new BoolParameter(false);
public MinFloatParameter outlineMaxWidth = new MinFloatParameter(1.0f, 0.0f);
[Space]
[Header("Hair Shadow")]
public BoolParameter enableHairShadow = new BoolParameter(false);
public ClampedFloatParameter shadowDistance = new ClampedFloatParameter(5.0f, 0.0f, 20.0f);
public ClampedFloatParameter shadowDistanceScale = new ClampedFloatParameter(0.5f, 0.0f, 1.0f);
public ClampedFloatParameter shadowDepthBias = new ClampedFloatParameter(0f, 0.0f, 0.01f);
public FloatParameter shadowFadeIn = new FloatParameter(45f);
public FloatParameter shadowFadeOut = new FloatParameter(50f);
[Space]
[Header("Exposure")]
public BoolParameter ignoreVolumeExposure = new BoolParameter(false);
public BoolParameter lightIntensityLimiter = new BoolParameter(false);
public MinFloatParameter compensation = new MinFloatParameter(0.0f, 0.0f);
public BoolParameter toonEVAdjustment = new BoolParameter(false);
public AnimationCurveParameter adjustmentCurve = new AnimationCurveParameter(DefaultAnimationCurve());
UTSRenderer()
{
displayName = "UTS Renderer";
}
protected override void OnEnable()
{
base.OnEnable();
UTSDebugPanel.OnEnable();
Initialize();
}
protected override void OnDisable()
{
base.OnDisable();
UTSDebugPanel.OnDisable();
Release();
}
private void OnValidate()
{
if (!enable.value)
{
Release();
return;
}
Initialize();
if (!_initialized)
{
return;
}
// Fail safe in case the curve is deleted / has 0 point
var curve = adjustmentCurve.value;
if (curve == null || curve.length == 0)
{
_Min = 0f;
_Max = 0f;
for (var i = 0; i < kAdjustmentCurvePrecision; i++)
_ExposureArray[i] = 0.0f;
}
else
{
_Min = curve[0].time;
_Max = curve[curve.length - 1].time;
var step = (_Max - _Min) / (kAdjustmentCurvePrecision - 1f);
for (var i = 0; i < kAdjustmentCurvePrecision; i++)
_ExposureArray[i] = curve.Evaluate(_Min + step * i);
}
#if UNITY_EDITOR
// handle script recompile
if (EditorApplication.isCompiling && !m_isCompiling)
{
// on compile begin
m_isCompiling = true;
// Release(); no need
return; //
}
else if (!EditorApplication.isCompiling && m_isCompiling)
{
// on compile end
m_isCompiling = false;
}
#endif
Shader.SetGlobalFloatArray(kExposureArrayPropName, _ExposureArray);
Shader.SetGlobalFloat(kExposureMinPropName, _Min);
Shader.SetGlobalFloat(kExposureMaxPropName, _Max);
Shader.SetGlobalInt(kExposureAdjustmentPropName, toonEVAdjustment.value ? 1 : 0);
Shader.SetGlobalInt(kToonLightFilterPropName, lightIntensityLimiter.value ? 1 : 0);
Shader.SetGlobalInt(kIgnoreVolumeExposurePropName, ignoreVolumeExposure.value ? 1 : 0);
Shader.SetGlobalFloat(kCompensationPropName, compensation.value);
}
internal static AnimationCurve DefaultAnimationCurve()
{
return AnimationCurve.Linear(-10f, -10f, -1.32f, -1.32f);
}
void Initialize()
{
if (_initialized)
{
return;
}
#if UNITY_EDITOR
// initializing renderer can interfere GI baking. so wait until it is completed.
if (EditorApplication.isCompiling)
return;
#endif
if (_ExposureArray == null || _ExposureArray.Length != kAdjustmentCurvePrecision)
{
_ExposureArray = new float[kAdjustmentCurvePrecision];
}
_initialized = true;
}
protected override void OnDestroy()
{
base.OnDestroy();
Release();
}
new void Release()
{
if (_initialized)
{
_ExposureArray = null;
Shader.SetGlobalFloat(kExposureMinPropName, 0);
Shader.SetGlobalFloat(kExposureMaxPropName, 0);
Shader.SetGlobalInt(kExposureAdjustmentPropName, 0);
Shader.SetGlobalInt(kToonLightFilterPropName, 0);
Shader.SetGlobalInt(kIgnoreVolumeExposurePropName, 0);
Shader.SetGlobalFloat(kCompensationPropName, 0);
}
_initialized = false;
base.Release();
}
private void Reset()
{
OnDisable();
OnEnable();
DefaultAnimationCurve();
}
}
}

View File

@@ -1,22 +0,0 @@
using UnityEngine;
[ExecuteInEditMode]
public class UTSMeshRenderer : MonoBehaviour
{
private const string Shader_Prop_Object_Center_Name = "_ObjectCenterPositionWS";
public Material material;
public Transform objectCenter;
private void Update()
{
if (material == null)
return;
if (objectCenter != null)
{
material.SetVector(Shader_Prop_Object_Center_Name, objectCenter.position);
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: ee7513f8cc93a9d4f981fd4b10f8dfc1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,6 +1,6 @@
{ {
"name": "Unity.Toonshader", "name": "Misaki.HdrpToon",
"rootNamespace": "Unity.Toonshader", "rootNamespace": "Misaki.HdrpToon",
"references": [ "references": [
"GUID:df380645f10b7bc4b97d4f5eb6303d95", "GUID:df380645f10b7bc4b97d4f5eb6303d95",
"GUID:3eae0364be2026648bf74846acb8a731", "GUID:3eae0364be2026648bf74846acb8a731",

View File

@@ -1,22 +1,15 @@
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using UnityEngine; using UnityEngine;
#if UNITY_EDITOR #if UNITY_EDITOR
using UnityEditor; using UnityEditor;
#endif #endif
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering;
using UnityObject = UnityEngine.Object;
using System.Linq; using System.Linq;
namespace Unity.Rendering.Toon namespace Misaki.HdrpToon
{ {
[ExecuteAlways] [ExecuteAlways]
[DisallowMultipleComponent] [DisallowMultipleComponent]
[UTSHelpURL("ToonEVAdjustment")] public class ModelToonEvAdjustment : MonoBehaviour
internal class ModelToonEvAdjustment : MonoBehaviour
{ {
const string kCompensationPorpName = "_ToonEvAdjustmentCompensation"; const string kCompensationPorpName = "_ToonEvAdjustmentCompensation";
const string kExposureAdjustmentPropName = "_ToonEvAdjustmentCurve"; const string kExposureAdjustmentPropName = "_ToonEvAdjustmentCurve";
@@ -31,30 +24,20 @@ namespace Unity.Rendering.Toon
const int kAdjustmentCurvePrecision = 128; const int kAdjustmentCurvePrecision = 128;
public bool m_ToonLightHiCutFilter = false;
public bool m_ExposureAdjustmnt = false;
public bool m_IgnorVolumeExposure = false;
[SerializeField] public AnimationCurve m_AnimationCurve = DefaultAnimationCurve();
internal bool m_ToonLightHiCutFilter = false; public float[] m_ExposureArray;
[SerializeField] public float m_Max, m_Min;
internal bool m_ExposureAdjustmnt = false; public float m_Compensation;
[SerializeField]
internal bool m_IgnorVolumeExposure = false;
[SerializeField]
internal AnimationCurve m_AnimationCurve = DefaultAnimationCurve();
[SerializeField]
internal float[] m_ExposureArray;
[SerializeField]
internal float m_Max, m_Min;
[SerializeField]
internal float m_Compensation;
internal GameObject[] m_Objs; internal GameObject[] m_Objs;
[SerializeField] [SerializeField]
// [HideInInspector] // [HideInInspector]
Renderer[] m_Renderers; Renderer[] m_Renderers;
[SerializeField] [SerializeField]
// [HideInInspector] // [HideInInspector]
MaterialPropertyBlock[] m_MaterialPropertyBlocks; MaterialPropertyBlock[] m_MaterialPropertyBlocks;
#if UNITY_EDITOR #if UNITY_EDITOR
@@ -111,16 +94,16 @@ namespace Unity.Rendering.Toon
m_Min = 0f; m_Min = 0f;
m_Max = 0f; m_Max = 0f;
for (int i = 0; i < kAdjustmentCurvePrecision; i++) for (var i = 0; i < kAdjustmentCurvePrecision; i++)
m_ExposureArray[i] = 0.0f; m_ExposureArray[i] = 0.0f;
} }
else else
{ {
m_Min = curve[0].time; m_Min = curve[0].time;
m_Max = curve[curve.length - 1].time; m_Max = curve[curve.length - 1].time;
float step = (m_Max - m_Min) / (kAdjustmentCurvePrecision - 1f); var step = (m_Max - m_Min) / (kAdjustmentCurvePrecision - 1f);
for (int i = 0; i < kAdjustmentCurvePrecision; i++) for (var i = 0; i < kAdjustmentCurvePrecision; i++)
m_ExposureArray[i] = curve.Evaluate(m_Min + step * i); m_ExposureArray[i] = curve.Evaluate(m_Min + step * i);
} }
@@ -143,8 +126,8 @@ namespace Unity.Rendering.Toon
int length = m_Renderers.Length; var length = m_Renderers.Length;
for (int ii = 0; ii < length; ii++) for (var ii = 0; ii < length; ii++)
{ {
m_Renderers[ii].GetPropertyBlock(m_MaterialPropertyBlocks[ii]); m_Renderers[ii].GetPropertyBlock(m_MaterialPropertyBlocks[ii]);
@@ -209,13 +192,13 @@ namespace Unity.Rendering.Toon
m_Objs = new GameObject[1]; m_Objs = new GameObject[1];
m_Objs[0] = this.gameObject; m_Objs[0] = this.gameObject;
} }
int objCount = m_Objs.Length; var objCount = m_Objs.Length;
int rendererCount = 0; var rendererCount = 0;
List<Renderer> rendererList = new List<Renderer>(); var rendererList = new List<Renderer>();
for (int ii = 0; ii < objCount; ii++) for (var ii = 0; ii < objCount; ii++)
{ {
if (m_Objs[ii] == null ) if (m_Objs[ii] == null)
{ {
continue; continue;
} }
@@ -227,20 +210,20 @@ namespace Unity.Rendering.Toon
rendererCount++; rendererCount++;
rendererList.Add(renderer); rendererList.Add(renderer);
} }
GameObject[] childGameObjects = m_Objs[ii].GetComponentsInChildren<Transform>().Select(t => t.gameObject).ToArray(); var childGameObjects = m_Objs[ii].GetComponentsInChildren<Transform>().Select(t => t.gameObject).ToArray();
int childCount = childGameObjects.Length; var childCount = childGameObjects.Length;
for (int jj = 0; jj < childCount; jj++) for (var jj = 0; jj < childCount; jj++)
{ {
if (m_Objs[ii] == childGameObjects[jj]) if (m_Objs[ii] == childGameObjects[jj])
continue; continue;
var modelToonEvAdjustment = childGameObjects[jj].GetComponent<ModelToonEvAdjustment>(); var modelToonEvAdjustment = childGameObjects[jj].GetComponent<ModelToonEvAdjustment>();
if ( modelToonEvAdjustment != null ) if (modelToonEvAdjustment != null)
{ {
break; break;
} }
renderer = childGameObjects[jj].GetComponent<Renderer>(); renderer = childGameObjects[jj].GetComponent<Renderer>();
if ( renderer != null ) if (renderer != null)
{ {
rendererList.Add(renderer); rendererList.Add(renderer);
rendererCount++; rendererCount++;
@@ -249,12 +232,12 @@ namespace Unity.Rendering.Toon
} }
if (rendererCount != 0) if (rendererCount != 0)
{ {
m_MaterialPropertyBlocks = new MaterialPropertyBlock[rendererCount]; m_MaterialPropertyBlocks = new MaterialPropertyBlock[rendererCount];
m_Renderers = rendererList.ToArray(); m_Renderers = rendererList.ToArray();
for (int ii = 0; ii < rendererCount; ii++) for (var ii = 0; ii < rendererCount; ii++)
{ {
m_MaterialPropertyBlocks[ii] = new MaterialPropertyBlock(); m_MaterialPropertyBlocks[ii] = new MaterialPropertyBlock();
} }
@@ -272,10 +255,10 @@ namespace Unity.Rendering.Toon
if (m_initialized) if (m_initialized)
{ {
m_ExposureArray = null; m_ExposureArray = null;
if (m_Renderers != null ) if (m_Renderers != null)
{ {
int length = m_Renderers.Length; var length = m_Renderers.Length;
for (int ii = 0; ii < length; ii++) for (var ii = 0; ii < length; ii++)
{ {
m_Renderers[ii].SetPropertyBlock(null); m_Renderers[ii].SetPropertyBlock(null);
} }

View File

@@ -0,0 +1,8 @@
namespace Misaki.HdrpToon
{
internal enum ShadingMode
{
Standard,
SDF,
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b5065e386905cb248bdf1ded804260b4

View File

@@ -0,0 +1,16 @@
using System;
using UnityEngine.Rendering;
namespace Misaki.HdrpToon
{
[Flags]
[GenerateHLSL(PackingRules.Exact)]
public enum SurfaceFeatureFlags : uint
{
None = 0,
RimLight = 1 << 0,
Stocking = 1 << 1,
AngelRing = 1 << 2,
Outline = 1 << 3,
}
}

View File

@@ -0,0 +1,17 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef SURFACEFEATUREFLAGS_CS_HLSL
#define SURFACEFEATUREFLAGS_CS_HLSL
//
// Misaki.HdrpToon.SurfaceFeatureFlags: static fields
//
#define SURFACEFEATUREFLAGS_NONE (0)
#define SURFACEFEATUREFLAGS_RIM_LIGHT (1)
#define SURFACEFEATUREFLAGS_STOCKING (2)
#define SURFACEFEATUREFLAGS_ANGEL_RING (4)
#define SURFACEFEATUREFLAGS_OUTLINE (8)
#endif

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: a37603210e947e945be7817ada46bff5 guid: ec297400b1508d647a7cdbad2c0edf40
ShaderIncludeImporter: ShaderIncludeImporter:
externalObjects: {} externalObjects: {}
userData: userData:

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 737ea728a50a7664b90cba3dd3e21249

View File

@@ -3,19 +3,32 @@ using System.IO;
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
namespace Unity.Toonshader namespace Misaki.HdrpToon
{ {
[Serializable] internal enum BufferQuality
public struct UTSOutlineSetting
{ {
public bool enable; Low,
High
} }
[Serializable] [Serializable]
public struct UtsHairShadowSetting internal struct UtsHairShadowSetting
{
public bool enable;
public BufferQuality quality;
}
[Serializable]
internal struct UtsHairBlendingSetting
{
public bool enable;
public BufferQuality quality;
}
[Serializable]
internal struct UTSOutlineSetting
{ {
public bool enable; public bool enable;
public RenderingLayerMask CasterRenderingLayer;
} }
[CreateAssetMenu(fileName = "UTSRenderSetting", menuName = "UTS/RenderSetting")] [CreateAssetMenu(fileName = "UTSRenderSetting", menuName = "UTS/RenderSetting")]
@@ -25,8 +38,12 @@ namespace Unity.Toonshader
public const string UTS_RENDERING_SETTINGS_PATH = "Assets/Resources/Settings/UTSRenderSettings.asset"; public const string UTS_RENDERING_SETTINGS_PATH = "Assets/Resources/Settings/UTSRenderSettings.asset";
public const string UTS_RENDERING_SETTINGS_RESOURCES_PATH = "Settings/UTSRenderSettings"; public const string UTS_RENDERING_SETTINGS_RESOURCES_PATH = "Settings/UTSRenderSettings";
public UTSOutlineSetting outlineSetting; [SerializeField]
public UtsHairShadowSetting hairShadowSetting; internal UtsHairShadowSetting hairShadowSetting;
[SerializeField]
internal UtsHairBlendingSetting hairBlendingSetting;
[SerializeField]
internal UTSOutlineSetting outlineSetting;
internal static UTSRenderPassSettings GetOrCreateSettings() internal static UTSRenderPassSettings GetOrCreateSettings()
{ {
@@ -43,6 +60,12 @@ namespace Unity.Toonshader
} }
else else
{ {
var directory = Path.GetDirectoryName(UTS_RENDERING_SETTINGS_PATH);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
renderingSettings = CreateInstance<UTSRenderPassSettings>(); renderingSettings = CreateInstance<UTSRenderPassSettings>();
AssetDatabase.CreateAsset(renderingSettings, UTS_RENDERING_SETTINGS_PATH); AssetDatabase.CreateAsset(renderingSettings, UTS_RENDERING_SETTINGS_PATH);
AssetDatabase.Refresh(); AssetDatabase.Refresh();

View File

@@ -1,205 +0,0 @@
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Unity.Rendering.Toon
{
[ExecuteAlways]
[DisallowMultipleComponent]
[UTSHelpURL("ToonEVAdjustment")]
internal class SceneToonEvAdjustment : MonoBehaviour
{
// flags
bool m_initialized = false;
bool m_srpCallbackInitialized = false;
const int kAdjustmentCurvePrecision = 128;
const string kCompensationPorpName = "_ToonEvAdjustmentCompensation";
const string kExposureAdjustmentPropName = "_ToonEvAdjustmentCurve";
const string kExposureArrayPropName = "_ToonEvAdjustmentValueArray";
const string kExposureMinPropName = "_ToonEvAdjustmentValueMin";
const string kExposureMaxPropName = "_ToonEvAdjustmentValueMax";
const string kToonLightFilterPropName = "_ToonLightHiCutFilter";
const string kIgonoreVolumeExposurePropName = "_ToonIgnoreExposureMultiplier";
internal bool m_ToonLightHiCutFilter = false;
internal bool m_ExposureAdjustmnt = false;
internal bool m_IgnorVolumeExposure = false;
internal AnimationCurve m_AnimationCurve = DefaultAnimationCurve();
internal float[] m_ExposureArray;
internal float m_Max, m_Min;
internal float m_Compensation;
private static SceneToonEvAdjustment instance;
#if UNITY_EDITOR
#pragma warning restore CS0414
bool m_isCompiling = false;
#endif
void Awake()
{
if (instance == null)
{
instance = this as SceneToonEvAdjustment;
return;
}
else if (instance == this)
{
return;
}
Debug.LogError("There is ToonEvAdjustmentCurve instance in hierarchy.");
#if UNITY_EDITOR
DestroyImmediate(this);
Selection.activeGameObject = instance.gameObject;
#else
Destroy(this);
#endif
}
void Reset()
{
OnDisable();
OnEnable();
DefaultAnimationCurve();
}
internal static AnimationCurve DefaultAnimationCurve()
{
return AnimationCurve.Linear(-10f, -10f, -1.32f, -1.32f);
}
void Update()
{
Initialize();
GetValues();
// Fail safe in case the curve is deleted / has 0 point
AnimationCurve curve = m_AnimationCurve;
if (curve == null || curve.length == 0)
{
m_Min = 0f;
m_Max = 0f;
for (int i = 0; i < kAdjustmentCurvePrecision; i++)
m_ExposureArray[i] = 0.0f;
}
else
{
m_Min = curve[0].time;
m_Max = curve[curve.length - 1].time;
float step = (m_Max - m_Min) / (kAdjustmentCurvePrecision - 1f);
for (int i = 0; i < kAdjustmentCurvePrecision; i++)
m_ExposureArray[i] = curve.Evaluate(m_Min + step * i);
}
#if UNITY_EDITOR
// handle script recompile
if (EditorApplication.isCompiling && !m_isCompiling)
{
// on compile begin
m_isCompiling = true;
// Release(); no need
return; //
}
else if (!EditorApplication.isCompiling && m_isCompiling)
{
// on compile end
m_isCompiling = false;
}
#endif
Shader.SetGlobalFloatArray(kExposureArrayPropName, m_ExposureArray);
Shader.SetGlobalFloat(kExposureMinPropName, m_Min);
Shader.SetGlobalFloat(kExposureMaxPropName, m_Max);
Shader.SetGlobalInt(kExposureAdjustmentPropName, m_ExposureAdjustmnt ? 1 : 0);
Shader.SetGlobalInt(kToonLightFilterPropName, m_ToonLightHiCutFilter ? 1 : 0);
Shader.SetGlobalInt(kIgonoreVolumeExposurePropName, m_IgnorVolumeExposure ? 1 : 0);
Shader.SetGlobalFloat(kCompensationPorpName, m_Compensation);
}
private void GetValues()
{
}
void EnableSrpCallbacks()
{
if (!m_srpCallbackInitialized)
{
m_srpCallbackInitialized = true;
}
}
void DisableSrpCallbacks()
{
if (m_srpCallbackInitialized)
{
m_srpCallbackInitialized = false;
}
}
void OnEnable()
{
Initialize();
EnableSrpCallbacks();
}
void OnDisable()
{
DisableSrpCallbacks();
Release();
}
void Initialize()
{
if (m_initialized)
{
return;
}
#if UNITY_EDITOR
// initializing renderer can interfere GI baking. so wait until it is completed.
if (EditorApplication.isCompiling)
return;
#endif
if (m_ExposureArray == null || m_ExposureArray.Length != kAdjustmentCurvePrecision)
{
m_ExposureArray = new float[kAdjustmentCurvePrecision];
}
m_initialized = true;
}
void Release()
{
if (m_initialized)
{
m_ExposureArray = null;
Shader.SetGlobalInt(kExposureAdjustmentPropName, 0);
Shader.SetGlobalInt(kToonLightFilterPropName, 0);
}
m_initialized = false;
}
}
}

View File

@@ -1,11 +0,0 @@
fileFormatVersion: 2
guid: db8edd5c572b6e648974dac4815d5619
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -11,18 +11,13 @@ Shader "HDRP/Toon"
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
[HideInInspector] _simpleUI("SimpleUI", Int) = 0 [HideInInspector] _simpleUI("SimpleUI", Int) = 0
// Versioning of material to help for upgrading // Versioning of material to help for upgrading
[HideInInspector] [Enum(OFF, 0, ON, 1)] _isUnityToonshader("Material is touched by Unity Toon Shader", Int) = 1 [HideInInspector] [Enum(Off, 0, ON, 1)] _isUnityToonshader("Material is touched by Unity Toon Shader", Int) = 1
[HideInInspector] _utsVersionX("VersionX", Float) = 0 [HideInInspector] _utsVersionX("VersionX", Float) = 0
[HideInInspector] _utsVersionY("VersionY", Float) = 7 [HideInInspector] _utsVersionY("VersionY", Float) = 7
[HideInInspector] _utsVersionZ("VersionZ", Float) = 6 [HideInInspector] _utsVersionZ("VersionZ", Float) = 6
_HairBlendingMap("HairBlendingMap", 2D) = "black" {}
// Reminder. Color here are in linear but the UI (color picker) do the conversion sRGB to linear
_BaseColor("BaseColor", Color) = (1,1,1,1)
_BaseColorMap("BaseColorMap", 2D) = "white" {}
[HideInInspector] _BaseColorMap_MipInfo("_BaseColorMap_MipInfo", Vector) = (0, 0, 0, 0)
[KeywordEnum(OFF, ST, ANISO, KK, TOON)] _PBR_Mode("PBR MODE", Float) = 0
_Metallic("_Metallic", Range(0.0, 1.0)) = 0 _Metallic("_Metallic", Range(0.0, 1.0)) = 0
_Smoothness("Smoothness", Range(0.0, 1.0)) = 0.5 _Smoothness("Smoothness", Range(0.0, 1.0)) = 0.5
_MaskMap("MaskMap", 2D) = "white" {} _MaskMap("MaskMap", 2D) = "white" {}
@@ -76,7 +71,7 @@ Shader "HDRP/Toon"
_AnisotropyMap("AnisotropyMap", 2D) = "white" {} _AnisotropyMap("AnisotropyMap", 2D) = "white" {}
[ToggleUI] _Use_Anisotropy("Use Anisotropy", int) = 0 [ToggleUI] _Use_Anisotropy("Use Anisotropy", int) = 0
_KKColor("BaseColor", Color) = (1,1,1,1) _KKColor("BaseColor", Color) = (1,1,1,1)
_BSDFContribution("_BSDFContribution", Float) = 0 _BSDFContribution("_BSDFContribution", Range(0.0,1.0)) = 0
[HideInInspector] _DiffusionProfile("Obsolete, kept for migration purpose", Int) = 0 [HideInInspector] _DiffusionProfile("Obsolete, kept for migration purpose", Int) = 0
[HideInInspector] _DiffusionProfileAsset("Diffusion Profile Asset", Vector) = (0, 0, 0, 0) [HideInInspector] _DiffusionProfileAsset("Diffusion Profile Asset", Vector) = (0, 0, 0, 0)
@@ -118,6 +113,8 @@ Shader "HDRP/Toon"
_EmissiveIntensity("Emissive Intensity", Float) = 1 _EmissiveIntensity("Emissive Intensity", Float) = 1
_EmissiveExposureWeight("Emissive Pre Exposure", Range(0.0, 1.0)) = 1.0 _EmissiveExposureWeight("Emissive Pre Exposure", Range(0.0, 1.0)) = 1.0
[Enum(WorldSpace, 0, ObjectSpace, 1)] _ObjectSpaceUVMappingEmissive("Mapping space", Float) = 0.0
_DistortionVectorMap("DistortionVectorMap", 2D) = "black" {} _DistortionVectorMap("DistortionVectorMap", 2D) = "black" {}
[ToggleUI] _DistortionEnable("Enable Distortion", Float) = 0.0 [ToggleUI] _DistortionEnable("Enable Distortion", Float) = 0.0
[ToggleUI] _DistortionDepthTest("Distortion Depth Test Enable", Float) = 1.0 [ToggleUI] _DistortionDepthTest("Distortion Depth Test Enable", Float) = 1.0
@@ -182,7 +179,7 @@ Shader "HDRP/Toon"
[HideInInspector] _AlphaDstBlend("__alphaDst", Float) = 0.0 [HideInInspector] _AlphaDstBlend("__alphaDst", Float) = 0.0
[HideInInspector][ToggleUI] _ZWrite("__zw", Float) = 1.0 [HideInInspector][ToggleUI] _ZWrite("__zw", Float) = 1.0
[HideInInspector][ToggleUI] _TransparentZWrite("_TransparentZWrite", Float) = 0.0 [HideInInspector][ToggleUI] _TransparentZWrite("_TransparentZWrite", Float) = 0.0
[HideInInspector] _CullMode("__cullmode", Float) = 2.0 [Enum(Off, 0, Front, 1, Back, 2)] _CullMode("__cullmode", Float) = 2.0
[HideInInspector] _CullModeForward("__cullmodeForward", Float) = 2.0 // This mode is dedicated to Forward to correctly handle backface then front face rendering thin transparent [HideInInspector] _CullModeForward("__cullmodeForward", Float) = 2.0 // This mode is dedicated to Forward to correctly handle backface then front face rendering thin transparent
[HideInInspector] _TransparentCullMode("_TransparentCullMode", Int) = 2 // Back culling by default [HideInInspector] _TransparentCullMode("_TransparentCullMode", Int) = 2 // Back culling by default
[HideInInspector] _ZTestDepthEqualForOpaque("_ZTestDepthEqualForOpaque", Int) = 4 // Less equal [HideInInspector] _ZTestDepthEqualForOpaque("_ZTestDepthEqualForOpaque", Int) = 4 // Less equal
@@ -243,40 +240,99 @@ Shader "HDRP/Toon"
_EmissionColor("Color", Color) = (1, 1, 1) _EmissionColor("Color", Color) = (1, 1, 1)
// HACK: GI Baking system relies on some properties existing in the shader ("_MainTex", "_Cutoff" and "_Color") for opacity handling, so we need to store our version of those parameters in the hard-coded name the GI baking system recognizes. // HACK: GI Baking system relies on some properties existing in the shader ("_MainTex", "_Cutoff" and "_Color") for opacity handling, so we need to store our version of those parameters in the hard-coded name the GI baking system recognizes.
_MainTex("BaseMap", 2D) = "white" {} _MainTex("Base Map", 2D) = "white" {}
_Color("Color", Color) = (1,1,1,1) _Color("Color", Color) = (1,1,1,1)
_Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5 _Cutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
[ToggleUI] _SupportDecals("Support Decals", Float) = 1.0 [ToggleUI] _SupportDecals("Support Decals", Float) = 1.0
[ToggleUI] _ReceivesSSR("Receives SSR", Float) = 0.0 [ToggleUI] _ReceivesSSR("Receives SSR", Float) = 0.0
[ToggleUI] _ReceivesSSAO("Receives SSAO", Float) = 1.0 [ToggleUI] _ReceivesSSAO("Receives SSAO", Float) = 1.0
_AOMin("_AOMin", Range(0.0, 1.0)) = 0 _AO_Factor("_AO_Factor", Range(0.0, 1.0)) = 1
[ToggleUI] _ReceivesSSGI("Receives SSGI", Float) = 1.0 [ToggleUI] _ReceivesSSGI("Receives SSGI", Float) = 1.0
_GIMultiplier("_GIMultiplier", Range(1.0, 10.0)) = 1 _GI_Factor("_GI_Factor", Range(0.0, 1.0)) = 1
[ToggleUI] _AddPrecomputedVelocity("AddPrecomputedVelocity", Float) = 0.0 [ToggleUI] _AddPrecomputedVelocity("AddPrecomputedVelocity", Float) = 0.0
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// Surface Options
[Enum(Off, 0, On, 1)] _TransparentEnabled("Transparent Mode", int) = 0
[ToggleUI] _AlphaCutoffEnable("Alpha Cutoff Enable", Float) = 0.0
_AlphaCutoff("Alpha Cutoff", Range(0.0, 1.0)) = 0.5
[Enum(Off, 0, FRONT, 1, BACK, 2)] _CullMode("Cull Mode", int) = 2 //OFF/FRONT/BACK
[KeywordEnum(ThreeColorStep, SDF, Ramp)] _Shading_Mode("Shade Grade mode", Float) = 0
[KeywordEnum(Standard, FrontHair, Face, Eye)] _Material_Type("Material Type", int) = 0
[KeywordEnum(Off, Standard, Anisotropy, KKHair, Toon)] _PBR_Mode("PBR Mode", int) = 0
[Toggle] _Receive_Hair_Shadow("Receive HairS hadow", Float) = 0
[ToggleUI] _HairBlendingTarget("Hair Blending Target", Float) = 0
_SurfaceFeatures("Surface Features", Float) = 0
// Shading Color
_BaseColor("BaseColor", Color) = (1,1,1,1)
_BaseColorMap("BaseColorMap", 2D) = "white" {}
[HideInInspector] _BaseColorMap_MipInfo("_BaseColorMap_MipInfo", Vector) = (0, 0, 0, 0)
_1stShadeColor("1st_ShadeColor", Color) = (0, 0, 0, 0)
_1stShadeColorMap("1st_ShadeMap", 2D) = "white" {}
[ToggleUI] _UseBaseAs1st("Use BaseMap as 1st_ShadeMap", Float) = 1
_2ndShadeColor("2nd_ShadeColor", Color) = (0, 0, 0, 0)
_2ndShadeColorMap("2nd_ShadeMap", 2D) = "white" {}
[ToggleUI] _Use1stAs2nd("Use 1st_ShadeMap as 2nd_ShadeMap", Float) = 1
_SDFShadowMap("SDFShadowMap", 2D) = "white" {}
_SDFShadowLevel("SDFShadowLevel", Range(0.0, 1.0)) = 0.25
_SDFSmoothLevel("SDFSmoothGamma", Range(0.0, 0.1)) = 0.02
_SDFHighlightStrength("SDFHighlightStrength", Range(0.0, 5.0)) = 1.25
_SDFHighlightSmoothLevel("SDFHighlightSmoothLevel", Range(0.0, 0.1)) = 0.02
_ShadingGradeMap("ShadingGradeMap", 2DArray) = "white" {}
_ShadingIndex("ShadingIndex", Int) = 0
// Angel Rings
_AngelRingColor("Angel Ring Color", Color) = (1, 1, 1, 1)
_AngelRingColorMap("Angel Ring Color Map", 2D) = "black" {}
_AngelRingIntensity("Angel Ring Intensity", Range(0, 10)) = 1
_AngelRingOffsetU("Angel Ring Offset U", Range(0, 1)) = 0
_AngelRingOffsetV("Angel Ring Offset V", Range(0, 1)) = 0
// Outline
_OutlineWidth("Outline Width", Float) = 0
_OutlineWidthMap("Outline Tex", 2D) = "white" {}
_OutlineColor("Outline Color", Color) = (0.5, 0.5, 0.5, 1)
_OutlineColorMap("Outline Color Map", 2D) = "white" {}
[Toggle(_)] _AlbedoAffectOutline("AlbedoAffectOutline", Float) = 0
_OutlineFadeIn("Outline Fade In", Float) = 50
_OutlineFadeOut("Outline Fade Out", Float) = 100
[Toggle(_)] _UseSmoothedNormal("Use Smoothed Normal", Float) = 0
//[HideInInspector]_Cutoff("Alpha cutoff", Range(0, 1)) = 0.5
_BakedNormal("Baked Normal for Outline", 2D) = "white" {}
[HideInInspector] _utsTechnique("Technique", int) = 0 //DWF [HideInInspector] _utsTechnique("Technique", int) = 0 //DWF
[HideInInspector] _AutoRenderQueue("Automatic Render Queue ", int) = 1 [HideInInspector] _AutoRenderQueue("Automatic Render Queue ", int) = 1
[Enum(OFF, 0, StencilOut, 1, StencilMask, 2)] _StencilMode("StencilMode", int) = 0 [Enum(Off, 0, StencilOut, 1, StencilMask, 2)] _StencilMode("StencilMode", int) = 0
// these are set in UniversalToonGUI.cs in accordance with _StencilMode // these are set in UniversalToonGUI.cs in accordance with _StencilMode
_StencilComp("Stencil Comparison", Float) = 8 _StencilComp("Stencil Comparison", Float) = 8
_StencilNo("Stencil No", Float) = 1 _StencilNo("Stencil No", Float) = 1
_StencilOpPass("Stencil Operation", Float) = 0 _StencilOpPass("Stencil Operation", Float) = 0
_StencilOpFail("Stencil Operation", Float) = 0 _StencilOpFail("Stencil Operation", Float) = 0
[Enum(OFF, 0, ON, 1, ] _TransparentEnabled("Transparent Mode", int) = 0
// DoubleShadeWithFeather // DoubleShadeWithFeather
// 0:_IS_CLIPPING_OFF 1:_IS_CLIPPING_MODE 2:_IS_CLIPPING_TRANSMODE // 0:_IS_CLIPPING_OFF 1:_IS_CLIPPING_MODE 2:_IS_CLIPPING_TRANSMODE
// ShadingGradeMap // ShadingGradeMap
// 0:_IS_TRANSCLIPPING_OFF 1:_IS_TRANSCLIPPING_ON // 0:_IS_TRANSCLIPPING_OFF 1:_IS_TRANSCLIPPING_ON
[Enum(OFF, 0, ON, 1, TRANSMODE, 2)] _ClippingMode("CliippingMode", int) = 0 [Enum(Off, 0, ON, 1, TRANSMODE, 2)] _ClippingMode("CliippingMode", int) = 0
[Enum(OFF, 0, FRONT, 1, BACK, 2)] _CullMode("Cull Mode", int) = 2 //OFF/FRONT/BACK [Enum(Off, 0, ONT, 1)] _ZWriteMode("ZWrite Mode", int) = 1 //OFF/ON
[Enum(OFF, 0, ONT, 1)] _ZWriteMode("ZWrite Mode", int) = 1 //OFF/ON [Enum(Off, 0, ONT, 1)] _ZOverDrawMode("ZOver Draw Mode", Float) = 0 //OFF/ON
[Enum(OFF, 0, ONT, 1)] _ZOverDrawMode("ZOver Draw Mode", Float) = 0 //OFF/ON
_SPRDefaultUnlitColorMask("SPRDefaultUnlit Path Color Mask", int) = 15 _SPRDefaultUnlitColorMask("SPRDefaultUnlit Path Color Mask", int) = 15
[Enum(OFF, 0, FRONT, 1, BACK, 2)] _SRPDefaultUnlitColMode("SPRDefaultUnlit Cull Mode", int) = 1 //OFF/FRONT/BACK [Enum(Off, 0, FRONT, 1, BACK, 2)] _SRPDefaultUnlitColMode("SPRDefaultUnlit Cull Mode", int) = 1 //OFF/FRONT/BACK
// ClippingMask paramaters from Here. // ClippingMask paramaters from Here.
_ClippingMask("ClippingMask", 2D) = "white" {} _ClippingMask("ClippingMask", 2D) = "white" {}
//v.2.0.4 //v.2.0.4
@@ -293,31 +349,13 @@ Shader "HDRP/Toon"
//v.2.0.5 : Clipping/TransClipping for SSAO Problems in PostProcessing Stack. //v.2.0.5 : Clipping/TransClipping for SSAO Problems in PostProcessing Stack.
//If you want to go back the former SSAO results, comment out the below line. //If you want to go back the former SSAO results, comment out the below line.
[HideInInspector] _Color("Color", Color) = (1, 1, 1, 1) [HideInInspector] _Color("Color", Color) = (1, 1, 1, 1)
//
[Toggle(_)] _Is_LightColor_Base("Is_LightColor_Base", Float) = 1 // _NormalMap("NormalMap", 2D) = "bump" {}
_1st_ShadeMap("1st_ShadeMap", 2D) = "white" {}
//v.2.0.5
[Toggle(_)] _Use_BaseAs1st("Use BaseMap as 1st_ShadeMap", Float) = 0
_1st_ShadeColor("1st_ShadeColor", Color) = (1, 1, 1, 1)
[Toggle(_)] _Is_LightColor_1st_Shade("Is_LightColor_1st_Shade", Float) = 1
_2nd_ShadeMap("2nd_ShadeMap", 2D) = "white" {}
//v.2.0.5
[Toggle(_)] _Use_1stAs2nd("Use 1st_ShadeMap as 2nd_ShadeMap", Float) = 0
_2nd_ShadeColor("2nd_ShadeColor", Color) = (1, 1, 1, 1)
[Toggle(_)] _Is_LightColor_2nd_Shade("Is_LightColor_2nd_Shade", Float) = 1
// _NormalMap("NormalMap", 2D) = "bump" {}
_BumpScale("Normal Scale", Range(0, 1)) = 1 _BumpScale("Normal Scale", Range(0, 1)) = 1
[Toggle(_)] _Is_NormalMapToBase("Is_NormalMapToBase", Float) = 0 [Toggle(_)] _Is_NormalMapToBase("Is_NormalMapToBase", Float) = 0
//v.2.0.4.4
[KeywordEnum(NORMAL, SDF)] _Shadow_Mode("Shadow MODE", Float) = 0
_SDFShadowTex("SDFShadowTex", 2D) = "white" {}
_SDFSmoothGamma("SDFSmoothGamma", Range(0.0, 0.1)) = 0.02
_SDFShadowLevel("SDFShadowLevel", Range(0.0, 1.0)) = 0.25
_SDFNoseHighlightCoef("SDFNoseHighlightCoef", Range(0.0, 5.0)) = 1.25
_SDFNoseHighlightSmoothRange("SDFNoseHighlightSmoothRange", Range(0.0, 0.1)) = 0.02
// Hair Shadow // Hair Shadow
[Toggle(_)] _Is_ReceiveHairShadow("Is_ReceiveHairShadow", Float) = 0 [Toggle(_)] _Cast_Hair_Shadow("CastHairShadow", Float) = 0
_ShadowBias("ShadowBias", Range(0.0, 5.0)) = 0.0 _ShadowBias("ShadowBias", Range(0.0, 5.0)) = 0.0
@@ -329,8 +367,7 @@ Shader "HDRP/Toon"
_EyeParallaxAmount("EyeParallaxAmount", Float) = 0.1 _EyeParallaxAmount("EyeParallaxAmount", Float) = 0.1
// Eyebrow Seethrough // Eyebrow Seethrough
[Togle(_)] _Is_EyebrowSeethrough("_Is_EyebrowSeethrough", Float) = 0 _HairBlendingFactor("EyeBrowBlendingFactor", Float) = 0.5
_EyeBrowBlendingFactor("EyeBrowBlendingFactor", Float) = 0.5
//v.2.0.6 //v.2.0.6
_BaseColor_Step("BaseColor_Step", Range(0, 1)) = 0.5 _BaseColor_Step("BaseColor_Step", Range(0, 1)) = 0.5
@@ -347,7 +384,6 @@ Shader "HDRP/Toon"
// //
_Set_1st_ShadePosition("Set_1st_ShadePosition", 2D) = "white" {} _Set_1st_ShadePosition("Set_1st_ShadePosition", 2D) = "white" {}
_Set_2nd_ShadePosition("Set_2nd_ShadePosition", 2D) = "white" {} _Set_2nd_ShadePosition("Set_2nd_ShadePosition", 2D) = "white" {}
_ShadingGradeMap("ShadingGradeMap", 2D) = "white" {}
//v.2.0.6 //v.2.0.6
_Tweak_ShadingGradeMapLevel("Tweak_ShadingGradeMapLevel", Range(-0.5, 0.5)) = 0 _Tweak_ShadingGradeMapLevel("Tweak_ShadingGradeMapLevel", Range(-0.5, 0.5)) = 0
_BlurLevelSGM("Blur Level of ShadingGradeMap", Range(0, 10)) = 0 _BlurLevelSGM("Blur Level of ShadingGradeMap", Range(0, 10)) = 0
@@ -361,7 +397,7 @@ Shader "HDRP/Toon"
_HighColor_Power("HighColor_Power", Range(0, 1)) = 0 _HighColor_Power("HighColor_Power", Range(0, 1)) = 0
[Toggle(_)] _Is_SpecularToHighColor("Is_SpecularToHighColor", Float) = 0 [Toggle(_)] _Is_SpecularToHighColor("Is_SpecularToHighColor", Float) = 0
[Toggle(_)] _Is_BlendAddToHiColor("Is_BlendAddToHiColor", Float) = 0 [Toggle(_)] _Is_BlendAddToHiColor("Is_BlendAddToHiColor", Float) = 0
[Toggle(_)] _Is_BlendAddToRimColor("Is_BlendAddToRimColor", Float) = 1 [Enum(Multiply,0, Add,1)] _Is_BlendAddToRimColor("Is_BlendAddToRimColor", Float) = 1
[Toggle(_)] _Is_UseTweakHighColorOnShadow("Is_UseTweakHighColorOnShadow", Float) = 0 [Toggle(_)] _Is_UseTweakHighColorOnShadow("Is_UseTweakHighColorOnShadow", Float) = 0
_TweakHighColorOnShadow("TweakHighColorOnShadow", Range(0, 1)) = 0 _TweakHighColorOnShadow("TweakHighColorOnShadow", Range(0, 1)) = 0
//HiColorMask //HiColorMask
@@ -387,8 +423,11 @@ Shader "HDRP/Toon"
_Set_RimLightMask("Set_RimLightMask", 2D) = "white" {} _Set_RimLightMask("Set_RimLightMask", 2D) = "white" {}
_Tweak_RimLightMaskLevel("Tweak_RimLightMaskLevel", Range(-1, 1)) = 0 _Tweak_RimLightMaskLevel("Tweak_RimLightMaskLevel", Range(-1, 1)) = 0
// //
_Indirect_Diffuse_Mode("_Indirect_Diffuse_Mode", Float) = 0
_Indirect_Specular_Mode("_Indirect_Specular_Mode", Float) = 0
[Toggle(_)] _MatCap("MatCap", Float) = 0 [Toggle(_)] _MatCap("MatCap", Float) = 0
_MatCap_Sampler("MatCap_Sampler", 2D) = "black" {} _MatCapMap("MatCapMap", 2D) = "black" {}
//v.2.0.6 //v.2.0.6
_BlurLevelMatcap("Blur Level of MatCap_Sampler", Range(0, 10)) = 0 _BlurLevelMatcap("Blur Level of MatCap_Sampler", Range(0, 10)) = 0
_MatCapColor("MatCapColor", Color) = (1, 1, 1, 1) _MatCapColor("MatCapColor", Color) = (1, 1, 1, 1)
@@ -410,21 +449,10 @@ Shader "HDRP/Toon"
[Toggle(_)] _Inverse_MatcapMask("Inverse_MatcapMask", Float) = 0 [Toggle(_)] _Inverse_MatcapMask("Inverse_MatcapMask", Float) = 0
//v.2.0.5 //v.2.0.5
[Toggle(_)] _Is_Ortho("Orthographic Projection for MatCap", Float) = 0 [Toggle(_)] _Is_Ortho("Orthographic Projection for MatCap", Float) = 0
//// Angel Rings
[Toggle(_)] _AngelRing("AngelRing", Float) = 0
_AngelRing_Sampler("AngelRing_Sampler", 2D) = "black" {}
_AngelRing_Color("AngelRing_Color", Color) = (1, 1, 1, 1)
[Toggle(_)] _Is_LightColor_AR("Is_LightColor_AR", Float) = 1
_AR_Intensity("AR_Intensity", Range(0, 100)) = 1
_AR_ShadowIntensity("AR_Intensity", Range(0, 1)) = 0
_AR_OffsetU("AR_OffsetU", Range(0, 0.5)) = 0
_AR_OffsetV("AR_OffsetV", Range(0, 1)) = 0.3
[Toggle(_)] _ARSampler_AlphaOn("ARSampler_AlphaOn", Float) = 0
// //
//v.2.0.7 Emissive //v.2.0.7 Emissive
[KeywordEnum(SIMPLE, ANIMATION)] _EMISSIVE("EMISSIVE MODE", Float) = 0 [KeywordEnum(SIMPLE, ANIMATION)] _EMISSIVE("EMISSIVE MODE", Float) = 0
_Emissive_Tex("Emissive_Tex", 2D) = "white" {}
[HDR]_Emissive_Color("Emissive_Color", Color) = (0, 0, 0, 1)
_Base_Speed("Base_Speed", Float) = 0 _Base_Speed("Base_Speed", Float) = 0
_Scroll_EmissiveU("Scroll_EmissiveU", Range(-1, 1)) = 0 _Scroll_EmissiveU("Scroll_EmissiveU", Range(-1, 1)) = 0
_Scroll_EmissiveV("Scroll_EmissiveV", Range(-1, 1)) = 0 _Scroll_EmissiveV("Scroll_EmissiveV", Range(-1, 1)) = 0
@@ -437,26 +465,6 @@ Shader "HDRP/Toon"
[HDR]_ViewShift("ViewSift", Color) = (0, 0, 0, 1) [HDR]_ViewShift("ViewSift", Color) = (0, 0, 0, 1)
[Toggle(_)] _Is_ViewCoord_Scroll("Is_ViewCoord_Scroll", Float) = 0 [Toggle(_)] _Is_ViewCoord_Scroll("Is_ViewCoord_Scroll", Float) = 0
// //
//Outline
[KeywordEnum(NML, POS)] _OUTLINE("OUTLINE MODE", Float) = 0
_Outline_Width("Outline_Width", Float) = 0
_Farthest_Distance("Farthest_Distance", Float) = 100
_Nearest_Distance("Nearest_Distance", Float) = 0.5
_Outline_Sampler("Outline_Sampler", 2D) = "white" {}
_Outline_Color("Outline_Color", Color) = (0.5, 0.5, 0.5, 1)
[Toggle(_)] _Is_BlendBaseColor("Is_BlendBaseColor", Float) = 0
// ClippingMask paramaters from Here.
[HideInInspector]_Cutoff("Alpha cutoff", Range(0, 1)) = 0.5
// ClippingMask paramaters to here.
//v.2.0.4
[Toggle(_)] _Is_OutlineTex("Is_OutlineTex", Float) = 0
_OutlineTex("OutlineTex", 2D) = "white" {}
//Offset parameter
_Offset_Z("Offset_Camera_Z", Float) = 0
//v.2.0.4.3 Baked Nrmal Texture for Outline
[Toggle(_)] _Is_BakedNormal("Is_BakedNormal", Float) = 0
_BakedNormal("Baked Normal for Outline", 2D) = "white" {}
_UseSmoothedNormal("Use Smoothed Normal", Float) = 0
//GI Intensity //GI Intensity
_ID_Intensity("GI_Intensity", Range(0, 1)) = 1 _ID_Intensity("GI_Intensity", Range(0, 1)) = 1
_IR_Intensity("GI_Intensity", Range(0, 1)) = 1 _IR_Intensity("GI_Intensity", Range(0, 1)) = 1
@@ -495,14 +503,13 @@ Shader "HDRP/Toon"
[Toggle(_)] _RimLightOverridden("Channel mask", Float) = 0 [Toggle(_)] _RimLightOverridden("Channel mask", Float) = 0
_RimLightMaskColor("Channel mask color", Color) = (1, 0, 1, 1) _RimLightMaskColor("Channel mask color", Color) = (1, 0, 1, 1)
[Toggle(_)] _OutlineVisible("Channel mask", Float) = 1
[Toggle(_)] _OutlineOverridden("Channel mask", Float) = 0
_OutlineMaskColor("Channel mask color", Color) = (0, 0, 0, 1)
[Toggle(_)] _ComposerMaskMode("", Float) = 0 [Toggle(_)] _ComposerMaskMode("", Float) = 0
[Enum(None, 0, BaseColor, 1, FirstShade, 2, SecondShade,3, Highlight, 4, AngelRing, 5, RimLight, 6)] _ClippingMatteMode("Clipping Matte Mode", int) = 0 [Enum(None, 0, BaseColor, 1, FirstShade, 2, SecondShade,3, Highlight, 4, AngelRing, 5, RimLight, 6)] _ClippingMatteMode("Clipping Matte Mode", int) = 0
[HideInInspector] emissive("to avoid srp batcher error", Color)= (0, 0, 0, 1) // [HideInInspector] emissive("to avoid srp batcher error", Color)= (0, 0, 0, 1)
[KeywordEnum(NONE, SINGLE, FULL)] _Light_Loop_Mode ("Light Loop Mode", Float) = 2
//
// to here parameters for UTS> // to here parameters for UTS>
} }
@@ -515,8 +522,6 @@ Shader "HDRP/Toon"
// Variant // Variant
//------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------
#pragma shader_feature _HAIR_SHADOWS
#pragma shader_feature_local _ALPHATEST_ON #pragma shader_feature_local _ALPHATEST_ON
#pragma shader_feature_local _DEPTHOFFSET_ON #pragma shader_feature_local _DEPTHOFFSET_ON
#pragma shader_feature_local _DOUBLESIDED_ON #pragma shader_feature_local _DOUBLESIDED_ON
@@ -529,15 +534,6 @@ Shader "HDRP/Toon"
#pragma shader_feature_local _NORMALMAP_TANGENT_SPACE #pragma shader_feature_local _NORMALMAP_TANGENT_SPACE
#pragma shader_feature_local _ _REQUIRE_UV2 _REQUIRE_UV3 #pragma shader_feature_local _ _REQUIRE_UV2 _REQUIRE_UV3
#pragma shader_feature_local _NORMALMAP
#pragma shader_feature_local _DISABLE_DECALS
#pragma shader_feature_local _DISABLE_SSR
#pragma shader_feature_local _MASKMAP
#pragma shader_feature_local _ANISOTROPYMAP
#pragma shader_feature_local _SDFShadow
#pragma shader_feature_local _SPECULARCOLORMAP
#pragma shader_feature_local_fragment _ENABLE_FOG_ON_TRANSPARENT #pragma shader_feature_local_fragment _ENABLE_FOG_ON_TRANSPARENT
#pragma shader_feature_local _TRANSPARENT_WRITES_MOTION_VEC #pragma shader_feature_local _TRANSPARENT_WRITES_MOTION_VEC
@@ -581,7 +577,7 @@ Shader "HDRP/Toon"
// variable declaration // variable declaration
//------------------------------------------------------------------------------------- //-------------------------------------------------------------------------------------
#include "UtsHdrpProperties.hlsl" #include "Packages/com.misaki.hdrp-toon/Runtime/Shaders/Includes/Properties/UtsHdrpProperties.hlsl"
// TODO: // TODO:
// Currently, Lit.hlsl and LitData.hlsl are included for every pass. Split Lit.hlsl in two: // Currently, Lit.hlsl and LitData.hlsl are included for every pass. Split Lit.hlsl in two:
@@ -962,7 +958,7 @@ Shader "HDRP/Toon"
HLSLPROGRAM HLSLPROGRAM
// #pragma multi_compile _ UTS_DEBUG_SHADOWMAP_BINALIZATION //#pragma multi_compile _ UTS_DEBUG_SHADOWMAP_BINALIZATION
#pragma multi_compile _ DEBUG_DISPLAY #pragma multi_compile _ DEBUG_DISPLAY
#pragma multi_compile _ LIGHTMAP_ON #pragma multi_compile _ LIGHTMAP_ON
#pragma multi_compile _ DIRLIGHTMAP_COMBINED #pragma multi_compile _ DIRLIGHTMAP_COMBINED
@@ -971,19 +967,14 @@ Shader "HDRP/Toon"
// Setup DECALS_OFF so the shader stripper can remove variants // Setup DECALS_OFF so the shader stripper can remove variants
#pragma multi_compile DECALS_OFF DECALS_3RT DECALS_4RT #pragma multi_compile DECALS_OFF DECALS_3RT DECALS_4RT
#pragma multi_compile SCREEN_SPACE_SHADOWS_OFF SCREEN_SPACE_SHADOWS_ON #pragma multi_compile SCREEN_SPACE_SHADOWS_OFF SCREEN_SPACE_SHADOWS_ON
// Supported shadow modes per light type
#pragma multi_compile SHADOW_LOW SHADOW_MEDIUM SHADOW_HIGH #pragma multi_compile_fragment USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST
#pragma multi_compile _PBR_Mode_OFF _PBR_Mode_ST _PBR_Mode_ANISO _PBR_Mode_KK _PBR_Mode_TOON
#define LIGHTLOOP_DISABLE_TILE_AND_CLUSTER
// #pragma multi_compile USE_FPTL_LIGHTLIST USE_CLUSTERED_LIGHTLIST
#define AREA_SHADOW_LOW
#define SHADERPASS SHADERPASS_FORWARD #define SHADERPASS SHADERPASS_FORWARD
// In case of opaque we don't want to perform the alpha test, it is done in depth prepass and we use depth equal for ztest (setup from UI) // In case of opaque we don't want to perform the alpha test, it is done in depth prepass and we use depth equal for ztest (setup from UI)
// Don't do it with debug display mode as it is possible there is no depth prepass in this case // Don't do it with debug display mode as it is possible there is no depth prepass in this case
#if !defined(_SURFACE_TYPE_TRANSPARENT) && !defined(DEBUG_DISPLAY) #if !defined(_SURFACE_TYPE_TRANSPARENT) && !defined(DEBUG_DISPLAY)
#define SHADERPASS_FORWARD_BYPASS_ALPHA_TEST #define SHADERPASS_FORWARD_BYPASS_ALPHA_TEST
#endif #endif
#pragma shader_feature _ _SHADINGGRADEMAP
// used in ShadingGradeMap // used in ShadingGradeMap
#pragma shader_feature _IS_TRANSCLIPPING_OFF _IS_TRANSCLIPPING_ON #pragma shader_feature _IS_TRANSCLIPPING_OFF _IS_TRANSCLIPPING_ON
#pragma shader_feature _IS_ANGELRING_OFF _IS_ANGELRING_ON #pragma shader_feature _IS_ANGELRING_OFF _IS_ANGELRING_ON
@@ -997,23 +988,45 @@ Shader "HDRP/Toon"
//Probe volume //Probe volume
#pragma multi_compile PROBE_VOLUMES_OFF PROBE_VOLUMES_L1 PROBE_VOLUMES_L2 #pragma multi_compile PROBE_VOLUMES_OFF PROBE_VOLUMES_L1 PROBE_VOLUMES_L2
// Sample Face Shadow #pragma shader_feature ENABLE_UTS_HAIR_SHAOW
#pragma shader_feature_local _RECEIVE_HAIR_SHADOW #pragma shader_feature ENABLE_UTS_HAIR_BLENDING
// Eye parallax
#pragma shader_feature_local _EYE_PARALLAX
// Eyebrow Blending with hair
#pragma shader_feature_local _EYEBROW_SEETHROUGH
#pragma shader_feature_local_fragment _SHADING_MODE_THREECOLORSTEP _SHADING_MODE_SDF _SHADING_MODE_RAMP
#pragma shader_feature_local_fragment _MATERIAL_TYPE_STANDARD _MATERIAL_TYPE_FRONTHAIR _MATERIAL_TYPE_FACE _MATERIAL_TYPE_EYE
#pragma shader_feature_local_fragment _PBR_MODE_OFF _PBR_MODE_STANDARD _PBR_MODE_ANISOTROPY _PBR_MODE_HAIR _PBR_MODE_TOON
#pragma shader_feature_local_fragment _INDIRECT_DIFFUSE_OFF _INDIRECT_DIFFUSE_IBL _INDIRECT_DIFFUSE_MATCAP _INDIRECT_DIFFUSE_RAMP
#pragma shader_feature_local_fragment _INDIRECT_SPECULAR_OFF _INDIRECT_SPECULAR_IBL _INDIRECT_SPECULAR_MATCAP
#pragma shader_feature_local_fragment _MASK_MAP
#pragma shader_feature_local_fragment _NORMAL_MAP
#pragma shader_feature_local_fragment _ANISOTROPY_MAP
#pragma shader_feature_local_fragment _SPECULAR_COLOR_MAP
#pragma shader_feature_local_fragment _EMISSIVE_COLOR_MAP
#pragma shader_feature_local_fragment _OUTLINE_COLOR_MAP
#pragma shader_feature_local_fragment _RECEIVE_HAIR_SHADOW_ON
#define PUNCTUAL_SHADOW_MEDIUM
#define DIRECTIONAL_SHADOW_MEDIUM
#define AREA_SHADOW_MEDIUM
#ifndef SHADER_STAGE_FRAGMENT
#define SHADOW_LOW
#define USE_FPTL_LIGHTLIST
#endif
#if !defined(_SURFACE_TYPE_TRANSPARENT) && !defined(DEBUG_DISPLAY)
#define SHADERPASS_FORWARD_BYPASS_ALPHA_TEST
#endif
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Lighting.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Lighting.hlsl"
#ifdef DEBUG_DISPLAY #ifdef DEBUG_DISPLAY
# if (SHADER_LIBRARY_VERSION_MAJOR >= 10) #include "Packages/com.misaki.hdrp-toon/Runtime/Shaders/Includes/Common/UtsCommon.hlsl"
#include "DebugDisplay.hlsl" #endif
# else
#include "DebugDisplayHDRP7.hlsl"
# endif
#endif
// The light loop (or lighting architecture) is in charge to: // The light loop (or lighting architecture) is in charge to:
// - Define light list // - Define light list
@@ -1027,20 +1040,17 @@ Shader "HDRP/Toon"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl"
#include "Packages/com.misaki.hdrp-toon/Runtime/Shaders/Includes/Common/UtsHead.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitSharePass.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitSharePass.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitData.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitData.hlsl"
#ifdef DEBUG_DISPLAY #ifdef DEBUG_DISPLAY
# if (SHADER_LIBRARY_VERSION_MAJOR >= 10) #include "Packages/com.misaki.hdrp-toon/Runtime/Shaders/Includes/ShaderPass/ShaderPassForward.hlsl"
#include "ShaderPassForward.hlsl" #else
# else #include "Packages/com.misaki.hdrp-toon/Runtime/Shaders/Includes/Lighting/UtsLightLoop.hlsl"
#include "ShaderPassForwardHDRP7.hlsl" #include "Packages/com.misaki.hdrp-toon/Runtime/Shaders/Includes/ShaderPass/UtsShaderPassForward.hlsl"
# endif #endif
#else
#include "UtsLightLoop.hlsl"
#include "ShaderPassForwardUTS.hlsl"
#endif
#pragma vertex Vert #pragma vertex Vert
#pragma fragment Frag #pragma fragment Frag
@@ -1107,8 +1117,7 @@ Shader "HDRP/Toon"
Tags { "LightMode" = "Outline" } Tags { "LightMode" = "Outline" }
Cull Front Cull Front
Blend SrcAlpha OneMinusSrcAlpha Blend Off
HLSLPROGRAM HLSLPROGRAM
@@ -1117,10 +1126,7 @@ Shader "HDRP/Toon"
#define SHADERPASS SHADERPASS_FORWARD #define SHADERPASS SHADERPASS_FORWARD
#define SHADOW_LOW #define SHADOW_LOW
#define LIGHTLOOP_DISABLE_TILE_AND_CLUSTER #define LIGHTLOOP_DISABLE_TILE_AND_CLUSTER
#define _REQUIRE_UV2
#pragma multi_compile _IS_OUTLINE_CLIPPING_NO _IS_OUTLINE_CLIPPING_YES
#pragma multi_compile _OUTLINE_NML _OUTLINE_POS
#pragma shader_feature _ _IS_CLIPPING_MATTE
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Lighting.hlsl" #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Lighting.hlsl"
@@ -1148,8 +1154,69 @@ Shader "HDRP/Toon"
#include "HDRPToonHead.hlsl" #include "Packages/com.misaki.hdrp-toon/Runtime/Shaders/Includes/Common/UtsHead.hlsl"
#include "HDRPToonOutline.hlsl" #include "Packages/com.misaki.hdrp-toon/Runtime/Shaders/Includes/ShaderPass/HDRPToonOutline.hlsl"
#pragma vertex Vert
#pragma fragment Frag
ENDHLSL
}
Pass
{
Name "HairShadowCaster"
Tags{ "LightMode" = "HairShadowCaster" }
Cull[_CullMode]
ZClip [_ZClip]
ZWrite On
ZTest LEqual
ColorMask 0
HLSLPROGRAM
#define SHADERPASS SHADERPASS_SHADOWS
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitDepthPass.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitData.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl"
#pragma vertex Vert
#pragma fragment Frag
ENDHLSL
}
Pass
{
Name "HairBlendingTarget"
Tags{ "LightMode" = "HairBlendingTarget" }
Cull[_CullMode]
ZClip [_ZClip]
ZWrite On
ZTest LEqual
HLSLPROGRAM
#define SHADERPASS SHADERPASS_FORWARD
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/ShaderPass/LitSharePass.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitData.hlsl"
#ifdef DEBUG_DISPLAY
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Debug/DebugDisplay.hlsl"
#endif
#include "Packages/com.misaki.hdrp-toon/Runtime/Shaders/Includes/Common/UtsHead.hlsl"
#include "Packages/com.misaki.hdrp-toon/Runtime/Shaders/Includes/ShaderPass/HDRPToonHairBlending.hlsl"
#pragma vertex Vert #pragma vertex Vert
#pragma fragment Frag #pragma fragment Frag
@@ -1367,5 +1434,6 @@ Shader "HDRP/Toon"
} }
} }
CustomEditor "UnityEditor.Rendering.Toon.UTS3GUI" //CustomEditor "UnityEditor.Rendering.Toon.UTS3GUI"
CustomEditor "Misaki.HdrpToon.Editor.UTSShaderGUI"
} }

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 98998b9942068044ab680ee5e6485837
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3642d3111f8bccb4180d12b99fa6de71
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -5,6 +5,8 @@
#define inverselerp(a, b, x) saturate(((x) - (a)) / ((b) - (a))) #define inverselerp(a, b, x) saturate(((x) - (a)) / ((b) - (a)))
#define APPLY_WEIGHT(x, y, t) lerp(x, x * y, t)
float2 GetWHRatio() float2 GetWHRatio()
{ {
return float2(_ScreenParams.y / _ScreenParams.x, 1); return float2(_ScreenParams.y / _ScreenParams.x, 1);
@@ -13,12 +15,112 @@ float2 GetWHRatio()
float StepAntiAliasing(float x, float y) float StepAntiAliasing(float x, float y)
{ {
float v = x - y; float v = x - y;
return saturate(v / fwidth(v));//fwidth(x) = abs(ddx(x) + ddy(x)) return saturate(v / fwidth(v) + HALF_MIN); //fwidth(x) = abs(ddx(x) + ddy(x))
}
float Remap(float In, float2 InMinMax, float2 OutMinMax)
{
return OutMinMax.x + (In - InMinMax.x) * (OutMinMax.y - OutMinMax.x) / (InMinMax.y - InMinMax.x);
}
float3 ToonMaping(float3 x)
{
x = x * (2.51 * x + 0.03) / (x * (2.43 * x + 0.59) + 0.14);
return x;
}
float3 GetSmoothedWorldNormal(float2 uv, float3x3 t_tbn)
{
float3 normal = float3(uv, 0);
normal.z = sqrt(1.0 - saturate(dot(normal.xy, normal.xy)));
return mul(normal, t_tbn);
}
float3 UtsComputeDiffuseColor(float3 baseColor, float metallic, float min)
{
#if _PBR_MODE_OFF
return baseColor;
#else
return baseColor * (max(min, 1.0 - metallic));
#endif
}
float3 UtsComputeDiffuseColor(float3 baseColor, float metallic)
{
return UtsComputeDiffuseColor(baseColor, metallic, 0.0);
} }
#define SampleRampSignalLine(texture, u) (SAMPLE_TEXTURE2D_LOD(texture, s_linear_clamp_sampler, float2(u, 0.5), 0)) #define SampleRampSignalLine(texture, u) (SAMPLE_TEXTURE2D_LOD(texture, s_linear_clamp_sampler, float2(u, 0.5), 0))
// Exposure
float3 ApplyCurrentExposureMultiplier(float3 color)
{
return color * lerp(GetCurrentExposureMultiplier(), 1, _ToonIgnoreExposureMultiplier);
}
float3 ConvertFromEV100(float3 EV100)
{
float3 value = pow(2, EV100) * 2.5f;
return value;
}
float3 ConvertToEV100(float3 value)
{
return log2(value * 0.4f);
}
float WeightSample(PositionInputs positionInput)
{
// Center-weighted
const float2 kCenter = _ScreenParams.xy * 0.5;
const float weight = pow(length((kCenter.xy - positionInput.positionSS.xy) / _ScreenParams.xy), 1.0);
return 1.0 - saturate(weight);
}
float3 ApplyCompensation(float3 originalColor)
{
float3 ev100_Color = ConvertToEV100(originalColor) + _ToonEvAdjustmentCompensation * 0.5f;
float3 resultColor = max(0, ConvertFromEV100(ev100_Color));
return resultColor;
}
float3 GetExposureAdjustedColor(float3 originalColor)
{
if (_ToonEvAdjustmentCurve != 0)
{
float3 ev100_Color = ConvertToEV100(originalColor);
ev100_Color = clamp(ev100_Color, _ToonEvAdjustmentValueMin, _ToonEvAdjustmentValueMax);
float3 ev100_remap = (ev100_Color - _ToonEvAdjustmentValueMin) * (128 - 1) / (_ToonEvAdjustmentValueMax - _ToonEvAdjustmentValueMin);
ev100_remap = clamp(ev100_remap, 0.0, 127.0);
int3 ev100_idx = (int3)ev100_remap;
float3 ev100_lerp = ev100_remap - ev100_idx;
float3 ev100_remapped;
ev100_remapped.r = _ToonEvAdjustmentValueArray[ev100_idx.r] + (_ToonEvAdjustmentValueArray[ev100_idx.r + 1] - _ToonEvAdjustmentValueArray[ev100_idx.r]) * ev100_lerp.r;
ev100_remapped.g = _ToonEvAdjustmentValueArray[ev100_idx.g] + (_ToonEvAdjustmentValueArray[ev100_idx.g + 1] - _ToonEvAdjustmentValueArray[ev100_idx.g]) * ev100_lerp.g;
ev100_remapped.b = _ToonEvAdjustmentValueArray[ev100_idx.b] + (_ToonEvAdjustmentValueArray[ev100_idx.b + 1] - _ToonEvAdjustmentValueArray[ev100_idx.b]) * ev100_lerp.b;
float3 resultColor = ConvertFromEV100(ev100_remapped);
return resultColor;
}
else // else is neccessary to avoid warrnings.
{
return originalColor;
}
}
void ApplyExposureAdjustment(inout float3 color)
{
color = GetExposureAdjustedColor(color);
color = ApplyCompensation(color);
}
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
// Transform // Transform
// ---------------------------------------------------------------------------- // ----------------------------------------------------------------------------
@@ -28,7 +130,7 @@ float3 ProjectOnPlane(float3 vec, float3 normal)
return vec - normal * dot(vec, normal); return vec - normal * dot(vec, normal);
} }
float2 Rotate_UV(float2 _uv, float _radian, float2 _piv, float _time) float2 RotateUV(float2 _uv, float _radian, float2 _piv, float _time)
{ {
float RotateUV_ang = _radian; float RotateUV_ang = _radian;
float RotateUV_cos = cos(_time * RotateUV_ang); float RotateUV_cos = cos(_time * RotateUV_ang);
@@ -141,6 +243,4 @@ float3 GetWorldPosFromDepthBuffer(float2 clipPos01, float cameraDepth)
return mul(unity_CameraToWorld, float4(localInvertDepthDirHD, 1.0)).xyz; return mul(unity_CameraToWorld, float4(localInvertDepthDirHD, 1.0)).xyz;
} }
#endif #endif

View File

@@ -0,0 +1,596 @@
//Unity Toon Shader/HDRP
//nobuyuki@unity3d.com
//toshiyuki@unity3d.com (Universal RP/HDRP)
#ifndef UCTS_HDRP_INCLUDED
#define UCTS_HDRP_INCLUDED
#include "Packages/com.misaki.hdrp-toon/Runtime/Shaders/Includes/Common/UtsCommon.hlsl"
#define UTS_LAYER_VISIBILITY
#ifndef DIRECTIONAL
# define DIRECTIONAL
#endif
#define FP_BUFFER 1
#if defined(UNITY_PASS_PREPASSBASE) || defined(UNITY_PASS_DEFERRED) || defined(UNITY_PASS_SHADOWCASTER)
#undef FOG_LINEAR
#undef FOG_EXP
#undef FOG_EXP2
#endif
#define Uts_ColorSpaceDielectricSpec half4(0.04, 0.04, 0.04, 1.0 - 0.04)
#if 1
struct UTSData
{
};
struct UTSSurfaceData
{
uint surfaceFeatures;
real3 baseColor;
real3 firstShadingColor;
real3 secondShadingColor;
real alpha;
float3 normalWS;
real perceptualSmoothness;
real metallic;
real specularOcclusion;
real ambientOcclusion;
real3 specularColor;
float3 geomNormalWS;
float3 tangentWS;
real4 subsurfaceColor;
real anisotropy;
};
struct UtsBSDFData
{
uint surfaceFeatures;
real3 diffuseColor;
real3 firstShadingDiffuseColor;
real3 secondShadingDiffuseColor;
real3 fresnel0;
real fresnel90;
real reflectivity;
real ambientOcclusion;
real specularOcclusion;
real perceptualRoughness;
real3 subsurfaceColor;
float3 geomNormalWS;
float3 normalWS;
float3 tangentWS;
float3 bitangentWS;
real anisotropy;
real roughnessT;
real roughnessB;
};
UTSSurfaceData ConvertSurfaceDataToUTSSurfaceData(SurfaceData surfaceData)
{
UTSSurfaceData output;
ZERO_INITIALIZE(UTSSurfaceData, output);
output.surfaceFeatures = surfaceData.materialFeatures;
output.baseColor = surfaceData.baseColor;
output.alpha = 1.0;
output.normalWS = surfaceData.normalWS;
output.perceptualSmoothness = surfaceData.perceptualSmoothness;
output.metallic = surfaceData.metallic;
output.specularOcclusion = surfaceData.specularOcclusion;
output.ambientOcclusion = surfaceData.ambientOcclusion;
output.specularColor = surfaceData.specularColor;
output.geomNormalWS = surfaceData.geomNormalWS;
output.tangentWS = surfaceData.tangentWS;
output.subsurfaceColor.rgb = surfaceData.transmittanceColor;
output.subsurfaceColor.a = surfaceData.subsurfaceMask;
output.anisotropy = surfaceData.anisotropy;
return output;
}
UTSSurfaceData GetUTSSurfaceData(FragInputs input, float3 V)
{
// Not zero initialized to make sure all fields are set.
UTSSurfaceData output;
output.surfaceFeatures = _SurfaceFeatures;
float4 mainTexture = SAMPLE_TEXTURE2D(_BaseColorMap, sampler_BaseColorMap, TRANSFORM_TEX(input.texCoord0, _BaseColorMap));
output.baseColor = mainTexture.rgb * _BaseColor.rgb;
output.alpha = mainTexture.a;
#if _USE_RAMP_COLOR_MAP_ON
output.firstShadingColor = 0.0;
output.secondShadingColor = 0.0;
#else
float4 firstShadingTexture = SAMPLE_TEXTURE2D(_1stShadeColorMap, sampler_BaseColorMap, TRANSFORM_TEX(input.texCoord0, _BaseColorMap));
output.firstShadingColor = lerp(firstShadingTexture.rgb, mainTexture.rgb, _UseBaseAs1st) * _1stShadeColor.rgb;
#if _SHADING_MODE_STANDARD
float4 secondShadingTexture = SAMPLE_TEXTURE2D(_2ndShadeColorMap, sampler_BaseColorMap, TRANSFORM_TEX(input.texCoord0, _BaseColorMap));
output.secondShadingColor = lerp(secondShadingTexture.rgb, output.firstShadingColor, _Use1stAs2nd) * _2ndShadeColor.rgb;
#else
output.secondShadingColor = 0.0;
#endif
#endif
float4 normalLocal = float4(0, 0, 1.0, 1.0);
#if _NORMAL_MAP
if (_Use_SSSLut)
{
normalLocal = SAMPLE_TEXTURE2D_LOD(_NormalMap, sampler_NormalMap, TRANSFORM_TEX(input.texCoord0, _BaseColorMap), _SSSIntensity);
}
else
{
normalLocal = SAMPLE_TEXTURE2D(_NormalMap, sampler_NormalMap, TRANSFORM_TEX(input.texCoord0, _BaseColorMap));
normalLocal.rgb = UnpackNormalScale(normalLocal, _NormalScale);
}
#endif
float3 normalWS = normalize(mul(normalLocal.rgb, input.tangentToWorld));
#if _PBR_MODE_OFF
float smoothness = 0.0;
float metallic = 0.0;
#else
float smoothness = _Smoothness;
float metallic = _Metallic;
#endif
float ao = 1.0;
float3 specularColor = 1;
float anisotropy = 0;
#ifdef _MASK_MAP
float4 _MaskMap_var = SAMPLE_TEXTURE2D(_MaskMap, sampler_MaskMap, TRANSFORM_TEX(input.texCoord0, _BaseColorMap));
metallic = _MaskMap_var.x;
metallic = lerp(_MetallicRemapMin, _MetallicRemapMax, metallic);
ao = _MaskMap_var.y;
ao = lerp(_AORemapMin, _AORemapMax, ao);
smoothness = _MaskMap_var.w;
smoothness = lerp(_SmoothnessRemapMin, _SmoothnessRemapMax, smoothness);
#endif
#ifdef _ANISOTROPY_MAP
anisotropy = SAMPLE_TEXTURE2D(_AnisotropyMap, sampler_AnisotropyMap, TRANSFORM_TEX(input.texCoord0, _AnisotropyMap)).r;
#if _PBR_Mode_KK
anisotropy += _Anisotropy - 0.5;
#else
anisotropy *= _Anisotropy;
#endif
#else
anisotropy = 1.0;
anisotropy *= _Anisotropy;
#endif
#ifdef _PBR_Mode_KK
metallic = 0.0;
smoothness *=_BSDFContribution;
#endif
#ifdef _PBR_Mode_TOON
#ifdef _SPECULAR_COLOR_MAP
specularColor = SAMPLE_TEXTURE2D(_SpecularColorMap, sampler_SpecularColorMap, TRANSFORM_TEX(input.texCoord0, _BaseColorMap)).rgb * _SpecularColor;
#endif
specularColor = GetSpecularColor(_MainTex_var.rgb * _BaseColor.rgb, metallic);
#endif
output.metallic = metallic;
output.ambientOcclusion = ao;
output.specularOcclusion = GetSpecularOcclusionFromAmbientOcclusion(dot(normalWS, V), ao, PerceptualRoughnessToRoughness(1 - smoothness));
output.perceptualSmoothness = smoothness;
output.normalWS = normalWS;
output.specularColor = specularColor;
output.geomNormalWS = input.tangentToWorld[2];
output.tangentWS = Orthonormalize(input.tangentToWorld[0].rgb, normalWS);
output.subsurfaceColor = SAMPLE_TEXTURE2D(_SSSLutMap, sampler_MainTex, TRANSFORM_TEX(input.texCoord0, _BaseColorMap)) * _SSSIntensity;
output.anisotropy = anisotropy;
return output;
}
UtsBSDFData ConvertUTSSurfaceDataToUTSBSDFData(UTSSurfaceData surfaceData)
{
UtsBSDFData output;
output.surfaceFeatures = surfaceData.surfaceFeatures;
output.diffuseColor = UtsComputeDiffuseColor(surfaceData.baseColor, surfaceData.metallic, 0.05);
output.firstShadingDiffuseColor = UtsComputeDiffuseColor(surfaceData.firstShadingColor, surfaceData.metallic, 0.05);
output.secondShadingDiffuseColor = UtsComputeDiffuseColor(surfaceData.secondShadingColor, surfaceData.metallic, 0.05);
#if _PBR_MODE_OFF
output.fresnel0 = surfaceData.baseColor;
#else
output.fresnel0 = ComputeFresnel0(surfaceData.baseColor, surfaceData.metallic, 0.22);
#endif
output.fresnel90 = ComputeF90(output.fresnel0);
output.reflectivity = (1.0 - 0.22) * (1 - surfaceData.metallic);
output.ambientOcclusion = surfaceData.ambientOcclusion;
output.specularOcclusion = surfaceData.specularOcclusion;
output.perceptualRoughness = PerceptualSmoothnessToPerceptualRoughness(surfaceData.perceptualSmoothness);\
output.subsurfaceColor = surfaceData.subsurfaceColor.rgb * surfaceData.subsurfaceColor.a;
output.normalWS = surfaceData.normalWS;
output.geomNormalWS = surfaceData.geomNormalWS;
output.tangentWS = surfaceData.tangentWS;
output.bitangentWS = normalize(cross(surfaceData.normalWS, surfaceData.tangentWS));
output.anisotropy = surfaceData.anisotropy;
ConvertAnisotropyToRoughness(output.perceptualRoughness, surfaceData.anisotropy, output.roughnessT, output.roughnessB);
return output;
}
PreLightData GetPreLightData_UTS(float3 V, PositionInputs posInput, inout UtsBSDFData bsdfData)
{
PreLightData preLightData;
ZERO_INITIALIZE(PreLightData, preLightData);
float3 N = bsdfData.normalWS;
preLightData.NdotV = dot(N, V);
preLightData.iblPerceptualRoughness = bsdfData.perceptualRoughness;
float clampedNdotV = ClampNdotV(preLightData.NdotV);
// Handle IBL + area light + multiscattering.
// Note: use the not modified by anisotropy iblPerceptualRoughness here.
float specularReflectivity = 1.0;
#if _PBR_MODE_OFF
preLightData.diffuseFGD = 1.0;
preLightData.specularFGD = 1.0;
#else
GetPreIntegratedFGDGGXAndDisneyDiffuse(clampedNdotV, preLightData.iblPerceptualRoughness, bsdfData.fresnel0, bsdfData.fresnel90, preLightData.specularFGD, preLightData.diffuseFGD, specularReflectivity);
#endif
#ifdef LIT_USE_GGX_ENERGY_COMPENSATION
// Ref: Practical multiple scattering compensation for microfacet models.
// We only apply the formulation for metals.
// For dielectrics, the change of reflectance is negligible.
// We deem the intensity difference of a couple of percent for high values of roughness
// to not be worth the cost of another precomputed table.
// Note: this formulation bakes the BSDF non-symmetric!
preLightData.energyCompensation = 1.0 / specularReflectivity - 1.0;
#else
preLightData.energyCompensation = 0.0;
#endif // LIT_USE_GGX_ENERGY_COMPENSATION
float3 iblN;
#if _PBR_MODE_ANISOTROPY
float TdotV = dot(bsdfData.tangentWS, V);
float BdotV = dot(bsdfData.bitangentWS, V);
preLightData.partLambdaV = GetSmithJointGGXAnisoPartLambdaV(TdotV, BdotV, clampedNdotV, bsdfData.roughnessT, bsdfData.roughnessB);
// perceptualRoughness is use as input and output here
GetGGXAnisotropicModifiedNormalAndRoughness(bsdfData.bitangentWS, bsdfData.tangentWS, N, V, bsdfData.anisotropy, preLightData.iblPerceptualRoughness, iblN, preLightData.iblPerceptualRoughness);
#else
preLightData.partLambdaV = GetSmithJointGGXPartLambdaV(clampedNdotV, bsdfData.roughnessT);
iblN = N;
#endif
preLightData.iblR = reflect(-V, iblN);
// Area light
#ifdef USE_DIFFUSE_LAMBERT_BRDF
preLightData.ltcTransformDiffuse = k_identity3x3;
if (HasFlag(bsdfData.materialFeatures, MATERIALFEATUREFLAGS_SSS_DIFFUSE_POWER))
ModifyLambertLTCTransformForDiffusePower(preLightData.ltcTransformDiffuse, GetDiffusePower(bsdfData.diffusionProfileIndex));
#else
preLightData.ltcTransformDiffuse = SampleLtcMatrix(bsdfData.perceptualRoughness, clampedNdotV, LTCLIGHTINGMODEL_DISNEY_DIFFUSE);
#endif
float perceptualRoughnessA = bsdfData.perceptualRoughness;
preLightData.ltcTransformSpecular[0] = SampleLtcMatrix(perceptualRoughnessA, clampedNdotV, LTCLIGHTINGMODEL_GGX);
// Construct a right-handed view-dependent orthogonal basis around the normal
preLightData.orthoBasisViewNormal = GetOrthoBasisViewNormal(V, N, preLightData.NdotV);
return preLightData;
}
void UtsClampRoughness(inout PreLightData preLightData, inout UtsBSDFData bsdfData, float minRoughness)
{
bsdfData.roughnessT = max(minRoughness, bsdfData.roughnessT);
bsdfData.roughnessB = max(minRoughness, bsdfData.roughnessB);
}
// Legacy for compatibility with existing shaders
inline bool IsGammaSpace()
{
#ifdef UNITY_COLORSPACE_GAMMA
return true;
#else
return false;
#endif
}
// normal should be normalized, w=1.0
half3 SHEvalLinearL0L1(half4 normal)
{
half3 x;
// Linear (L1) + constant (L0) polynomial terms
x.r = dot(unity_SHAr, normal);
x.g = dot(unity_SHAg, normal);
x.b = dot(unity_SHAb, normal);
return x;
}
// normal should be normalized, w=1.0
half3 SHEvalLinearL2(half4 normal)
{
half3 x1, x2;
// 4 of the quadratic (L2) polynomials
half4 vB = normal.xyzz * normal.yzzx;
x1.r = dot(unity_SHBr, vB);
x1.g = dot(unity_SHBg, vB);
x1.b = dot(unity_SHBb, vB);
// Final (5th) quadratic (L2) polynomial
half vC = normal.x * normal.x - normal.y * normal.y;
x2 = unity_SHC.rgb * vC;
return x1 + x2;
}
// normal should be normalized, w=1.0
// output in active color space
half3 ShadeSH9(half4 normal)
{
// Linear + constant polynomial terms
half3 res = SHEvalLinearL0L1(normal);
// Quadratic polynomials
res += SHEvalLinearL2(normal);
# ifdef UNITY_COLORSPACE_GAMMA
res = LinearToGammaSpace(res);
# endif
return res;
}
float3 DecodeLightProbe(float3 N) {
return ShadeSH9(float4(N, 1));
}
inline float GammaToLinearSpaceExact(float value)
{
if (value <= 0.04045F)
return value / 12.92F;
else if (value < 1.0F)
return pow((value + 0.055F) / 1.055F, 2.4F);
else
return pow(value, 2.2F);
}
inline float3 GammaToLinearSpace(float3 sRGB)
{
// Approximate version from http://chilliant.blogspot.com.au/2012/08/srgb-approximations-for-hlsl.html?m=1
return sRGB * (sRGB * (sRGB * 0.305306011h + 0.682171111h) + 0.012522878h);
// Precise version, useful for debugging.
//return half3(GammaToLinearSpaceExact(sRGB.r), GammaToLinearSpaceExact(sRGB.g), GammaToLinearSpaceExact(sRGB.b));
}
inline float LinearToGammaSpaceExact(float value)
{
if (value <= 0.0F)
return 0.0F;
else if (value <= 0.0031308F)
return 12.92F * value;
else if (value < 1.0F)
return 1.055F * pow(value, 0.4166667F) - 0.055F;
else
return pow(value, 0.45454545F);
}
inline float3 LinearToGammaSpace(float3 linRGB)
{
linRGB = max(linRGB, float3(0.h, 0.h, 0.h));
// An almost-perfect approximation from http://chilliant.blogspot.com.au/2012/08/srgb-approximations-for-hlsl.html?m=1
return max(1.055h * pow(linRGB, 0.416666667h) - 0.055h, 0.h);
// Exact version, useful for debugging.
//return half3(LinearToGammaSpaceExact(linRGB.r), LinearToGammaSpaceExact(linRGB.g), LinearToGammaSpaceExact(linRGB.b));
}
#if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)
#define UNITY_FOG_COORDS(idx) UNITY_FOG_COORDS_PACKED(idx, float1)
#if (SHADER_TARGET < 30) || defined(SHADER_API_MOBILE)
// mobile or SM2.0: calculate fog factor per-vertex
#define UNITY_TRANSFER_FOG(o,outpos) UNITY_CALC_FOG_FACTOR((outpos).z); o.fogCoord.x = unityFogFactor
#else
// SM3.0 and PC/console: calculate fog distance per-vertex, and fog factor per-pixel
#define UNITY_TRANSFER_FOG(o,outpos) o.fogCoord.x = (outpos).z
#endif
#else
#define UNITY_FOG_COORDS(idx)
#define UNITY_TRANSFER_FOG(o,outpos)
#endif
#define UNITY_FOG_LERP_COLOR(col,fogCol,fogFac) col.rgb = lerp((fogCol).rgb, (col).rgb, saturate(fogFac))
#if defined(FOG_LINEAR) || defined(FOG_EXP) || defined(FOG_EXP2)
#if (SHADER_TARGET < 30) || defined(SHADER_API_MOBILE)
// mobile or SM2.0: fog factor was already calculated per-vertex, so just lerp the color
#define UNITY_APPLY_FOG_COLOR(coord,col,fogCol) UNITY_FOG_LERP_COLOR(col,fogCol,(coord).x)
#else
// SM3.0 and PC/console: calculate fog factor and lerp fog color
#define UNITY_APPLY_FOG_COLOR(coord,col,fogCol) UNITY_CALC_FOG_FACTOR((coord).x); UNITY_FOG_LERP_COLOR(col,fogCol,unityFogFactor)
#endif
#else
#define UNITY_APPLY_FOG_COLOR(coord,col,fogCol)
#endif
#ifdef UNITY_PASS_FORWARDADD
#define UNITY_APPLY_FOG(coord,col) UNITY_APPLY_FOG_COLOR(coord,col,fixed4(0,0,0,0))
#else
#define UNITY_APPLY_FOG(coord,col) UNITY_APPLY_FOG_COLOR(coord,col,unity_FogColor)
#endif
#endif //#if false
#ifdef DIRECTIONAL
#define LIGHTING_COORDS(idx1,idx2) SHADOW_COORDS(idx1)
#define TRANSFER_VERTEX_TO_FRAGMENT(a) TRANSFER_SHADOW(a)
#define LIGHT_ATTENUATION(a) SHADOW_ATTENUATION(a)
#endif
// Transforms 2D UV by scale/bias property
//#define TRANSFORM_TEX(tex,name) (tex.xy * name##_ST.xy + name##_ST.zw)
#define UCTS_TEXTURE2D(tex,name) SAMPLE_TEXTURE2D(tex,sampler##tex,TRANSFORM_TEX(name, tex));
inline float4 UnityObjectToClipPosInstanced(in float3 pos)
{
// return mul(UNITY_MATRIX_VP, mul(unity_ObjectToWorldArray[unity_InstanceID], float4(pos, 1.0)));
// todo. right?
return mul(UNITY_MATRIX_VP, mul(UNITY_MATRIX_M, float4(pos, 1.0)));
}
inline float4 UnityObjectToClipPosInstanced(float4 pos)
{
return UnityObjectToClipPosInstanced(pos.xyz);
}
#define UnityObjectToClipPos UnityObjectToClipPosInstanced
inline float3 UnityObjectToWorldNormal( in float3 norm )
{
#ifdef UNITY_ASSUME_UNIFORM_SCALING
return UnityObjectToWorldDir(norm);
#else
// mul(IT_M, norm) => mul(norm, I_M) => {dot(norm, I_M.col0), dot(norm, I_M.col1), dot(norm, I_M.col2)}
return normalize(mul(norm, (float3x3)UNITY_MATRIX_M));
#endif
}
// normal should be normalized, w=1.0
float3 SHEvalLinearL0L1 (float4 normal)
{
float3 x;
// Linear (L1) + constant (L0) polynomial terms
x.r = dot(unity_SHAr,normal);
x.g = dot(unity_SHAg,normal);
x.b = dot(unity_SHAb,normal);
return x;
}
// normal should be normalized, w=1.0
float3 SHEvalLinearL2 (float4 normal)
{
float3 x1, x2;
// 4 of the quadratic (L2) polynomials
float4 vB = normal.xyzz * normal.yzzx;
x1.r = dot(unity_SHBr,vB);
x1.g = dot(unity_SHBg,vB);
x1.b = dot(unity_SHBb,vB);
// Final (5th) quadratic (L2) polynomial
half vC = normal.x*normal.x - normal.y*normal.y;
x2 = unity_SHC.rgb * vC;
return x1 + x2;
}
// normal should be normalized, w=1.0
// output in active color space
float3 ShadeSH9 (float4 normal)
{
// Linear + constant polynomial terms
float3 res = SHEvalLinearL0L1 (normal);
// Quadratic polynomials
res += SHEvalLinearL2 (normal);
# ifdef UNITY_COLORSPACE_GAMMA
res = LinearToGammaSpace (res);
# endif
return res;
}
float3 SampleBakedGI_UTS(float3 positionRWS, float3 normalWS, float2 uvStaticLightmap, float2 uvDynamicLightmap, bool needToIncludeAPV = false)
{
float3 bakeDiffuseLighting = float3(0, 0, 0);
float3 backBakeDiffuseLighting = float3(0, 0, 0);
float3 backNormalWS = float3(0, 0, 0);
#if !defined(_SURFACE_TYPE_TRANSPARENT) && (SHADERPASS != SHADERPASS_RAYTRACING_INDIRECT) && (SHADERPASS != SHADERPASS_RAYTRACING_GBUFFER)
if (_IndirectDiffuseMode != INDIRECTDIFFUSEMODE_OFF
#if (SHADERPASS == SHADERPASS_GBUFER)
&& _IndirectDiffuseMode != INDIRECTDIFFUSEMODE_MIXED && _ReflectionsMode != REFLECTIONSMODE_MIXED
#endif
)
return bakeDiffuseLighting;
#endif
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
EvaluateLightmap(positionRWS, normalWS, backNormalWS, uvStaticLightmap, uvDynamicLightmap, bakeDiffuseLighting, backBakeDiffuseLighting);
#elif (defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2))
if (needToIncludeAPV)
{
EvaluateAdaptiveProbeVolume(GetAbsolutePositionWS(positionRWS), normalWS, backNormalWS, GetWorldSpaceNormalizeViewDir(positionRWS), 0.0, bakeDiffuseLighting, backBakeDiffuseLighting);
}
#else
EvaluateLightProbeBuiltin(positionRWS, normalWS, backNormalWS, bakeDiffuseLighting, backBakeDiffuseLighting);
#if defined(SHADER_STAGE_RAY_TRACING)
bakeDiffuseLighting *= _RayTracingAmbientProbeDimmer;
backBakeDiffuseLighting *= _RayTracingAmbientProbeDimmer;
#endif
#endif
return bakeDiffuseLighting;
}
float3 SampleBakedGI_UTS_OutLine(float3 positionRWS, float3 normalWS, float2 uvStaticLightmap, float2 uvDynamicLightmap)
{
float3 bakeDiffuseLighting = float3(0, 0, 0);
float3 backBakeDiffuseLighting = float3(0, 0, 0);
float3 backNormalWS = float3(0, 0, 0);
#if defined(LIGHTMAP_ON) || defined(DYNAMICLIGHTMAP_ON)
EvaluateLightmap(positionRWS, normalWS, backNormalWS, uvStaticLightmap, uvDynamicLightmap, bakeDiffuseLighting, backBakeDiffuseLighting);
#elif (defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2))
EvaluateAdaptiveProbeVolume(GetAbsolutePositionWS(positionRWS), normalWS, backNormalWS, GetWorldSpaceNormalizeViewDir(positionRWS), 0.0, bakeDiffuseLighting, backBakeDiffuseLighting);
#else
EvaluateLightProbeBuiltin(positionRWS, normalWS, backNormalWS, bakeDiffuseLighting, backBakeDiffuseLighting);
#if defined(SHADER_STAGE_RAY_TRACING)
bakeDiffuseLighting *= _RayTracingAmbientProbeDimmer;
backBakeDiffuseLighting *= _RayTracingAmbientProbeDimmer;
#endif
#endif
return bakeDiffuseLighting;
}
#endif //#ifndef UCTS_HDRP_INCLUDED

View File

@@ -0,0 +1,258 @@
#ifndef UTS_MATERIAL_EVALUATION
#define UTS_MATERIAL_EVALUATION
#define ColorSpaceDielectricSpec half4(0.22, 0.22, 0.22, 0.779)
struct UtsShadeMask
{
float baseShadeMask;
float firstShadeMask;
};
float RoughnessToBlinnPhongSpecularExponent(float roughness)
{
return clamp(2 * rcp(roughness * roughness) - 2, FLT_EPS, rcp(FLT_EPS));
}
float StepFeatherToon(float value,float step,float feather)
{
return saturate((value - step + feather) / feather);
}
float3 ComputeSpecularTerm(UtsBSDFData bsdfData, PreLightData preLightData, float3 V, float3 L)
{
#ifdef _PBR_MODE_OFF
return 0;
#else
float3 specTerm;
float3 N = bsdfData.normalWS;
float3 H = normalize(L + V);
float NdotL = dot(N, L);
float NdotH = saturate(dot(N, H));
float clampedNdotV = ClampNdotV(preLightData.NdotV);
float clampedNdotL = saturate(NdotL);
float partLambdaV;
float3 DV = 0;
#ifdef _PBR_MODE_STANDARD
partLambdaV = GetSmithJointGGXPartLambdaV(clampedNdotV, bsdfData.roughnessT);
// We use abs(NdotL) to handle the none case of double sided
DV = DV_SmithJointGGX(NdotH, abs(NdotL), clampedNdotV, bsdfData.roughnessT, partLambdaV);
#elif _PBR_MODE_ANISOTROPY
float TdotV = dot(bsdfData.tangentWS, V);
float BdotV = dot(bsdfData.bitangentWS, V);
ConvertAnisotropyToRoughness(bsdfData.perceptualRoughness, bsdfData.anisotropy, bsdfData.roughnessT, bsdfData.roughnessB);
partLambdaV = GetSmithJointGGXAnisoPartLambdaV(TdotV, BdotV, clampedNdotV, bsdfData.roughnessT, bsdfData.roughnessB);
// For anisotropy we must not saturate these values
float TdotH = dot(bsdfData.tangentWS, H);
float TdotL = dot(bsdfData.tangentWS, L);
float BdotH = dot(bsdfData.bitangentWS, H);
float BdotL = dot(bsdfData.bitangentWS, L);
// We use abs(NdotL) to handle the none case of double sided
DV = DV_SmithJointGGXAniso(TdotH, BdotH, NdotH, clampedNdotV, TdotL, BdotL, abs(NdotL), bsdfData.roughnessT, bsdfData.roughnessB, partLambdaV);
#elif _PBR_MODE_HAIR
float3 t = ShiftTangent(bsdfData.bitangentWS, N, bsdfData.anisotropy);
float specularExponent = RoughnessToBlinnPhongSpecularExponent(PerceptualRoughnessToRoughness(bsdfData.coatRoughness));
DV = D_KajiyaKay(t, H, specularExponent);
float normalizeSpec = DV * rcp(specularExponent + 2) * 2 * PI;
//DV *= StepFeatherToon(normalizeSpec,specularStep,specularFeather);
DV = DV * normalizeSpec * _KKColor.rgb;
#elif _PBR_MODE_TOON
float specularExponent = RoughnessToBlinnPhongSpecularExponent(PerceptualRoughnessToRoughness(bsdfData.perceptualRoughness));
DV = pow(NdotH, 5.0 * specularExponent);
DV = StepFeatherToon(DV, _ToonSpecularStep, _ToonSpecularFeather);
//specTerm = pow(NdotH, 5.0 * specularExponent);
//specTerm = StepFeatherToon(specTerm, _ToonSpecularStep, _ToonSpecularFeather);
//return specTerm * ColorSpaceDielectricSpec.rgb * clampedNdotL;
#endif
specTerm = DV * preLightData.specularFGD;
specTerm = specTerm * clampedNdotL;
return specTerm;
#endif
}
half3 FitWithCurveApprox(half NdotL, half Curvature)
{
half curva = (1.0 / mad(Curvature, 0.5 - 0.0625, 0.0625) - 2.0) / (16.0 - 2.0);
half oneMinusCurva = 1.0 - curva;
half3 curve0;
{
half3 rangeMin = half3(0.0, 0.3, 0.3);
half3 rangeMax = half3(1.0, 0.7, 0.7);
half3 offset = half3(0.0, 0.06, 0.06);
half3 t = saturate(mad(NdotL, 1.0 / (rangeMax - rangeMin), (offset + rangeMin) / (rangeMin - rangeMax)));
half3 lowerLine = (t * t) * half3(0.65, 0.5, 0.9);
lowerLine.r += 0.045;
lowerLine.b *= t.b;
half3 m = half3(1.75, 2.0, 1.97);
half3 upperLine = mad(NdotL, m, half3(0.99, 0.99, 0.99) - m);
upperLine = saturate(upperLine);
half3 lerpMin = half3(0.0, 0.35, 0.35);
half3 lerpMax = half3(1.0, 0.7, 0.6);
half3 lerpT = saturate(mad(NdotL, 1.0 / (lerpMax - lerpMin), lerpMin / (lerpMin - lerpMax)));
curve0 = lerp(lowerLine, upperLine, lerpT * lerpT);
}
half3 curve1;
{
half3 m = half3(1.95, 2.0, 2.0);
half3 upperLine = mad(NdotL, m, half3(0.99, 0.99, 1.0) - m);
curve1 = saturate(upperLine);
}
float oneMinusCurva2 = oneMinusCurva * oneMinusCurva;
return lerp(curve0, curve1, mad(oneMinusCurva2, -1.0 * oneMinusCurva2, 1.0));
}
float3 SampleSDFTexture(float3 L, float2 uv, out float angle)
{
float2 right_uv = float2(1 - uv.x, uv.y);
float3 left_SDFTex = SAMPLE_TEXTURE2D(_SDFShadowMap, sampler_SDFShadowMap, uv).rgb;
float3 right_SDFTex = SAMPLE_TEXTURE2D(_SDFShadowMap, sampler_SDFShadowMap, right_uv).rgb;
float2 leftVector = normalize(mul(UNITY_MATRIX_M, float4(1.0, 0.0, 0.0, 0.0)).xz);
float2 forwardVector = normalize(mul(UNITY_MATRIX_M, float4(0.0, 0.0, 1.0, 0.0)).xz);
float2 lightDirection = normalize(L.xz);
angle = saturate(dot(forwardVector, lightDirection) * -1.0 + _SDFShadowLevel);
bool isRightSide = dot(lightDirection, leftVector) > 0;
return isRightSide ? right_SDFTex : left_SDFTex;
}
float GetHairShadow(PositionInputs posInput, float3 L)
{
float shadow = 1.0;
// Push the face fragment view space position towards the light for a little bit
float hairShadowOpacity = saturate(Remap(length(posInput.positionWS), float2(_HairShadowFadeOutDistance, _HairShadowFadeInDistance), float2(0, 1)));
if (hairShadowOpacity > 0.0)
{
float3 viewLightDir = TransformWorldToViewDir(L); // / posInput.deviceDepth; when linearDepth grows large, the movement amount should be lower since we are getting further from the face.
float3 cameraDirOS = normalize(TransformWorldToObject(GetCameraPositionWS()));
float shadowLengthY = _HairShadowDistance * 5.0 * max(0.5, posInput.linearDepth * _HairShadowDistanceScaleFactor) / posInput.linearDepth;
float2 shadowLength = float2(shadowLengthY * 2.0f, shadowLengthY);
float3 camDirOS = normalize(TransformWorldToObject(GetCameraPositionWS()));
float camDirFactor = 1 - smoothstep(0.1, 0.9, camDirOS.y);
shadowLength.y *= camDirFactor;
float2 samplingPoint = (posInput.positionSS + shadowLength * viewLightDir.xy * (_ScreenSize.xy / float2(1920.0f, 1080.0f))) * _ScreenSize.zw; // Use 1080p as the reference resolution to achieve consistent shadow lengths across various screen resolutions.
// Then sample the hair buffer, to see if the fragment lands in shadow.
float2 scaledUVs = samplingPoint * _HairShadowRTHandleScale.xy; // We have to including the scaling factor for our shadow map since we are not going to allocate new texture if the rendering resolution changed.
float hairDepth = SAMPLE_TEXTURE2D(_HairShadowTex, s_trilinear_clamp_sampler, scaledUVs).r;
float shadowMask = posInput.deviceDepth <= hairDepth + _HairShadowDepthBias ? 1 : 0; // Hair < Face means Hair are closer to camera
// Note that we have LinearEyeDepth in the buffer. A comparison of depth is needed so that we don't project the shadow of hair behind the face.
shadow = lerp(1, 1.0 - hairShadowOpacity, shadowMask);
}
return shadow;
}
DirectLighting UtsShadeSurface(PositionInputs posInput, UtsBSDFData bsdfData, PreLightData preLightData, SHADOW_TYPE shadow,
float3 lightColor, float3 V, float3 L, float2 uv,
float diffuseDimmer, float specularDimmer)
{
DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
if (Max3(lightColor.r, lightColor.g, lightColor.b) > 0.0)
{
shadow = smoothstep(0.4, 0.6, shadow);
#if _RECEIVE_HAIR_SHADOW_ON && ENABLE_UTS_HAIR_SHAOW
shadow *= GetHairShadow(posInput, L);
#endif
shadow = saturate(lerp(1.0, shadow, _Set_SystemShadowsToBase));
#if _SHADING_MODE_SDF
float angle;
float3 sdfTexture = SampleSDFTexture(L, uv, angle); // r: sdf shadow, g: sdf highlight, b: fixed shadow
float sdfShadowMask = smoothstep(angle - _SDFSmoothLevel, angle + _SDFSmoothLevel, sdfTexture.r);
float sdfHighlight = sdfTexture.g * _SDFHighlightStrength;
#endif
float3 diffuseTerm = 0.0;
float3 specularTerm = ComputeSpecularTerm(bsdfData, preLightData, V, L);
#if _USE_RAMP_COLOR_MAP_ON
#if _SHADING_MODE_STANDARD
float NdotL = dot(bsdfData.normalWS, L);
float halfLambert = 0.5 * NdotL + 0.5;
float3 rampColor = SAMPLE_TEXTURE2D_ARRAY_LOD(_ShadingRampMap, s_linear_clamp_sampler, float2(halfLambert * shadow.x, 0.0), _ShadingIndex, 0.0).rgb;
diffuseTerm = bsdfData.diffuseColor * rampColor;
specularTerm *= saturate(NdotL) * shadow;
#elif _SHADING_MODE_SDF
float3 rampColor = SAMPLE_TEXTURE2D_ARRAY_LOD(_ShadingRampMap, s_linear_clamp_sampler, float2(sdfShadowMask * shadow.x, 0.0), _ShadingIndex, 0.0).rgb;
diffuseTerm = bsdfData.diffuseColor * rampColor;
specularTerm = (specularTerm + sdfHighlight) * sdfShadowMask * shadow;
#endif
#else
#if _SHADING_MODE_STANDARD
float NdotL = dot(bsdfData.normalWS, L);
float halfLambert = 0.5 * NdotL + 0.5;
float firstColorFeatherForMask = lerp(_1stShadeColorFeather, 0.0, max(_ComposerMaskMode, _FirstShadeOverridden));
float baseShadeMask = saturate((halfLambert - (_1stShadeColorStep - firstColorFeatherForMask)) / (_1stShadeColorStep - (_1stShadeColorStep - firstColorFeatherForMask)));
baseShadeMask *= shadow;
float secondColorFeatherForMask = lerp(_2ndShadeColorFeather, 0.0, max(_SecondShadeOverridden, _ComposerMaskMode));
float firstShadeMask = saturate((halfLambert - (_2ndShadeColorStep - secondColorFeatherForMask)) / (_2ndShadeColorStep - (_2ndShadeColorStep - secondColorFeatherForMask)));
diffuseTerm = lerp(lerp(bsdfData.secondShadingDiffuseColor, bsdfData.firstShadingDiffuseColor, firstShadeMask), bsdfData.diffuseColor, baseShadeMask);
specularTerm *= baseShadeMask;
#elif _SHADING_MODE_SDF
float shadeMask = sdfShadowMask * sdfTexture.b * shadow;
diffuseTerm = lerp(bsdfData.firstShadingDiffuseColor, bsdfData.diffuseColor, shadeMask);
specularTerm = (specularTerm + sdfHighlight) * shadeMask;
#endif
#endif
lighting.diffuse += diffuseTerm * lightColor * diffuseDimmer;
lighting.specular += specularTerm * lightColor * specularDimmer;
}
return lighting;
}
DirectLighting UtsEvaluateAngelRing(FragInputs input, float3 normalWS, float3 V)
{
DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
// Should we scroll the angel ring texture on x?
float3 cameraRight = UNITY_MATRIX_V[0].xyz;
float3 cameraFront = UNITY_MATRIX_V[2].xyz;
float3 upVector = float3(0, 1, 0);
float3 rightAxis = cross(cameraFront, upVector);
float cameraRightMagnitude = sqrt(cameraRight.x * cameraRight.x + cameraRight.y * cameraRight.y + cameraRight.z * cameraRight.z);
float rightAxisMagnitude = sqrt(rightAxis.x * rightAxis.x + rightAxis.y * rightAxis.y + rightAxis.z * rightAxis.z);
float cameraRollCos = dot(rightAxis, cameraRight) / (rightAxisMagnitude * cameraRightMagnitude);
float3 cameraRoll = acos(clamp(cameraRollCos, -1.0, 1.0));
float cameraDir = cameraRight.y < 0 ? -1.0 : 1.0;
float2 arOffsetU = lerp(mul(UNITY_MATRIX_V, float4(normalWS, 0)).xyz, float3(0, 0, 1), _AngelRingOffsetU).xy;
arOffsetU = arOffsetU * 0.5 + 0.5;
float2 arvnRotate = RotateUV(arOffsetU, -(cameraDir * cameraRoll), 0.5, 1.0);
float2 arOffsetUV = float2(arvnRotate.x, lerp(input.texCoord0.y, arvnRotate.y, _AngelRingOffsetV));
float4 angelRingColor = SAMPLE_TEXTURE2D(_AngelRingColorMap, sampler_AngelRingColorMap, TRANSFORM_TEX(arOffsetUV, _AngelRingColorMap)) * _AngelRingColor * _AngelRingIntensity;
float weight = saturate(dot(normalize(V), normalWS));
lighting.specular += angelRingColor.r * angelRingColor.a * weight;
return lighting;
}
#endif

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 69cd89636d3fcd844b1f0381f929ca71
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -2,6 +2,8 @@
//nobuyuki@unity3d.com //nobuyuki@unity3d.com
//toshiyuki@unity3d.com (Universal RP/HDRP) //toshiyuki@unity3d.com (Universal RP/HDRP)
#include "Packages/com.misaki.hdrp-toon/Runtime/HDRP/Shaders/Includes/Common/UtsPBR.hlsl"
#ifndef DirectionalShadowType #ifndef DirectionalShadowType
# if (SHADEROPTIONS_RAYTRACING && (defined(SHADER_API_D3D11) || defined(SHADER_API_D3D12)) && !defined(SHADER_API_XBOXONE) && !defined(SHADER_API_PSSL)) # if (SHADEROPTIONS_RAYTRACING && (defined(SHADER_API_D3D11) || defined(SHADER_API_D3D12)) && !defined(SHADER_API_XBOXONE) && !defined(SHADER_API_PSSL))
# define DirectionalShadowType float3 # define DirectionalShadowType float3
@@ -16,15 +18,9 @@ void UTS_MainLight(LightLoopContext lightLoopContext, FragInputs input, UTSLight
channelOutAlpha = 1.0f; channelOutAlpha = 1.0f;
ZERO_INITIALIZE(UTSData, utsData); ZERO_INITIALIZE(UTSData, utsData);
// We dont have to calculate lighting here if we are using sdf shadow // We don't have to calculate lighting here if we are using sdf shadow
#ifndef _SDFShadow #ifndef _SDFShadow
uint2 tileIndex = uint2(input.positionSS.xy) / GetTileSize();
// input.positionSS is SV_Position
PositionInputs posInput = GetPositionInput(input.positionSS.xy, _ScreenSize.zw, input.positionSS.z, input.positionSS.w, input.positionRWS.xyz, tileIndex);
float2 screenUV = posInput.positionNDC;
#ifdef VARYINGS_NEED_POSITION_WS #ifdef VARYINGS_NEED_POSITION_WS
float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS); float3 V = GetWorldSpaceNormalizeViewDir(input.positionRWS);
#else #else
@@ -32,7 +28,6 @@ void UTS_MainLight(LightLoopContext lightLoopContext, FragInputs input, UTSLight
float3 V = float3(1.0, 1.0, 1.0); // Avoid the division by 0 float3 V = float3(1.0, 1.0, 1.0); // Avoid the division by 0
#endif #endif
PreLightData preLightData = GetPreLightData(V, posInput, bsdfData);
/* todo. these should be put int a struct */ /* todo. these should be put int a struct */
float4 Set_UV0 = input.texCoord0; float4 Set_UV0 = input.texCoord0;
float3x3 tangentTransform = input.tangentToWorld; float3x3 tangentTransform = input.tangentToWorld;
@@ -59,7 +54,7 @@ void UTS_MainLight(LightLoopContext lightLoopContext, FragInputs input, UTSLight
SHADOW_TYPE shadowAttenuation = lightLoopContext.shadowValue; SHADOW_TYPE shadowAttenuation = lightLoopContext.shadowValue;
//v.2.0.6 //v.2.0.6
//Minmimum value is same as the Minimum Feather's value with the Minimum Step's value as threshold. //Minimal value is same as the Minimum Feather's value with the Minimum Step's value as threshold.
#if !defined (UTS_USE_RAYTRACING_SHADOW) #if !defined (UTS_USE_RAYTRACING_SHADOW)
shadowAttenuation *= 2.0f; shadowAttenuation *= 2.0f;
shadowAttenuation = saturate(shadowAttenuation); shadowAttenuation = saturate(shadowAttenuation);
@@ -79,21 +74,18 @@ void UTS_MainLight(LightLoopContext lightLoopContext, FragInputs input, UTSLight
lightDirection = lerp(lightDirection, customLightDirection, _Is_BLD); lightDirection = lerp(lightDirection, customLightDirection, _Is_BLD);
float3 originalLightColor = mainLightColor.rgb; float3 originalLightColor = mainLightColor.rgb;
originalLightColor = lerp(originalLightColor, clamp(originalLightColor, ConvertFromEV100(_ToonEvAdjustmentValueMin), ConvertFromEV100(_ToonEvAdjustmentValueMax)), _ToonEvAdjustmentCurve) * _Light_Intensity_Multiplier; originalLightColor = lerp(originalLightColor, clamp(originalLightColor, ConvertFromEV100(_ToonEvAdjustmentValueMin), ConvertFromEV100(_ToonEvAdjustmentValueMax)), _ToonEvAdjustmentCurve);
float3 lightColor = lerp(max(defaultLightColor, originalLightColor), max(defaultLightColor, saturate(originalLightColor)), max(_Is_Filter_LightColor, _ToonLightHiCutFilter)); float3 lightColor = lerp(max(defaultLightColor, originalLightColor), max(defaultLightColor, saturate(originalLightColor)), max(_Is_Filter_LightColor, _ToonLightHiCutFilter)) * _Light_Intensity_Multiplier;
////// Lighting: ////// Lighting:
float3 halfDirection = normalize(utsData.viewDirection + lightDirection); float3 halfDirection = normalize(utsData.viewDirection + lightDirection);
//v.2.0.5 //v.2.0.5
_Color = _BaseColor; _Color = _BaseColor;
float3 Set_LightColor = lightColor.rgb; float3 Set_LightColor = lightColor.rgb;
float3 Set_BaseColor = lerp((_BaseColor.rgb * _MainTex_var.rgb), ((_BaseColor.rgb * _MainTex_var.rgb) * Set_LightColor), _Is_LightColor_Base); float3 Set_BaseColor = lerp((_BaseColor.rgb * _MainTex_var.rgb), ((_BaseColor.rgb * _MainTex_var.rgb) * Set_LightColor), _Is_LightColor_Base);
float Set_BaseColorAlpha = _BaseColorVisible; float Set_BaseColorAlpha = _BaseColorVisible;
float3 clippingColor = float3(1.0f, 1.0f, 1.0f);
#ifdef _IS_CLIPPING_MATTE #ifdef _IS_CLIPPING_MATTE
if (_ClippingMatteMode == 1) if (_ClippingMatteMode == 1)
{ {
@@ -131,41 +123,6 @@ void UTS_MainLight(LightLoopContext lightLoopContext, FragInputs input, UTSLight
float Set_FinalShadowMask = saturate((1.0 + ((Set_ShadingGrade - (_1st_ShadeColor_Step - _1stColorFeatherForMask)) * -1) / (_1st_ShadeColor_Step - (_1st_ShadeColor_Step - _1stColorFeatherForMask)))); // Base and 1st Shade Mask float Set_FinalShadowMask = saturate((1.0 + ((Set_ShadingGrade - (_1st_ShadeColor_Step - _1stColorFeatherForMask)) * -1) / (_1st_ShadeColor_Step - (_1st_ShadeColor_Step - _1stColorFeatherForMask)))); // Base and 1st Shade Mask
// #ifdef _SDFShadow
// // modified by Suomi @ 20230902 - SDFResult is used to sample SDF texture on the correct side
// float angle;
// bool rightside;
// float2 SDF_UV = TRANSFORM_TEX(Set_UV0, _BaseColorMap);
// float4 sdfRes = SDFResult(rightside, angle, mainLightDirection, SDF_UV);
// Set_FinalShadowMask = max(SDFMask(angle, sdfRes.r), Set_FinalShadowMask);
// Set_BaseColor += _SDFNoseHighlightCoef * SDFNoseHighlight(angle, sdfRes.g, rightside, SDF_UV);
// //#else
// #endif
// #ifdef _RECEIVE_HAIR_SHADOW
// // Push the face fragment view space position towards the light for a little bit
// float2 scrPos = input.positionSS.xy;
// float3 viewLightDir = TransformWorldToViewDir(mainLightDirection) / posInput.linearDepth; // / posInput.deviceDepth; when linearDepth grows large, the movement amount should be lower since we are getting further from the face.
// float2 samplingPoint = (scrPos + _HairShadowDistance * viewLightDir.xy ) * _ScreenSize.zw;
// // Then sample the hair buffer, to see if the fragment lands in shadow.
// float3 hairBuffer = SAMPLE_TEXTURE2D(_HairShadowTex, sampler_HairShadowTex, samplingPoint);
// float hairDepth = hairBuffer.r;
// float depthCorrect = posInput.deviceDepth < hairDepth + 0.0001 ? 1 : 0; // Hair < Face means Hair are closer to camera
// // Note that we have LinearEyeDepth in the buffer. A comparison of depth is needed so that we don't project the shadow of hair behind the face.
// float hairShadow = lerp(0,1,depthCorrect);
// Set_FinalShadowMask = max(hairShadow, Set_FinalShadowMask);
// // Set_FinalShadowMask += SAMPLE_TEXTURE2D(_HairShadowTex, sampler_HairShadowTex, screenUV).r;
// // Set_BaseColor = float3(samplingPoint, 0);
// #endif
#ifdef _IS_CLIPPING_MATTE #ifdef _IS_CLIPPING_MATTE
if (_ClippingMatteMode == 2) if (_ClippingMatteMode == 2)
{ {
@@ -191,7 +148,7 @@ void UTS_MainLight(LightLoopContext lightLoopContext, FragInputs input, UTSLight
//Composition: 3 Basic Colors as Set_FinalBaseColor //Composition: 3 Basic Colors as Set_FinalBaseColor
#ifdef UTS_LAYER_VISIBILITY #ifdef UTS_LAYER_VISIBILITY
float3 Set_FinalBaseColor; float3 diffuseTerm;
{ {
float4 overridingColor = lerp(_SecondShadeMaskColor, float4(_SecondShadeMaskColor.w, _SecondShadeMaskColor.w, _SecondShadeMaskColor.w, 1.0f), _ComposerMaskMode); float4 overridingColor = lerp(_SecondShadeMaskColor, float4(_SecondShadeMaskColor.w, _SecondShadeMaskColor.w, _SecondShadeMaskColor.w, 1.0f), _ComposerMaskMode);
float maskEnabled = max(_SecondShadeOverridden, _ComposerMaskMode); float maskEnabled = max(_SecondShadeOverridden, _ComposerMaskMode);
@@ -200,7 +157,7 @@ void UTS_MainLight(LightLoopContext lightLoopContext, FragInputs input, UTSLight
_Is_LightColor_2nd_Shade_var = lerp(_Is_LightColor_2nd_Shade_var, overridingColor.rgb, maskEnabled); _Is_LightColor_2nd_Shade_var = lerp(_Is_LightColor_2nd_Shade_var, overridingColor.rgb, maskEnabled);
_Is_LightColor_2nd_Shade_var = lerp(_Is_LightColor_2nd_Shade_var, Set_BaseColor, 1.0f - _SecondShadeVisible); _Is_LightColor_2nd_Shade_var = lerp(_Is_LightColor_2nd_Shade_var, Set_BaseColor, 1.0f - _SecondShadeVisible);
float Set_2nd_ShadeAlpha = _SecondShadeVisible; float Set_2nd_ShadeAlpha = _SecondShadeVisible;
Set_FinalBaseColor = diffuseTerm =
lerp(_BaseColor_var, lerp(_BaseColor_var,
lerp(_Is_LightColor_1st_Shade_var, _Is_LightColor_2nd_Shade_var lerp(_Is_LightColor_1st_Shade_var, _Is_LightColor_2nd_Shade_var
, Set_ShadeShadowMask) , Set_ShadeShadowMask)
@@ -221,7 +178,7 @@ void UTS_MainLight(LightLoopContext lightLoopContext, FragInputs input, UTSLight
#endif //#ifdef UTS_LAYER_VISIBILITY #endif //#ifdef UTS_LAYER_VISIBILITY
float albedoIntensity = max(0.1, (1 - sqrt(surfaceData.metallic)) * (1.7 - 0.7 * (1 - sqrt(surfaceData.metallic)))); float albedoIntensity = max(0.1, (1 - sqrt(surfaceData.metallic)) * (1.7 - 0.7 * (1 - sqrt(surfaceData.metallic))));
Set_FinalBaseColor = Set_FinalBaseColor * albedoIntensity; diffuseTerm = diffuseTerm * albedoIntensity;
#ifdef _IS_CLIPPING_MATTE #ifdef _IS_CLIPPING_MATTE
if (_ClippingMatteMode == 3) if (_ClippingMatteMode == 3)
@@ -256,7 +213,7 @@ void UTS_MainLight(LightLoopContext lightLoopContext, FragInputs input, UTSLight
_HighColor_var *= _HighlightVisible; _HighColor_var *= _HighlightVisible;
Set_HighColor = Set_HighColor =
lerp(SATURATE_IF_SDR(Set_FinalBaseColor - _TweakHighColorMask_var), Set_FinalBaseColor, lerp(SATURATE_IF_SDR(diffuseTerm - _TweakHighColorMask_var), diffuseTerm,
lerp(_Is_BlendAddToHiColor, 1.0 lerp(_Is_BlendAddToHiColor, 1.0
, _Is_SpecularToHighColor)); , _Is_SpecularToHighColor));
float3 addColor = float3 addColor =
@@ -312,74 +269,7 @@ void UTS_MainLight(LightLoopContext lightLoopContext, FragInputs input, UTSLight
float3 _RimLight_var = lerp(lerp(Set_HighColor, (Set_HighColor * Set_RimLight), _RimLight), lerp(Set_HighColor, (Set_HighColor + Set_RimLight), _RimLight), _Is_BlendAddToRimColor); float3 _RimLight_var = lerp(lerp(Set_HighColor, (Set_HighColor * Set_RimLight), _RimLight), lerp(Set_HighColor, (Set_HighColor + Set_RimLight), _RimLight), _Is_BlendAddToRimColor);
_RimLight_var = lerp(_RimLight_var, (_RimLight_var * ((1.0 - Set_FinalShadowMask) + (Set_FinalShadowMask * _TweakHighColorOnShadow))), _Is_UseTweakHighColorOnShadow); _RimLight_var = lerp(_RimLight_var, (_RimLight_var * ((1.0 - Set_FinalShadowMask) + (Set_FinalShadowMask * _TweakHighColorOnShadow))), _Is_UseTweakHighColorOnShadow);
#endif #endif
//Matcap
//v.2.0.6 : CameraRolling Stabilizer
//Mirror Script Determination: if sign_Mirror = -1, determine "Inside the mirror".
//v.2.0.7
utsData.signMirror= 0.0; // i.mirrorFlag; todo.
//
float3 _Camera_Right = UNITY_MATRIX_V[0].xyz;
float3 _Camera_Front = UNITY_MATRIX_V[2].xyz;
float3 _Up_Unit = float3(0, 1, 0);
float3 _Right_Axis = cross(_Camera_Front, _Up_Unit);
//Invert if it's "inside the mirror".
if (utsData.signMirror < 0) {
_Right_Axis = -1 * _Right_Axis;
_Rotate_MatCapUV = -1 * _Rotate_MatCapUV;
}
else {
_Right_Axis = _Right_Axis;
}
float _Camera_Right_Magnitude = sqrt(_Camera_Right.x * _Camera_Right.x + _Camera_Right.y * _Camera_Right.y + _Camera_Right.z * _Camera_Right.z);
float _Right_Axis_Magnitude = sqrt(_Right_Axis.x * _Right_Axis.x + _Right_Axis.y * _Right_Axis.y + _Right_Axis.z * _Right_Axis.z);
float _Camera_Roll_Cos = dot(_Right_Axis, _Camera_Right) / (_Right_Axis_Magnitude * _Camera_Right_Magnitude);
utsData.cameraRoll = acos(clamp(_Camera_Roll_Cos, -1, 1));
utsData.cameraDir = _Camera_Right.y < 0 ? -1 : 1;
float _Rot_MatCapUV_var_ang = (_Rotate_MatCapUV * 3.141592654) - utsData.cameraDir * utsData.cameraRoll * _CameraRolling_Stabilizer;
//v.2.0.7
float2 _Rot_MatCapNmUV_var = RotateUV(Set_UV0, (_Rotate_NormalMapForMatCapUV * 3.141592654), float2(0.5, 0.5), 1.0);
//V.2.0.6
float3 _NormalMapForMatCap_var = UnpackNormalScale(tex2D(_NormalMapForMatCap, TRANSFORM_TEX(_Rot_MatCapNmUV_var, _NormalMapForMatCap)), _BumpScaleMatcap);
//v.2.0.5: MatCap with camera skew correction
float3 viewNormal = (mul(UNITY_MATRIX_V, float4(mul(_NormalMapForMatCap_var.rgb, tangentTransform).rgb, 0))).rgb;
float3 NormalBlend_MatcapUV_Detail = viewNormal.rgb * float3(-1, -1, 1);
float3 NormalBlend_MatcapUV_Base = (mul(UNITY_MATRIX_V, float4(utsData.viewDirection, 0)).rgb * float3(-1, -1, 1)) + float3(0, 0, 1);
float3 noSknewViewNormal = NormalBlend_MatcapUV_Base * dot(NormalBlend_MatcapUV_Base, NormalBlend_MatcapUV_Detail) / NormalBlend_MatcapUV_Base.b - NormalBlend_MatcapUV_Detail;
float2 _ViewNormalAsMatCapUV = (lerp(noSknewViewNormal, viewNormal, _Is_Ortho).rg * 0.5) + 0.5;
//
//v.2.0.7
float2 _Rot_MatCapUV_var = RotateUV((0.0 + ((_ViewNormalAsMatCapUV - (0.0 + _Tweak_MatCapUV)) * (1.0 - 0.0)) / ((1.0 - _Tweak_MatCapUV) - (0.0 + _Tweak_MatCapUV))), _Rot_MatCapUV_var_ang, float2(0.5, 0.5), 1.0);
//Invert if it's "inside the mirror".
if (utsData.signMirror < 0) {
_Rot_MatCapUV_var.x = 1 - _Rot_MatCapUV_var.x;
}
else {
_Rot_MatCapUV_var = _Rot_MatCapUV_var;
}
//v.2.0.6 : LOD of Matcap
float4 _MatCap_Sampler_var = tex2Dlod(_MatCap_Sampler, float4(TRANSFORM_TEX(_Rot_MatCapUV_var, _MatCap_Sampler), 0.0, _BlurLevelMatcap));
float4 _Set_MatcapMask_var = tex2D(_Set_MatcapMask, TRANSFORM_TEX(Set_UV0, _Set_MatcapMask));
//
//MatcapMask
float _Tweak_MatcapMaskLevel_var = saturate(lerp(_Set_MatcapMask_var.g, (1.0 - _Set_MatcapMask_var.g), _Inverse_MatcapMask) + _Tweak_MatcapMaskLevel);
float3 _Is_LightColor_MatCap_var = lerp((_MatCap_Sampler_var.rgb * _MatCapColor.rgb), ((_MatCap_Sampler_var.rgb * _MatCapColor.rgb) * Set_LightColor), _Is_LightColor_MatCap);
//v.2.0.6 : ShadowMask on Matcap in Blend mode : multiply
float3 Set_MatCap = lerp(_Is_LightColor_MatCap_var, (_Is_LightColor_MatCap_var * ((1.0 - Set_FinalShadowMask) + (Set_FinalShadowMask * _TweakMatCapOnShadow)) + lerp(Set_HighColor * Set_FinalShadowMask * (1.0 - _TweakMatCapOnShadow), float3(0.0, 0.0, 0.0), _Is_BlendAddToMatCap)), _Is_UseTweakMatCapOnShadow);
//
//v.2.0.6
//Composition: RimLight and MatCap as diffuseTerm
//Broke down diffuseTerm composition
float3 matCapColorOnAddMode = _RimLight_var + Set_MatCap * _Tweak_MatcapMaskLevel_var;
float _Tweak_MatcapMaskLevel_var_MultiplyMode = _Tweak_MatcapMaskLevel_var * lerp(1, (1 - (Set_FinalShadowMask) * (1 - _TweakMatCapOnShadow)), _Is_UseTweakMatCapOnShadow);
float3 matCapColorOnMultiplyMode = Set_HighColor * (1 - _Tweak_MatcapMaskLevel_var_MultiplyMode) + Set_HighColor * Set_MatCap * _Tweak_MatcapMaskLevel_var_MultiplyMode + lerp(float3(0, 0, 0), Set_RimLight, _RimLight);
float3 matCapColorFinal = lerp(matCapColorOnMultiplyMode, matCapColorOnAddMode, _Is_BlendAddToMatCap);
//v.2.0.4 //v.2.0.4
#ifdef _IS_ANGELRING_OFF #ifdef _IS_ANGELRING_OFF
#ifdef _IS_CLIPPING_MATTE #ifdef _IS_CLIPPING_MATTE
@@ -389,10 +279,10 @@ void UTS_MainLight(LightLoopContext lightLoopContext, FragInputs input, UTSLight
return clippingColor; return clippingColor;
} }
#endif // _IS_CLIPPING_MATTE #endif // _IS_CLIPPING_MATTE
float3 diffuseTerm = lerp(_RimLight_var, matCapColorFinal, _MatCap);// Final Composition before Emissive //float3 diffuseTerm = lerp(_RimLight_var, matCapColorFinal, _MatCap);// Final Composition before Emissive
// //
#elif _IS_ANGELRING_ON #elif _IS_ANGELRING_ON
float3 diffuseTerm = lerp(_RimLight_var, matCapColorFinal, _MatCap);// Final Composition before AR //float3 diffuseTerm = lerp(_RimLight_var, matCapColorFinal, _MatCap);// Final Composition before AR
//v.2.0.7 AR Camera Rolling Stabilizer //v.2.0.7 AR Camera Rolling Stabilizer
float3 _AR_OffsetU_var = lerp(mul(UNITY_MATRIX_V, float4(utsData.normalDirection, 0)).xyz, float3(0, 0, 1), _AR_OffsetU); float3 _AR_OffsetU_var = lerp(mul(UNITY_MATRIX_V, float4(utsData.normalDirection, 0)).xyz, float3(0, 0, 1), _AR_OffsetU);
float2 AR_VN = _AR_OffsetU_var.xy * 0.5 + float2(0.5, 0.5); float2 AR_VN = _AR_OffsetU_var.xy * 0.5 + float2(0.5, 0.5);
@@ -434,21 +324,17 @@ void UTS_MainLight(LightLoopContext lightLoopContext, FragInputs input, UTSLight
// PBR---------------------------------------------------------------------------------------------------------------- // PBR----------------------------------------------------------------------------------------------------------------
//Specular Term //Specular Term
float3 specularTerm = ComputeSpecularTerm(V, lightDirection, bsdfData) * (1 - Set_FinalShadowMask) * PI * surfaceData.specularColor * Set_LightColor * utsLightData.specularDimmer; //float3 specularTerm = ComputeSpecularTerm(V, lightDirection, bsdfData) * (1 - Set_FinalShadowMask) * PI * surfaceData.specularColor * Set_LightColor;
float3 specularTerm = 0;
//SSS //SSS
if (_Use_SSSLut == 1) float3 sssColor = SAMPLE_TEXTURE2D(_SSSLutMap, s_linear_clamp_sampler, FitWithCurveApprox(1 - Set_FinalShadowMask, 1));
{ sssColor *= _BaseColor.rgb * _MainTex_var.rgb * Set_LightColor;
float3 sssColor = SAMPLE_TEXTURE2D(_SSSLutMap, s_linear_clamp_sampler, FitWithCurveApprox(1 - Set_FinalShadowMask, 1)); specularTerm *= lerp((1 - Set_FinalShadowMask), FitWithCurveApprox(1 - Set_FinalShadowMask, 1).r, _Use_SSSLut);
sssColor *= _BaseColor.rgb * _MainTex_var.rgb * Set_LightColor; diffuseTerm = lerp(diffuseTerm, sssColor, _Use_SSSLut);
specularTerm *= lerp((1 - Set_FinalShadowMask), FitWithCurveApprox(1 - Set_FinalShadowMask, 1).r, _Use_SSSLut);
diffuseTerm = lerp(diffuseTerm, sssColor, _Use_SSSLut); utsAggregateLighting.directDiffuse += diffuseTerm * utsLightData.diffuseDimmer;
} utsAggregateLighting.directSpecular += specularTerm * utsLightData.specularDimmer;
diffuseTerm = diffuseTerm * utsLightData.diffuseDimmer;
utsAggregateLighting.directDiffuse += diffuseTerm;
utsAggregateLighting.directSpecular += specularTerm;
#endif // _SDFShadow #endif // _SDFShadow
} }

View File

@@ -2,8 +2,10 @@
//nobuyuki@unity3d.com //nobuyuki@unity3d.com
//toshiyuki@unity3d.com (Universal RP/HDRP) //toshiyuki@unity3d.com (Universal RP/HDRP)
#include "PBR.hlsl" #include "Packages/com.misaki.hdrp-toon/Runtime/HDRP/Shaders/Includes/Common/UtsPBR.hlsl"
void UTS_OtherLights(LightLoopContext lightLoopContext, FragInputs input, UTSLightData utsLightData, SurfaceData surfaceData, BSDFData bsdfData, int lightType, float3 i_normalDir, float notDirectional, out float channelOutAlpha, inout UTSAggregateLighting utsAggregateLighting)
void UTS_OtherLights(LightLoopContext lightLoopContext, FragInputs input, UTSLightData utsLightData, SurfaceData surfaceData, BSDFData bsdfData, int lightType, float3 i_normalDir, float notDirectional,
out float channelOutAlpha, inout UTSAggregateLighting utsAggregateLighting)
{ {
channelOutAlpha = 1.0f; channelOutAlpha = 1.0f;
@@ -47,36 +49,41 @@ void UTS_OtherLights(LightLoopContext lightLoopContext, FragInputs input, UTSLig
shadowAttenuation *= 2.0f; shadowAttenuation *= 2.0f;
shadowAttenuation = saturate(shadowAttenuation); shadowAttenuation = saturate(shadowAttenuation);
#endif #endif
float _HalfLambert_var = 0.5 * dot(lerp(i_normalDir, normalDirection, _Is_NormalMapToBase), lightDirection) + 0.5;
//v.2.0.5: //v.2.0.5:
float3 addPassLightColor; float3 addPassLightColor;
if (lightType == GPULIGHTTYPE_TUBE) if (lightType == GPULIGHTTYPE_TUBE)
{ {
addPassLightColor = (0.5f * (preLightData.diffuseFGD * utsLightData.diffuseDimmer) + 0.5f) / PI * additionalLightColor.rgb; addPassLightColor = (0.5f * preLightData.diffuseFGD + 0.5f) / PI * additionalLightColor.rgb;
} }
else if (lightType == GPULIGHTTYPE_RECTANGLE) else if (lightType == GPULIGHTTYPE_RECTANGLE)
{ {
addPassLightColor = ((preLightData.diffuseFGD * utsLightData.diffuseDimmer)) * additionalLightColor.rgb; addPassLightColor = preLightData.diffuseFGD * additionalLightColor.rgb;
} }
else else
{ {
addPassLightColor = (0.5f * dot(lerp(i_normalDir, normalDirection, _Is_NormalMapToBase), lightDirection) + 0.5f) * additionalLightColor.rgb ; addPassLightColor = _HalfLambert_var * additionalLightColor.rgb;
} }
float pureIntencity = max(0.001, (0.299 * additionalLightColor.r + 0.587 * additionalLightColor.g + 0.114 * additionalLightColor.b)); float pureIntensity = max(0.001, (0.299 * additionalLightColor.r + 0.587 * additionalLightColor.g + 0.114 * additionalLightColor.b));
float3 lightColor = max(float3(0.0, 0.0, 0.0), lerp(addPassLightColor, lerp(float3(0.0, 0.0, 0.0), min(addPassLightColor, addPassLightColor / pureIntencity), notDirectional), _Is_Filter_LightColor)); float3 lightColor = max(float3(0.0, 0.0, 0.0), lerp(addPassLightColor, lerp(float3(0.0, 0.0, 0.0), min(addPassLightColor, addPassLightColor / pureIntensity), notDirectional), _Is_Filter_LightColor));
float3 halfDirection = normalize(viewDirection + lightDirection); // has to be recalced here. float3 halfDirection = normalize(viewDirection + lightDirection); // has to be recalced here.
//v.2.0.5: //v.2.0.5:
//v.2.0.5:
_1st_ShadeColor_Step = saturate(_1st_ShadeColor_Step + _StepOffset); _1st_ShadeColor_Step = saturate(_1st_ShadeColor_Step + _StepOffset);
_2nd_ShadeColor_Step = saturate(_2nd_ShadeColor_Step + _StepOffset); _2nd_ShadeColor_Step = saturate(_2nd_ShadeColor_Step + _StepOffset);
// //
//v.2.0.5: If Added lights is directional, set 0 as _LightIntensity //v.2.0.5: If Added lights is directional, set 0 as _LightIntensity
float _LightIntensity = lerp(0, (0.299 * additionalLightColor.r + 0.587 * additionalLightColor.g + 0.114 * additionalLightColor.b), notDirectional); float _LightIntensity = lerp(0, pureIntensity, notDirectional);
//v.2.0.5: Filtering the high intensity zone of PointLights //v.2.0.5: Filtering the high intensity zone of PointLights
float3 Set_LightColor = lightColor; float3 Set_LightColor = lightColor;
// //
float3 Set_BaseColor = lerp((_BaseColor.rgb * _MainTex_var.rgb * _LightIntensity), ((_BaseColor.rgb * _MainTex_var.rgb) * Set_LightColor), _Is_LightColor_Base); float3 Set_BaseColor = lerp((_BaseColor.rgb * _MainTex_var.rgb * _LightIntensity), ((_BaseColor.rgb * _MainTex_var.rgb) * Set_LightColor), _Is_LightColor_Base);
#ifdef UTS_LAYER_VISIBILITY #ifdef UTS_LAYER_VISIBILITY
float Set_BaseColorAlpha = _BaseColorVisible; float Set_BaseColorAlpha = _BaseColorVisible;
float4 overridingColor = lerp(_BaseColorMaskColor, float4(_BaseColorMaskColor.w, _BaseColorMaskColor.w, _BaseColorMaskColor.w, 1.0f), _ComposerMaskMode); float4 overridingColor = lerp(_BaseColorMaskColor, float4(_BaseColorMaskColor.w, _BaseColorMaskColor.w, _BaseColorMaskColor.w, 1.0f), _ComposerMaskMode);
@@ -85,6 +92,7 @@ void UTS_OtherLights(LightLoopContext lightLoopContext, FragInputs input, UTSLig
Set_BaseColor *= _BaseColorVisible; Set_BaseColor *= _BaseColorVisible;
#endif //#ifdef UTS_LAYER_VISIBILITY #endif //#ifdef UTS_LAYER_VISIBILITY
//v.2.0.5 //v.2.0.5
float4 _1st_ShadeMap_var = lerp(SAMPLE_TEXTURE2D(_1st_ShadeMap, sampler_BaseColorMap, TRANSFORM_TEX(Set_UV0, _1st_ShadeMap)), _MainTex_var, _Use_BaseAs1st); float4 _1st_ShadeMap_var = lerp(SAMPLE_TEXTURE2D(_1st_ShadeMap, sampler_BaseColorMap, TRANSFORM_TEX(Set_UV0, _1st_ShadeMap)), _MainTex_var, _Use_BaseAs1st);
float3 Set_1st_ShadeColor = lerp((_1st_ShadeColor.rgb * _1st_ShadeMap_var.rgb * _LightIntensity), ((_1st_ShadeColor.rgb * _1st_ShadeMap_var.rgb) * Set_LightColor), _Is_LightColor_1st_Shade); float3 Set_1st_ShadeColor = lerp((_1st_ShadeColor.rgb * _1st_ShadeMap_var.rgb * _LightIntensity), ((_1st_ShadeColor.rgb * _1st_ShadeMap_var.rgb) * Set_LightColor), _Is_LightColor_1st_Shade);
@@ -97,6 +105,7 @@ void UTS_OtherLights(LightLoopContext lightLoopContext, FragInputs input, UTSLig
} }
float Set_1st_ShadeAlpha = _FirstShadeVisible; float Set_1st_ShadeAlpha = _FirstShadeVisible;
#endif //#ifdef UTS_LAYER_VISIBILITY //v.2.0.5 #endif //#ifdef UTS_LAYER_VISIBILITY //v.2.0.5
//v.2.0.5 //v.2.0.5
float4 _2nd_ShadeMap_var = lerp(SAMPLE_TEXTURE2D(_2nd_ShadeMap, sampler_BaseColorMap, TRANSFORM_TEX(Set_UV0, _2nd_ShadeMap)), _1st_ShadeMap_var, _Use_1stAs2nd); float4 _2nd_ShadeMap_var = lerp(SAMPLE_TEXTURE2D(_2nd_ShadeMap, sampler_BaseColorMap, TRANSFORM_TEX(Set_UV0, _2nd_ShadeMap)), _1st_ShadeMap_var, _Use_1stAs2nd);
float3 Set_2nd_ShadeColor = lerp((_2nd_ShadeColor.rgb * _2nd_ShadeMap_var.rgb * _LightIntensity), ((_2nd_ShadeColor.rgb * _2nd_ShadeMap_var.rgb) * Set_LightColor), _Is_LightColor_2nd_Shade); float3 Set_2nd_ShadeColor = lerp((_2nd_ShadeColor.rgb * _2nd_ShadeMap_var.rgb * _LightIntensity), ((_2nd_ShadeColor.rgb * _2nd_ShadeMap_var.rgb) * Set_LightColor), _Is_LightColor_2nd_Shade);
@@ -110,8 +119,6 @@ void UTS_OtherLights(LightLoopContext lightLoopContext, FragInputs input, UTSLig
} }
#endif //#ifdef UTS_LAYER_VISIBILITY #endif //#ifdef UTS_LAYER_VISIBILITY
float _HalfLambert_var = 0.5 * dot(lerp(i_normalDir, normalDirection, _Is_NormalMapToBase), lightDirection) + 0.5;
// //v.2.0.5: // //v.2.0.5:
//SGM //SGM
//v.2.0.6 //v.2.0.6
@@ -119,20 +126,19 @@ void UTS_OtherLights(LightLoopContext lightLoopContext, FragInputs input, UTSLig
//v.2.0.6 //v.2.0.6
//Minmimum value is same as the Minimum Feather's value with the Minimum Step's value as threshold. //Minmimum value is same as the Minimum Feather's value with the Minimum Step's value as threshold.
float _SystemShadowsLevel_var = (shadowAttenuation*0.5)+0.5+_Tweak_SystemShadowsLevel > 0.001 ? (shadowAttenuation*0.5)+0.5+_Tweak_SystemShadowsLevel : 0.0001; float _SystemShadowsLevel_var = (shadowAttenuation * 0.5) + 0.5 + _Tweak_SystemShadowsLevel > 0.001 ? (shadowAttenuation * 0.5) + 0.5 + _Tweak_SystemShadowsLevel : 0.0001;
float _ShadingGradeMapLevel_var = _ShadingGradeMap_var.r < 0.95 ? _ShadingGradeMap_var.r + _Tweak_ShadingGradeMapLevel : 1; float _ShadingGradeMapLevel_var = _ShadingGradeMap_var.r < 0.95 ? _ShadingGradeMap_var.r + _Tweak_ShadingGradeMapLevel : 1;
float Set_ShadingGrade = saturate(_ShadingGradeMapLevel_var)*lerp( _HalfLambert_var, (_HalfLambert_var*saturate(_SystemShadowsLevel_var)), _Set_SystemShadowsToBase ); float Set_ShadingGrade = saturate(_ShadingGradeMapLevel_var)*lerp( _HalfLambert_var, (_HalfLambert_var * saturate(_SystemShadowsLevel_var)), _Set_SystemShadowsToBase );
//float Set_ShadingGrade = saturate(_ShadingGradeMapLevel_var) * lerp(_HalfLambert_var, (_HalfLambert_var * saturate(1.0 + _Tweak_SystemShadowsLevel)), _Set_SystemShadowsToBase); //float Set_ShadingGrade = saturate(_ShadingGradeMapLevel_var) * lerp(_HalfLambert_var, (_HalfLambert_var * saturate(1.0 + _Tweak_SystemShadowsLevel)), _Set_SystemShadowsToBase);
float _1stColorFeatherForMask = lerp(_1st_ShadeColor_Feather, 0.0f, max(_FirstShadeOverridden, _ComposerMaskMode)); float _1stColorFeatherForMask = lerp(_1st_ShadeColor_Feather, 0.0f, max(_FirstShadeOverridden, _ComposerMaskMode));
float _2ndColorFeatherForMask = lerp(_2nd_ShadeColor_Feather, 0.0f, max(_SecondShadeOverridden, _ComposerMaskMode)); float _2ndColorFeatherForMask = lerp(_2nd_ShadeColor_Feather, 0.0f, max(_SecondShadeOverridden, _ComposerMaskMode));
// //
float Set_FinalShadowMask = saturate((1.0 + ((Set_ShadingGrade - (_1st_ShadeColor_Step - _1stColorFeatherForMask)) * (0.0 - 1.0)) / (_1st_ShadeColor_Step - (_1st_ShadeColor_Step - _1stColorFeatherForMask)))); float Set_FinalShadowMask = saturate(1.0 + (Set_ShadingGrade - (_1st_ShadeColor_Step - _1stColorFeatherForMask)) * (0.0 - 1.0) / (_1st_ShadeColor_Step - (_1st_ShadeColor_Step - _1stColorFeatherForMask)));
float Set_ShadeShadowMask = saturate((1.0 + ((Set_ShadingGrade - (_2nd_ShadeColor_Step - _2ndColorFeatherForMask)) * (0.0 - 1.0)) / (_2nd_ShadeColor_Step - (_2nd_ShadeColor_Step - _2ndColorFeatherForMask)))); // 1st and 2nd Shades Mask float Set_ShadeShadowMask = saturate(1.0 + (Set_ShadingGrade - (_2nd_ShadeColor_Step - _2ndColorFeatherForMask)) * (0.0 - 1.0) / (_2nd_ShadeColor_Step - (_2nd_ShadeColor_Step - _2ndColorFeatherForMask))); // 1st and 2nd Shades Mask
//SGM //SGM
@@ -147,13 +153,15 @@ void UTS_OtherLights(LightLoopContext lightLoopContext, FragInputs input, UTSLig
Set_ShadeShadowMask Set_ShadeShadowMask
), ),
Set_FinalShadowMask); Set_FinalShadowMask);
#ifdef UTS_LAYER_VISIBILITY #ifdef UTS_LAYER_VISIBILITY
float Set_2nd_ShadeAlpha = _SecondShadeVisible; float Set_2nd_ShadeAlpha = _SecondShadeVisible;
channelOutAlpha = channelOutAlpha =
lerp(Set_BaseColorAlpha, lerp(Set_1st_ShadeAlpha, Set_2nd_ShadeAlpha, Set_ShadeShadowMask), Set_FinalShadowMask); lerp(Set_BaseColorAlpha, lerp(Set_1st_ShadeAlpha, Set_2nd_ShadeAlpha, Set_ShadeShadowMask), Set_FinalShadowMask);
#endif #endif
//v.2.0.6: Add HighColor if _Is_Filter_HiCutPointLightColor is False //v.2.0.6: Add HighColor if _Is_Filter_HiCutPointLightColor is False
float4 _Set_HighColorMask_var = tex2D(_Set_HighColorMask, TRANSFORM_TEX(Set_UV0, _Set_HighColorMask)); float4 _Set_HighColorMask_var = tex2D(_Set_HighColorMask, TRANSFORM_TEX(Set_UV0, _Set_HighColorMask));
float _Specular_var = 0.5 * dot(halfDirection, lerp(i_normalDir, normalDirection, _Is_NormalMapToHighColor)) + 0.5; // Specular float _Specular_var = 0.5 * dot(halfDirection, lerp(i_normalDir, normalDirection, _Is_NormalMapToHighColor)) + 0.5; // Specular
float _TweakHighColorMask_var = (saturate((_Set_HighColorMask_var.g + _Tweak_HighColorMaskLevel)) * lerp((1.0 - step(_Specular_var, (1.0 - pow(_HighColor_Power, 5)))), pow(_Specular_var, exp2(lerp(11, 1, _HighColor_Power))), _Is_SpecularToHighColor)); float _TweakHighColorMask_var = (saturate((_Set_HighColorMask_var.g + _Tweak_HighColorMaskLevel)) * lerp((1.0 - step(_Specular_var, (1.0 - pow(_HighColor_Power, 5)))), pow(_Specular_var, exp2(lerp(11, 1, _HighColor_Power))), _Is_SpecularToHighColor));
@@ -176,8 +184,8 @@ void UTS_OtherLights(LightLoopContext lightLoopContext, FragInputs input, UTSLig
#ifdef UTS_LAYER_VISIBILITY #ifdef UTS_LAYER_VISIBILITY
float4 overrideColor = lerp(_HighlightMaskColor, float4(_HighlightMaskColor.w, _HighlightMaskColor.w, _HighlightMaskColor.w, 1.0f), _ComposerMaskMode); float4 overrideColor = lerp(_HighlightMaskColor, float4(_HighlightMaskColor.w, _HighlightMaskColor.w, _HighlightMaskColor.w, 1.0f), _ComposerMaskMode);
float isMaskEnabled = max(_HighlightOverridden, _ComposerMaskMode); float isMaskEnabled = max(_HighlightOverridden, _ComposerMaskMode);
_HighColor_var *= _TweakHighColorMask_var; //_HighColor_var *= _TweakHighColorMask_var;
_HighColor_var *= _HighlightVisible; //_HighColor_var *= _HighlightVisible;
float4 overridingRimColor = lerp(_RimLightMaskColor, float4(_RimLightMaskColor.w, _RimLightMaskColor.w, _RimLightMaskColor.w, 1.0f), _ComposerMaskMode); float4 overridingRimColor = lerp(_RimLightMaskColor, float4(_RimLightMaskColor.w, _RimLightMaskColor.w, _RimLightMaskColor.w, 1.0f), _ComposerMaskMode);
float maskRimEnabled = max(_RimLightOverridden, _ComposerMaskMode); float maskRimEnabled = max(_RimLightOverridden, _ComposerMaskMode);
@@ -188,10 +196,11 @@ void UTS_OtherLights(LightLoopContext lightLoopContext, FragInputs input, UTSLig
if (any(Set_RimLight) * maskRimEnabled) if (any(Set_RimLight) * maskRimEnabled)
{ {
_HighColor_var = overridingRimColor; //_HighColor_var = overridingRimColor;
channelOutAlpha = Set_RimLightAlpha; channelOutAlpha = Set_RimLightAlpha;
} }
/*
diffuseTerm = diffuseTerm =
lerp(saturate(diffuseTerm - _TweakHighColorMask_var), diffuseTerm, lerp(saturate(diffuseTerm - _TweakHighColorMask_var), diffuseTerm,
lerp(_Is_BlendAddToHiColor, 1.0 lerp(_Is_BlendAddToHiColor, 1.0
@@ -205,6 +214,7 @@ void UTS_OtherLights(LightLoopContext lightLoopContext, FragInputs input, UTSLig
diffuseTerm = lerp(diffuseTerm, overrideColor, isMaskEnabled); diffuseTerm = lerp(diffuseTerm, overrideColor, isMaskEnabled);
channelOutAlpha = _HighlightVisible; channelOutAlpha = _HighlightVisible;
} }
*/
// Rim light // Rim light
diffuseTerm = lerp(lerp(diffuseTerm, (diffuseTerm * Set_RimLight), _RimLight), lerp(diffuseTerm, (diffuseTerm + Set_RimLight), _RimLight), _Is_BlendAddToRimColor); diffuseTerm = lerp(lerp(diffuseTerm, (diffuseTerm * Set_RimLight), _RimLight), lerp(diffuseTerm, (diffuseTerm + Set_RimLight), _RimLight), _Is_BlendAddToRimColor);
@@ -224,22 +234,25 @@ void UTS_OtherLights(LightLoopContext lightLoopContext, FragInputs input, UTSLig
//Specular Term //Specular Term
float3 specularTerm = 0; float3 specularTerm = 0;
if(lightType == GPULIGHTTYPE_RECTANGLE || lightType == GPULIGHTTYPE_TUBE)
{ #ifndef _PBR_Mode_OFF
specularTerm = preLightData.specularFGD * Set_LightColor * utsLightData.specularDimmer; if(lightType == GPULIGHTTYPE_RECTANGLE || lightType == GPULIGHTTYPE_TUBE)
#ifdef _PBR_Mode_TOON {
specularTerm = StepFeatherToon(specularTerm, _ToonSpecularStep, _ToonSpecularFeather); specularTerm = preLightData.specularFGD * Set_LightColor;
#endif #ifdef _PBR_Mode_TOON
} specularTerm = StepFeatherToon(specularTerm, _ToonSpecularStep, _ToonSpecularFeather);
else #endif
{ }
specularTerm = ComputeSpecularTerm(V, lightDirection, bsdfData) * Set_LightColor * utsLightData.specularDimmer; else
} {
//specularTerm = ComputeSpecularTerm(V, lightDirection, bsdfData) * Set_LightColor;
}
#endif
specularTerm = specularTerm * (1.0 - Set_FinalShadowMask) * PI * surfaceData.specularColor; specularTerm = specularTerm * (1.0 - Set_FinalShadowMask) * PI * surfaceData.specularColor;
diffuseTerm = diffuseTerm * albedoIntensity; diffuseTerm = diffuseTerm * albedoIntensity;
utsAggregateLighting.directDiffuse += diffuseTerm; utsAggregateLighting.directDiffuse += diffuseTerm * utsLightData.diffuseDimmer;
utsAggregateLighting.directSpecular += specularTerm; utsAggregateLighting.directSpecular += specularTerm * utsLightData.specularDimmer;
#endif // _SDFShadow #endif // _SDFShadow
} }

View File

@@ -0,0 +1,220 @@
#ifndef UTS_AREA_LIGHT_INLCUDE
#define UTS_AREA_LIGHT_INLCUDE
// The output is *not* normalized by the factor of 1/TWO_PI (this is done by the PolygonFormFactor function).
real3 UTS_ComputeEdgeFactor(real3 V1, real3 V2)
{
real V1oV2 = dot(V1, V2);
real3 V1xV2 = cross(V1, V2); // Plane normal (tangent to the unit sphere)
real sqLen = saturate(1 - V1oV2 * V1oV2); // length(V1xV2) = abs(sin(angle))
real rcpLen = rsqrt(max(FLT_EPS, sqLen)); // Make sure it is finite
#if 0
real y = rcpLen * acos(V1oV2);
#else
// Let y[x_] = ArcCos[x] / Sqrt[1 - x^2].
// Range reduction: since ArcCos[-x] == Pi - ArcCos[x], we only need to consider x on [0, 1].
real x = abs(V1oV2);
// Limit[y[x], x -> 1] == 1,
// Limit[y[x], x -> 0] == Pi/2.
// The approximation is exact at the endpoints of [0, 1].
// Max. abs. error on [0, 1] is 1.33e-6 at x = 0.0036.
// Max. rel. error on [0, 1] is 8.66e-7 at x = 0.0037.
real y = HALF_PI + x * (-0.99991 + x * (0.783393 + x * (-0.649178 + x * (0.510589 + x * (-0.326137 + x * (0.137528 + x * -0.0270813))))));
if (V1oV2 < 0)
{
y = rcpLen * PI - y;
}
#endif
return V1xV2 * y;
}
// Input: 3-5 vertices in the coordinate frame centered at the shaded point.
// Output: signed vector irradiance.
// No horizon clipping is performed.
real3 UTS_PolygonFormFactor(real4x3 L, real3 L4, uint n, bool isDiffuse)
{
// The length cannot be zero since we have already checked
// that the light has a non-zero effective area,
// and thus its plane cannot pass through the origin.
L[0] = normalize(L[0]);
L[1] = normalize(L[1]);
L[2] = normalize(L[2]);
switch (n)
{
case 3:
L[3] = L[0];
break;
case 4:
L[3] = normalize(L[3]);
L4 = L[0];
break;
case 5:
L[3] = normalize(L[3]);
L4 = normalize(L4);
break;
}
// If the magnitudes of a pair of edge factors are
// nearly the same, catastrophic cancellation may occur:
// https://en.wikipedia.org/wiki/Catastrophic_cancellation
// For the same reason, the value of the cross product of two
// nearly collinear vectors is prone to large errors.
// Therefore, the algorithm is inherently numerically unstable
// for area lights that shrink to a line (or a point) after
// projection onto the unit sphere.
real3 F = UTS_ComputeEdgeFactor(L[0], L[1]);
F += UTS_ComputeEdgeFactor(L[1], L[2]);
F += UTS_ComputeEdgeFactor(L[2], L[3]);
if (n >= 4)
F += UTS_ComputeEdgeFactor(L[3], L4);
if (n == 5)
F += UTS_ComputeEdgeFactor(L4, L[0]);
return lerp(INV_TWO_PI * F, HALF_PI * F, isDiffuse); // The output may be projected onto the tangent plane (F.z) to yield signed irradiance.
}
// See "Real-Time Area Lighting: a Journey from Research to Production", slide 102.
// Turns out, despite the authors claiming that this function "calculates an approximation of
// the clipped sphere form factor", that is simply not true.
// First of all, above horizon, the function should then just return 'F.z', which it does not.
// Secondly, if we use the correct function called DiffuseSphereLightIrradiance(), it results
// in severe light leaking if the light is placed vertically behind the camera.
// So this function is clearly a hack designed to work around these problems.
real UTS_PolygonIrradianceFromVectorFormFactor(float3 F, bool isDiffuse)
{
float l = length(F);
float z = lerp(F.z , INV_TWO_PI * F.z, isDiffuse);
return max(0, (l * l + z) / (l + 1));
}
// Expects non-normalized vertex positions.
// Output: F is the signed vector irradiance.
real UTS_PolygonIrradiance(real4x3 L, bool isDiffuse, out real3 F)
{
//APPROXIMATE_POLY_LIGHT_AS_SPHERE_LIGHT
F = UTS_PolygonFormFactor(L, float3(0,0,1), 4, isDiffuse);
return UTS_PolygonIrradianceFromVectorFormFactor(F, isDiffuse); // Accounts for the horizon.
}
// This function assumes that inputs are well-behaved, e.i.
// that the line does not pass through the origin and
// that the light is (at least partially) above the surface.
float UTS_Diffuse_Line(float3 C, float3 A, float hl)
{
// Solve C.z + h * A.z = 0.
float h = -C.z * rcp(A.z); // May be Inf, but never NaN
// Clip the line segment against the z-plane if necessary.
float h2 = (A.z >= 0) ? max( hl, h)
: min( hl, h); // P2 = C + h2 * A
float h1 = (A.z >= 0) ? max(-hl, h)
: min(-hl, h); // P1 = C + h1 * A
// Normalize the tangent.
float as = dot(A, A); // |A|^2
float ar = rsqrt(as); // 1/|A|
float a = as * ar; // |A|
float3 T = A * ar; // A/|A|
// Orthogonal 2D coordinates:
// P(n, t) = n * N + t * T.
float tc = dot(T, C); // C = n * N + tc * T
float3 P0 = C - tc * T; // P(n, 0) = n * N
float ns = dot(P0, P0); // |P0|^2
float nr = rsqrt(ns); // 1/|P0|
float n = ns * nr; // |P0|
float Nz = P0.z * nr; // N.z = P0.z/|P0|
// P(n, t) - C = P0 + t * T - P0 - tc * T
// = (t - tc) * T = h * A = (h * a) * T.
float t2 = tc + h2 * a; // P2.t
float t1 = tc + h1 * a; // P1.t
float s2 = ns + t2 * t2; // |P2|^2
float s1 = ns + t1 * t1; // |P1|^2
float mr = rsqrt(s1 * s2); // 1/(|P1|*|P2|)
float r2 = s1 * (mr * mr); // 1/|P2|^2
float r1 = s2 * (mr * mr); // 1/|P1|^2
// I = (i1 + i2 + i3) / Pi.
// i1 = N.z * (P2.t / |P2|^2 - P1.t / |P1|^2).
// i2 = -T.z * (P2.n / |P2|^2 - P1.n / |P1|^2).
// i3 = N.z * ArcCos[Dot[P1, P2] / (|P1| * |P2|)] / |P0|.
float i12 = (Nz * t2 - (T.z * n)) * r2
- (Nz * t1 - (T.z * n)) * r1;
// Guard against numerical errors.
float dt = min(1, (ns + t1 * t2) * mr);
float i3 = acos(dt) * (Nz * nr); // angle * cos(θ) / r^2
//return T.z * n ;
// Guard against numerical errors.
return INV_PI * max(0, i12 + i3);
}
float4 UTS_EvaluateLTC_Area(bool isRectLight, float3 center, float3 right, float3 up, float halfLength, float halfHeight,
float3x3 invM, float perceptualRoughness, bool isDiffuse, int cookieMode, float4 cookieScaleOffset)
{
float3 ortho = cross(center, right);
float orthoSq = dot(ortho, ortho);
// Check whether the light is in a vertical orientation.
bool quit = (orthoSq == 0);
// Check whether the light is entirely below the surface.
// We must test twice, since a linear transformation
// may bring the light above the surface (a side-effect).
quit = quit || (center.z + halfLength * abs(right.z) + halfHeight * abs(up.z) <= 0);
float4 ltcValue = float4(1, 1, 1, 0);
if (quit && !isDiffuse)
{
return ltcValue;
}
// Perform a sparse matrix multiplication.
float3 C = mul(invM, center);
float3 A = mul(invM, right);
float3 B = mul(invM, up);
// Check whether the light is entirely below the surface.
// We must test twice, since a linear transformation
// may bring the light below the surface (as expected).
if (C.z + halfLength * abs(A.z) + halfHeight * abs(B.z) <= 0 && !isDiffuse)
{
return ltcValue;
}
if (isRectLight)
{
float4x3 lightVerts;
lightVerts[0] = C - halfLength * A - halfHeight * B; // LL
lightVerts[1] = lightVerts[0] + (2 * halfHeight) * B; // UL
lightVerts[2] = lightVerts[1] + (2 * halfLength) * A; // UR
lightVerts[3] = lightVerts[2] - (2 * halfHeight) * B; // LR
// Polygon irradiance in the transformed configuration.
float3 fromFactor;
ltcValue.a = UTS_PolygonIrradiance(lightVerts, isDiffuse, fromFactor);
if (cookieMode != COOKIEMODE_NONE)
{
ltcValue.rgb = SampleAreaLightCookie(cookieScaleOffset, lightVerts, fromFactor, perceptualRoughness);
}
}
else // Line light
{
float w = ComputeLineWidthFactor(invM, ortho, orthoSq);
ltcValue.a = UTS_Diffuse_Line(C, A, halfLength) * w;
}
return ltcValue;
}
#endif

View File

@@ -1,5 +1,5 @@
fileFormatVersion: 2 fileFormatVersion: 2
guid: 583ca489f74f54c45a708f3a17018fca guid: afada69a218dd594ea0f17e7c639c533
ShaderIncludeImporter: ShaderIncludeImporter:
externalObjects: {} externalObjects: {}
userData: userData:

View File

@@ -0,0 +1,231 @@
#ifndef UTS_ENV
#define UTS_ENV
#include "Packages/com.misaki.hdrp-toon/Runtime/HDRP/Shaders/Includes/Common/UtsCommon.hlsl"
// _preIntegratedFGD and _CubemapLD are unique for each BRDF
float3 EvaluateBSDF_ReflectionProbe(LightLoopContext lightLoopContext,
float3 V, PositionInputs posInput,
PreLightData preLightData, EnvLightData lightData, UtsBSDFData bsdfData,
int influenceShapeType,
inout float hierarchyWeight)
{
float weight = 1.0;
float3 R = reflect(-V, bsdfData.normalWS);
EvaluateLight_EnvIntersection(posInput.positionWS, bsdfData.normalWS, lightData, influenceShapeType, R, weight);
// No distance based roughness for simple lit
float4 preLD = SampleEnv(lightLoopContext, lightData.envIndex, R, PerceptualRoughnessToMipmapLevel(preLightData.iblPerceptualRoughness) * lightData.roughReflections, lightData.rangeCompressionFactorCompensation, posInput.positionNDC);
weight *= preLD.a; // Used by planar reflection to discard pixel
//envLighting = F_Schlick(bsdfData.fresnel0, dot(bsdfData.normalWS, V)) * preLD.rgb;
float3 envLighting = preLD.rgb;
UpdateLightingHierarchyWeights(hierarchyWeight, weight);
envLighting *= weight * lightData.multiplier;
return envLighting;
}
float4 ComputeReflection(LightLoopContext context, PositionInputs posInput, PreLightData preLightData, BuiltinData builtinData, UtsBSDFData bsdfData, float3 V)
{
float3 refcolor = 0;
float reflectionHierarchyWeight = 0.0; // Max: 1.0
uint envLightStart, envLightCount;
// Fetch first env light to provide the scene proxy for screen space computation
#ifndef LIGHTLOOP_DISABLE_TILE_AND_CLUSTER
GetCountAndStart(posInput, LIGHTCATEGORY_ENV, envLightStart, envLightCount);
#else // LIGHTLOOP_DISABLE_TILE_AND_CLUSTER
envLightCount = _EnvLightCount;
envLightStart = 0;
#endif
bool fastPath = false;
#if SCALARIZE_LIGHT_LOOP
uint envStartFirstLane;
fastPath = IsFastPath(envLightStart, envStartFirstLane);
#endif
context.sampleReflection = SINGLE_PASS_CONTEXT_SAMPLE_REFLECTION_PROBES;
#if SCALARIZE_LIGHT_LOOP
if (fastPath)
{
envLightStart = envStartFirstLane;
}
#endif
// Scalarized loop, same rationale of the punctual light version
uint v_envLightListOffset = 0;
uint v_envLightIdx = envLightStart;
#if NEED_TO_CHECK_HELPER_LANE
// On some platform helper lanes don't behave as we'd expect, therefore we prevent them from entering the loop altogether.
// IMPORTANT! This has implications if ddx/ddy is used on results derived from lighting, however given Lightloop is called in compute we should be
// sure it will not happen.
bool isHelperLane = WaveIsHelperLane();
while (!isHelperLane && v_envLightListOffset < envLightCount)
#else
while (v_envLightListOffset < envLightCount)
#endif
{
v_envLightIdx = FetchIndex(envLightStart, v_envLightListOffset);
#if SCALARIZE_LIGHT_LOOP
uint s_envLightIdx = ScalarizeElementIndex(v_envLightIdx, fastPath);
#else
uint s_envLightIdx = v_envLightIdx;
#endif
if (s_envLightIdx == -1)
break;
EnvLightData s_envLightData = FetchEnvLight(s_envLightIdx); // Scalar load.
// If current scalar and vector light index match, we process the light. The v_envLightListOffset for current thread is increased.
// Note that the following should really be ==, however, since helper lanes are not considered by WaveActiveMin, such helper lanes could
// end up with a unique v_envLightIdx value that is smaller than s_envLightIdx hence being stuck in a loop. All the active lanes will not have this problem.
if (s_envLightIdx >= v_envLightIdx)
{
v_envLightListOffset++;
if (reflectionHierarchyWeight < 1.0)
{
if (IsMatchingLightLayer(s_envLightData.lightLayers, builtinData.renderingLayers))
{
float RefProbeLighting = EvaluateBSDF_ReflectionProbe(context, V, posInput, preLightData, s_envLightData, bsdfData, s_envLightData.influenceShapeType, reflectionHierarchyWeight);
#if defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2)
float3 lightInReflDir = float3(-1, -1, -1);
if (s_envLightData.normalizeWithAPV > 0 && all(lightInReflDir >= 0))
{
float factor = GetReflectionProbeNormalizationFactor(lightInReflDir, bsdfData.normalWS, s_envLightData.L0L1, s_envLightData.L2_1, s_envLightData.L2_2);
RefProbeLighting *= factor;
}
#endif
refcolor += RefProbeLighting;
}
}
}
}
return float4(refcolor.r, refcolor.g, refcolor.b, reflectionHierarchyWeight);
}
float3 ComputeFresnelLerp(float3 c0, float3 c1, float cosA)
{
float t = pow(1 - cosA, 5);
return lerp(c0, c1, t);
}
float3 EvaluateIndirectDiffusePBR(PositionInputs posInput, UtsBSDFData bsdfData, float3 V)
{
float3 indirectDiffuse = 0.0;
#ifdef _PBR_Mode_ANISO
GetGGXAnisotropicModifiedNormalAndRoughness(bsdfData.bitangentWS, bsdfData.tangentWS , bsdfData.normalWS, V, bsdfData.anisotropy, bsdfData.perceptualRoughness, bsdfData.normalWS, bsdfData.perceptualRoughness);
#endif
float NdotV = saturate(dot(bsdfData.normalWS, V));
#if defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2)
BuiltinData apvBuiltinData;
ZERO_INITIALIZE(BuiltinData, apvBuiltinData);
#if defined(_PBR_Mode_OFF) || defined(_PBR_Mode_TOON)
EvaluateAdaptiveProbeVolume(GetAbsolutePositionWS(posInput.positionWS), 0.0, 0.0, V, posInput.positionSS, apvBuiltinData.bakeDiffuseLighting, apvBuiltinData.backBakeDiffuseLighting);
#else
EvaluateAdaptiveProbeVolume(GetAbsolutePositionWS(posInput.positionWS), bsdfData.normalWS, -bsdfData.normalWS, V, posInput.positionSS, apvBuiltinData.bakeDiffuseLighting, apvBuiltinData.backBakeDiffuseLighting);
#endif
float3 probeDiffuse = apvBuiltinData.bakeDiffuseLighting * GetCurrentExposureMultiplier();
indirectDiffuse = probeDiffuse;
#else
#if defined(_PBR_Mode_OFF) || defined(_PBR_Mode_TOON)
indirectDiffuse = EvaluateAmbientProbe(0.0) * GetCurrentExposureMultiplier();
#else
indirectDiffuse = EvaluateAmbientProbe(bsdfData.normalWS) * GetCurrentExposureMultiplier();
#endif
#endif
//SSGI
if(_ReceivesSSGI == 1)
{
float4 ssgiLighting = LOAD_TEXTURE2D_X(_IndirectDiffuseTexture, posInput.positionSS);
ssgiLighting *= _GIMultiplier;
indirectDiffuse = lerp(indirectDiffuse, ssgiLighting.rgb, ssgiLighting.a);
}
//Complete the indirect lighting
indirectDiffuse *= bsdfData.diffuseColor.rgb * _BaseColor.rgb;
//SSAO
if(_ReceivesSSAO == 1)
{
AmbientOcclusionFactor aoFactor;
GetScreenSpaceAmbientOcclusionMultibounce(posInput.positionSS, NdotV, bsdfData.perceptualRoughness, bsdfData.ambientOcclusion, bsdfData.specularOcclusion, bsdfData.diffuseColor, bsdfData.fresnel0, aoFactor);
indirectDiffuse *= lerp(_AO_Factor, 1, aoFactor.indirectAmbientOcclusion);
}
indirectDiffuse *= bsdfData.ambientOcclusion;
return indirectDiffuse;
}
float3 EvaluateIndirectDiffuse(PositionInputs posInput, UtsBSDFData bsdfData, float3 V)
{
float3 indirectDiffuse = 0.0;
indirectDiffuse = EvaluateIndirectDiffusePBR(posInput, bsdfData,V);
return indirectDiffuse * _ID_Intensity;
}
float3 EvaluateIndirectSpecular(LightLoopContext lightLoopContext, PositionInputs posInput, PreLightData preLightData, UtsBSDFData bsdfData, BuiltinData builtinData, float3 V)
{
#if defined(_PBR_Mode_OFF) || defined(_PBR_Mode_TOON)
return 0;
#else
float3 indirectSpecular = 0;
#ifdef _PBR_Mode_ANISO
GetGGXAnisotropicModifiedNormalAndRoughness(bsdfData.bitangentWS, bsdfData.tangentWS , bsdfData.normalWS, V, bsdfData.anisotropy, bsdfData.perceptualRoughness, bsdfData.normalWS, bsdfData.perceptualRoughness);
#endif
float mip = PerceptualRoughnessToMipmapLevel(bsdfData.perceptualRoughness);
float NdotV = saturate(dot(bsdfData.normalWS, V));
indirectSpecular = SampleSkyTexture(reflect(-V, bsdfData.normalWS), mip, 0).rgb;\
//Reflection Probe
float4 refProbe = ComputeReflection(lightLoopContext, posInput, preLightData, builtinData, bsdfData, V);
indirectSpecular = lerp(indirectSpecular, refProbe.rgb, refProbe.a);
//SSR
if(_ReceivesSSR == 1)
{
float4 ssrLighting = LOAD_TEXTURE2D_X(_SsrLightingTexture, posInput.positionSS);
InversePreExposeSsrLighting(ssrLighting);
ApplyScreenSpaceReflectionWeight(ssrLighting);
indirectSpecular = lerp(indirectSpecular, ssrLighting.rgb * preLightData.specularFGD, ssrLighting.a);
}
//Complete the indirect lighting
float grazingTerm = saturate((1 - bsdfData.perceptualRoughness) + (1 - bsdfData.reflectivity));
indirectSpecular *= ComputeFresnelLerp(bsdfData.fresnel0, grazingTerm, NdotV) * GetCurrentExposureMultiplier();
// Occlusion
if(_ReceivesSSAO == 1)
{
AmbientOcclusionFactor aoFactor;
GetScreenSpaceAmbientOcclusionMultibounce(posInput.positionSS, NdotV, bsdfData.perceptualRoughness, bsdfData.ambientOcclusion, bsdfData.specularOcclusion, bsdfData.diffuseColor, bsdfData.fresnel0, aoFactor);
indirectSpecular *= lerp(_AO_Factor, 1, aoFactor.indirectSpecularOcclusion);
}
indirectSpecular *= bsdfData.specularOcclusion;
return indirectSpecular * _IR_Intensity;
#endif
}
#endif

View File

@@ -0,0 +1,264 @@
#ifndef UTS_LIGHT_EVALUATION
#define UTS_LIGHT_EVALUATION
#if FP_BUFFER
#define SATURATE_IF_SDR(x) (x)
#define SATURATE_BASE_COLOR_IF_SDR(x) (x)
#else
#define SATURATE_IF_SDR(x) saturate(x)
#define SATURATE_BASE_COLOR_IF_SDR(x) saturate(x)
#endif
const float rateR = 0.299;
const float rateG = 0.587;
const float rateB = 0.114;
struct UTSLightData
{
float3 lightDirection;
float3 lightColor;
float diffuseDimmer;
float specularDimmer;
float3 shadowTint;
float penumbraTint;
SHADOW_TYPE shadowValue;
};
float GetColorAttenuation(float3 lightColor)
{
float lightAttenuation = rateR * lightColor.r + rateG * lightColor.g + rateB * lightColor.b;
return lightAttenuation;
}
float3 GetLimitedLightColor(float3 lightColor)
{
lightColor = ApplyCurrentExposureMultiplier(lightColor);
float3 result = lerp(lightColor, saturate(lightColor), _Is_Filter_LightColor);
return result;
}
DirectLighting UtsEvaluateBSDF_Directional(LightLoopContext lightLoopContext, PositionInputs posInput, BuiltinData builtinData, DirectionalLightData lightData, UtsBSDFData bsdfData, PreLightData preLightData, float3 V, float2 uv0)
{
DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
float3 L = -lightData.forward;
SHADOW_TYPE shadow = EvaluateShadow_Directional(lightLoopContext, posInput, lightData, builtinData, bsdfData.geomNormalWS);
if (lightData.lightDimmer > 0.0)
{
// TODO: Colored shadow will overwrite the first and second shading diffuse color
//float3 shadowColor = ComputeShadowColor(shadow, lightData.shadowTint, lightData.penumbraTint);
float4 lightColor = EvaluateLight_Directional(lightLoopContext, posInput, lightData);
lightColor.rgb = GetLimitedLightColor(lightColor.rgb * lightColor.a * _Light_Intensity_Multiplier);
UtsClampRoughness(preLightData, bsdfData, lightData.minRoughness);
lighting = UtsShadeSurface(posInput, bsdfData, preLightData, shadow, lightColor.rgb, V, L, uv0, lightData.diffuseDimmer, lightData.specularDimmer);
}
return lighting;
}
DirectLighting UtsEvaluateBSDF_Punctual(LightLoopContext lightLoopContext, PositionInputs posInput, BuiltinData builtinData, LightData lightData, UtsBSDFData bsdfData, PreLightData preLightData, float3 V, float2 uv0)
{
DirectLighting lighting;
ZERO_INITIALIZE(DirectLighting, lighting);
float3 L;
float4 distances; // {d, d^2, 1/d, d_proj}
GetPunctualLightVectors(posInput.positionWS, lightData, L, distances);
PositionInputs shadowPositionInputs = posInput;
shadowPositionInputs.positionWS = posInput.positionWS + L * _ShadowBias;
SHADOW_TYPE shadow = EvaluateShadow_Punctual(lightLoopContext, shadowPositionInputs, lightData, builtinData, bsdfData.geomNormalWS, L, distances);
if (lightData.lightDimmer > 0.0)
{
// TODO: Colored shadow will overwrite the first and second shading diffuse color
//float3 shadowColor = ComputeShadowColor(shadow, lightData.shadowTint, lightData.penumbraTint);
float4 lightColor = EvaluateLight_Punctual(lightLoopContext, posInput, lightData, L, distances);
lightColor.rgb = GetLimitedLightColor(lightColor.rgb * lightColor.a * _Light_Intensity_Multiplier);
UtsClampRoughness(preLightData, bsdfData, lightData.minRoughness);
lighting = UtsShadeSurface(posInput, bsdfData, preLightData, shadow, lightColor.rgb, V, L, uv0, lightData.diffuseDimmer, lightData.specularDimmer);
}
return lighting;
}
IndirectLighting UtsEvaluateBSDF_ScreenSpaceReflection(PositionInputs posInput, PreLightData preLightData, inout float reflectionHierarchyWeight)
{
IndirectLighting lighting;
ZERO_INITIALIZE(IndirectLighting, lighting);
// TODO: this texture is sparse (mostly black). Can we avoid reading every texel? How about using Hi-S?
float4 ssrLighting = LOAD_TEXTURE2D_X(_SsrLightingTexture, posInput.positionSS);
InversePreExposeSsrLighting(ssrLighting);
// Apply the weight on the ssr contribution (if required)
ApplyScreenSpaceReflectionWeight(ssrLighting);
reflectionHierarchyWeight = ssrLighting.a;
lighting.specularReflected = ssrLighting.rgb * preLightData.specularFGD;
return lighting;
}
void UtsEvaluateBSDF_BakeDiffuse(PositionInputs posInput, PreLightData preLightData, UtsBSDFData bsdfData, float3 V, inout BuiltinData builtinData, out float3 lightInReflDir)
{
lightInReflDir = 0.0;
#if defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2)
lightInReflDir = float3(-1, -1, -1); // This variable is used with APV for reflection probe normalization - see code for LIGHTFEATUREFLAGS_ENV
#endif
#if !defined(_SURFACE_TYPE_TRANSPARENT) && !defined(SCREEN_SPACE_INDIRECT_DIFFUSE_DISABLED)
if (_IndirectDiffuseMode != INDIRECTDIFFUSEMODE_OFF)
{
builtinData.bakeDiffuseLighting = LOAD_TEXTURE2D_X(_IndirectDiffuseTexture, posInput.positionSS).xyz * GetInverseCurrentExposureMultiplier();
}
else
#endif
{
#if defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2)
if (_EnableProbeVolumes)
{
// Reflect normal to get lighting for reflection probe tinting
float3 R = reflect(-V, bsdfData.normalWS);
#if defined(_PBR_Mode_OFF) || defined(_PBR_Mode_TOON)
float3 normalWS = 0.0;
float3 backNormalWS = 0.0;
#else
float3 normalWS = bsdfData.normalWS;
float3 backNormalWS = -bsdfData.normalWS;
#endif
EvaluateAdaptiveProbeVolume(GetAbsolutePositionWS(posInput.positionWS),
bsdfData.normalWS, -bsdfData.normalWS,
R, V,
posInput.positionSS, builtinData.renderingLayers,
builtinData.bakeDiffuseLighting, builtinData.backBakeDiffuseLighting, lightInReflDir);
}
else // If probe volume is disabled we fallback on the ambient probes
{
builtinData.bakeDiffuseLighting = EvaluateAmbientProbe(bsdfData.normalWS);
builtinData.backBakeDiffuseLighting = EvaluateAmbientProbe(-bsdfData.normalWS);
}
#endif
}
}
void UtsEvaluateBSDF_MatCapDiffuse(float3 positionWS, float3 normalWS, inout BuiltinData builtinData)
{
float3 positionVS = mul(UNITY_MATRIX_V, float4(positionWS, 1.0)).xyz;
float3 normalVS = mul(UNITY_MATRIX_V, float4(normalWS, 1.0)).xyz;
float3 PcrossN = cross(normalize(positionVS), normalVS);
float2 uv = PcrossN.yx;
uv.x *= -1;
uv = uv * 0.5 + 0.5;
builtinData.bakeDiffuseLighting = SAMPLE_TEXTURE2D_LOD(_MatCapMap, s_linear_clamp_sampler, uv, UNITY_SPECCUBE_LOD_STEPS).rgb * GetInverseCurrentExposureMultiplier();
}
IndirectLighting UtsEvaluateBSDF_MatCapSpecular(float3 positionWS, UtsBSDFData bsdfData, PreLightData preLightData)
{
IndirectLighting lighting;
ZERO_INITIALIZE(IndirectLighting, lighting);
float3 positionVS = mul(UNITY_MATRIX_V, float4(positionWS, 1.0)).xyz;
float3 normalVS = mul(UNITY_MATRIX_V, float4(bsdfData.normalWS, 1.0)).xyz;
float3 pcrossN = cross(normalize(positionVS), normalVS);
float2 uv = pcrossN.yx;
uv.x *= -1;
uv = uv * 0.5 + 0.5;
lighting.specularReflected = SAMPLE_TEXTURE2D_LOD(_MatCapMap, s_linear_clamp_sampler, uv, PerceptualRoughnessToMipmapLevel(bsdfData.perceptualRoughness)).rgb;
lighting.specularReflected *= preLightData.specularFGD * GetInverseCurrentExposureMultiplier();
return lighting;
}
void UtsEvaluateBSDF_Ramp(PositionInputs posInput, UtsBSDFData bsdfData, float3 L, inout BuiltinData builtinData)
{
// TODO
}
IndirectLighting UtsEvaluateBSDF_Env(LightLoopContext lightLoopContext, PositionInputs posInput, PreLightData preLightData, EnvLightData lightData, UtsBSDFData bsdfData, int influenceShapeType, int GPUImageBasedLightingType, inout float hierarchyWeight)
{
IndirectLighting lighting;
ZERO_INITIALIZE(IndirectLighting, lighting);
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFRACTION)
{
return lighting;
}
float3 envLighting;
float3 positionWS = posInput.positionWS;
float weight = 1.0;
float3 R = preLightData.iblR;
if (!IsEnvIndexTexture2D(lightData.envIndex)) // ENVCACHETYPE_CUBEMAP
{
R = GetSpecularDominantDir(bsdfData.normalWS, R, preLightData.iblPerceptualRoughness, ClampNdotV(preLightData.NdotV));
// When we are rough, we tend to see outward shifting of the reflection when at the boundary of the projection volume
// Also it appear like more sharp. To avoid these artifact and at the same time get better match to reference we lerp to original unmodified reflection.
// Formula is empirical.
float roughness = PerceptualRoughnessToRoughness(preLightData.iblPerceptualRoughness);
R = lerp(R, preLightData.iblR, saturate(smoothstep(0, 1, roughness * roughness)));
}
// Note: using influenceShapeType and projectionShapeType instead of (lightData|proxyData).shapeType allow to make compiler optimization in case the type is know (like for sky)
float intersectionDistance = EvaluateLight_EnvIntersection(positionWS, bsdfData.normalWS, lightData, influenceShapeType, R, weight);
float3 F = preLightData.specularFGD;
float4 preLD = SampleEnvWithDistanceBaseRoughness(lightLoopContext, posInput, lightData, R, preLightData.iblPerceptualRoughness, intersectionDistance);
weight *= preLD.a; // Used by planar reflection to discard pixel
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
{
envLighting = F * preLD.rgb;
// Apply the main lobe weight and update main reflection hierarchyWeight:
UpdateLightingHierarchyWeights(hierarchyWeight, weight);
envLighting *= weight;
}
envLighting *= lightData.multiplier;
if (GPUImageBasedLightingType == GPUIMAGEBASEDLIGHTINGTYPE_REFLECTION)
{
lighting.specularReflected = envLighting;
}
return lighting;
}
void UtsPostEvaluateBSDF(PositionInputs posInput, PreLightData preLightData, UtsBSDFData bsdfData, BuiltinData builtinData, AggregateLighting lighting, out LightLoopOutput lightLoopOutput)
{
AmbientOcclusionFactor aoFactor;
GetScreenSpaceAmbientOcclusionMultibounce(posInput.positionSS, preLightData.NdotV, bsdfData.perceptualRoughness, bsdfData.ambientOcclusion, bsdfData.specularOcclusion, bsdfData.diffuseColor, bsdfData.fresnel0, aoFactor);
builtinData.bakeDiffuseLighting = APPLY_WEIGHT(builtinData.bakeDiffuseLighting, aoFactor.indirectAmbientOcclusion, _AO_Factor);
lighting.indirect.specularReflected = APPLY_WEIGHT(lighting.indirect.specularReflected, aoFactor.indirectSpecularOcclusion, _AO_Factor);
lighting.direct.diffuse = APPLY_WEIGHT(lighting.direct.diffuse, aoFactor.directAmbientOcclusion, _AO_Factor);
lighting.direct.specular = APPLY_WEIGHT(lighting.direct.specular, aoFactor.directSpecularOcclusion, _AO_Factor);
builtinData.bakeDiffuseLighting = ApplyCurrentExposureMultiplier(builtinData.bakeDiffuseLighting * bsdfData.diffuseColor * preLightData.diffuseFGD * _ID_Intensity);
lighting.indirect.specularReflected = ApplyCurrentExposureMultiplier(lighting.indirect.specularReflected * bsdfData.fresnel0 * _IR_Intensity);
lightLoopOutput.diffuseLighting = lighting.direct.diffuse + builtinData.bakeDiffuseLighting;
lightLoopOutput.specularLighting = lighting.direct.specular + lighting.indirect.specularReflected;
// Rescale the GGX to account for the multiple scattering.
lightLoopOutput.specularLighting *= 1.0 + bsdfData.fresnel0 * preLightData.energyCompensation;
ApplyExposureAdjustment(lightLoopOutput.diffuseLighting);
ApplyExposureAdjustment(lightLoopOutput.specularLighting);
lightLoopOutput.diffuseLighting += builtinData.emissiveColor;
}
#endif

Some files were not shown because too many files have changed in this diff Show More