From f4efa953a9d5ed8f2d013e7164b265fec417929f Mon Sep 17 00:00:00 2001 From: uc-hoba Date: Wed, 12 Feb 2025 11:55:16 +0800 Subject: [PATCH] feat: add SGE files --- Assets/Plugins.meta | 8 + Assets/Plugins/ShaderGraphEssentials.meta | 8 + .../ShaderGraphEssentials/ChangeLog.txt | 87 + .../ShaderGraphEssentials/ChangeLog.txt.meta | 14 + .../Plugins/ShaderGraphEssentials/Plugin.meta | 8 + .../ShaderGraphEssentials/Plugin/Editor.meta | 8 + .../Plugin/Editor/GettingStarted.meta | 8 + .../Plugin/Editor/GettingStarted/Data.meta | 8 + .../GettingStarted/Data/SGE_key_128x128.png | 3 + .../Data/SGE_key_128x128.png.meta | 108 + .../GettingStarted/GettingStartedWindow.cs | 481 +++++ .../GettingStartedWindow.cs.meta | 18 + .../Editor/GettingStarted/SGESettings.cs | 27 + .../Editor/GettingStarted/SGESettings.cs.meta | 18 + .../Plugin/Editor/Plugin_Base.meta | 8 + .../Plugin/Editor/Plugin_Base/Resources.meta | 8 + .../Editor/Plugin_Base/Resources/Styles.meta | 8 + .../Resources/Styles/Controls.meta | 8 + .../NoiseDimensionEnumControlView.uss | 24 + .../NoiseDimensionEnumControlView.uss.meta | 10 + .../NoisePeriodicityEnumControlView.uss | 24 + .../NoisePeriodicityEnumControlView.uss.meta | 10 + .../Plugin/Editor/Plugin_Base/Scripts.meta | 8 + .../Plugin_Base/Scripts/BakeTextureManager.cs | 289 +++ .../Scripts/BakeTextureManager.cs.meta | 11 + .../Editor/Plugin_Base/Scripts/Controls.meta | 8 + .../Scripts/Controls/LabelControl.cs | 63 + .../Scripts/Controls/LabelControl.cs.meta | 11 + .../Controls/NoiseDimensionEnumControl.cs | 139 ++ .../NoiseDimensionEnumControl.cs.meta | 11 + .../Controls/NoisePeriodicityEnumControl.cs | 139 ++ .../NoisePeriodicityEnumControl.cs.meta | 11 + .../Editor/Plugin_Base/Scripts/Nodes.meta | 8 + .../Scripts/Nodes/BakeTextureNode.cs | 162 ++ .../Scripts/Nodes/BakeTextureNode.cs.meta | 11 + .../Plugin_Base/Scripts/Nodes/NoiseNode.cs | 419 ++++ .../Scripts/Nodes/NoiseNode.cs.meta | 11 + .../Nodes/NormalFromHeightVectorNode.cs | 54 + .../Nodes/NormalFromHeightVectorNode.cs.meta | 11 + .../Scripts/Nodes/NormalUOffsetNode.cs | 51 + .../Scripts/Nodes/NormalUOffsetNode.cs.meta | 11 + .../Scripts/Nodes/NormalVOffsetNode.cs | 51 + .../Scripts/Nodes/NormalVOffsetNode.cs.meta | 11 + .../Editor/Plugin_Base/Scripts/Noises.meta | 8 + .../Plugin_Base/Scripts/Noises/NoiseBase.cs | 45 + .../Scripts/Noises/NoiseBase.cs.meta | 11 + .../Scripts/Noises/NoiseCombine.cs | 27 + .../Scripts/Noises/NoiseCombine.cs.meta | 11 + .../Scripts/Noises/NoiseDimension.cs | 60 + .../Scripts/Noises/NoiseDimension.cs.meta | 11 + .../Scripts/Noises/NoisePeriodicity.cs | 59 + .../Scripts/Noises/NoisePeriodicity.cs.meta | 11 + .../Scripts/Noises/NoiseShaderUtils.cs | 606 ++++++ .../Scripts/Noises/NoiseShaderUtils.cs.meta | 11 + .../Plugin_Base/Scripts/Noises/NoiseType.cs | 26 + .../Scripts/Noises/NoiseType.cs.meta | 11 + .../Plugin_Base/Scripts/Noises/PerlinNoise.cs | 129 ++ .../Scripts/Noises/PerlinNoise.cs.meta | 11 + .../Scripts/Noises/SimplexNoise.cs | 85 + .../Scripts/Noises/SimplexNoise.cs.meta | 11 + .../Plugin_Base/Scripts/Noises/ValueNoise.cs | 101 + .../Scripts/Noises/ValueNoise.cs.meta | 11 + .../Plugin/Editor/Plugin_URP.meta | 8 + .../Editor/Plugin_URP/Master_Nodes.meta | 8 + .../Plugin_URP/Master_Nodes/CustomLit.meta | 8 + .../CustomLit/SGECustomLitMasterNode.cs | 36 + .../CustomLit/SGECustomLitMasterNode.cs.meta | 11 + .../Plugin_URP/Master_Nodes/SimpleLit.meta | 8 + .../SimpleLit/SGESimpleLitMasterNode.cs | 36 + .../SimpleLit/SGESimpleLitMasterNode.cs.meta | 11 + .../Editor/Plugin_URP/Master_Nodes/Unlit.meta | 8 + .../Master_Nodes/Unlit/SGEUnlitMasterNode.cs | 53 + .../Unlit/SGEUnlitMasterNode.cs.meta | 11 + .../Plugin/Editor/Plugin_URP/Shaders.meta | 8 + .../Shaders/CustomLitForwardPass.hlsl | 194 ++ .../Shaders/CustomLitForwardPass.hlsl.meta | 9 + .../Shaders/CustomLitGBufferPass.hlsl | 138 ++ .../Shaders/CustomLitGBufferPass.hlsl.meta | 7 + .../Shaders/SGE_CustomLightingInternal.hlsl | 33 + .../SGE_CustomLightingInternal.hlsl.meta | 9 + .../SGE_CustomLightingInternalFull.hlsl | 33 + .../SGE_CustomLightingInternalFull.hlsl.meta | 10 + .../Shaders/SGE_DefaultCustomLighting.hlsl | 63 + .../SGE_DefaultCustomLighting.hlsl.meta | 9 + ...SGE_DefaultCustomLightingGraph.shadergraph | 965 +++++++++ ...efaultCustomLightingGraph.shadergraph.meta | 10 + .../Plugin_URP/Shaders/SGE_ToonLighting.hlsl | 72 + .../Shaders/SGE_ToonLighting.hlsl.meta | 9 + .../Shaders/SimpleLitForwardPass.hlsl | 137 ++ .../Shaders/SimpleLitForwardPass.hlsl.meta | 9 + .../Shaders/SimpleLitGBufferPass.hlsl | 138 ++ .../Shaders/SimpleLitGBufferPass.hlsl.meta | 7 + .../Plugin/Editor/Plugin_URP/Templates.meta | 8 + .../Plugin_URP/Templates/PassMesh.template | 130 ++ .../Templates/PassMesh.template.meta | 7 + .../Plugin_URP/URPAssemblySpecific.meta | 8 + .../URPAssemblySpecific/AssetCallbacks.meta | 8 + .../CreateSGECustomLitShaderGraph.cs | 76 + .../CreateSGECustomLitShaderGraph.cs.meta | 11 + .../CreateSGESimpleLitShaderGraph.cs | 47 + .../CreateSGESimpleLitShaderGraph.cs.meta | 11 + .../CreateSGEUnlitShaderGraph.cs | 43 + .../CreateSGEUnlitShaderGraph.cs.meta | 11 + .../URPAssemblySpecific/SGEUniversal.asmref | 3 + .../SGEUniversal.asmref.meta | 7 + .../URPAssemblySpecific/Targets.meta | 8 + .../URPAssemblySpecific/Targets/SGEFields.cs | 67 + .../Targets/SGEFields.cs.meta | 11 + .../Targets/SGEShaderUtils.cs | 34 + .../Targets/SGEShaderUtils.cs.meta | 11 + .../Targets/SGEUniversalCustomLitSubTarget.cs | 855 ++++++++ .../SGEUniversalCustomLitSubTarget.cs.meta | 11 + .../Targets/SGEUniversalSimpleLitSubTarget.cs | 821 ++++++++ .../SGEUniversalSimpleLitSubTarget.cs.meta | 11 + .../Targets/SGEUniversalSubTarget.cs | 144 ++ .../Targets/SGEUniversalSubTarget.cs.meta | 11 + .../Targets/SGEUniversalTarget.cs | 1849 +++++++++++++++++ .../Targets/SGEUniversalTarget.cs.meta | 11 + .../Targets/SGEUniversalUnlitSubTarget.cs | 314 +++ .../SGEUniversalUnlitSubTarget.cs.meta | 11 + .../Editor/ShaderGraphEssentials.asmref | 3 + .../Editor/ShaderGraphEssentials.asmref.meta | 7 + .../ShaderGraphEssentials/Settings.asset | 15 + .../ShaderGraphEssentials/Settings.asset.meta | 8 + .../ShaderGraphEssentials_Documentation.pdf | 3 + ...aderGraphEssentials_Documentation.pdf.meta | 14 + 126 files changed, 10286 insertions(+) create mode 100644 Assets/Plugins.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/ChangeLog.txt create mode 100644 Assets/Plugins/ShaderGraphEssentials/ChangeLog.txt.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/Data.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/Data/SGE_key_128x128.png create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/Data/SGE_key_128x128.png.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/GettingStartedWindow.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/GettingStartedWindow.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/SGESettings.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/SGESettings.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoiseDimensionEnumControlView.uss create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoiseDimensionEnumControlView.uss.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoisePeriodicityEnumControlView.uss create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoisePeriodicityEnumControlView.uss.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/BakeTextureManager.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/BakeTextureManager.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/LabelControl.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/LabelControl.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoiseDimensionEnumControl.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoiseDimensionEnumControl.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoisePeriodicityEnumControl.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoisePeriodicityEnumControl.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/BakeTextureNode.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/BakeTextureNode.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NoiseNode.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NoiseNode.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalFromHeightVectorNode.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalFromHeightVectorNode.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalUOffsetNode.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalUOffsetNode.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalVOffsetNode.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalVOffsetNode.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseBase.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseBase.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseCombine.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseCombine.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseDimension.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseDimension.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoisePeriodicity.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoisePeriodicity.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseShaderUtils.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseShaderUtils.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseType.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseType.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/PerlinNoise.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/PerlinNoise.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/SimplexNoise.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/SimplexNoise.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/ValueNoise.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/ValueNoise.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/CustomLit.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/CustomLit/SGECustomLitMasterNode.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/CustomLit/SGECustomLitMasterNode.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/SimpleLit.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/SimpleLit/SGESimpleLitMasterNode.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/SimpleLit/SGESimpleLitMasterNode.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/Unlit.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/Unlit/SGEUnlitMasterNode.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/Unlit/SGEUnlitMasterNode.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitForwardPass.hlsl create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitForwardPass.hlsl.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitGBufferPass.hlsl create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitGBufferPass.hlsl.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternal.hlsl create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternal.hlsl.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternalFull.hlsl create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternalFull.hlsl.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLighting.hlsl create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLighting.hlsl.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLightingGraph.shadergraph create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLightingGraph.shadergraph.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_ToonLighting.hlsl create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_ToonLighting.hlsl.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitForwardPass.hlsl create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitForwardPass.hlsl.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitGBufferPass.hlsl create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitGBufferPass.hlsl.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Templates.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Templates/PassMesh.template create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Templates/PassMesh.template.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGECustomLitShaderGraph.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGECustomLitShaderGraph.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGESimpleLitShaderGraph.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGESimpleLitShaderGraph.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGEUnlitShaderGraph.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGEUnlitShaderGraph.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/SGEUniversal.asmref create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/SGEUniversal.asmref.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEFields.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEFields.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEShaderUtils.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEShaderUtils.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalCustomLitSubTarget.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalCustomLitSubTarget.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSimpleLitSubTarget.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSimpleLitSubTarget.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSubTarget.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSubTarget.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalTarget.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalTarget.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalUnlitSubTarget.cs create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalUnlitSubTarget.cs.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/ShaderGraphEssentials.asmref create mode 100644 Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/ShaderGraphEssentials.asmref.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/Settings.asset create mode 100644 Assets/Plugins/ShaderGraphEssentials/Settings.asset.meta create mode 100644 Assets/Plugins/ShaderGraphEssentials/ShaderGraphEssentials_Documentation.pdf create mode 100644 Assets/Plugins/ShaderGraphEssentials/ShaderGraphEssentials_Documentation.pdf.meta diff --git a/Assets/Plugins.meta b/Assets/Plugins.meta new file mode 100644 index 0000000..205ad68 --- /dev/null +++ b/Assets/Plugins.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: aecdca8e9f9827a4686c85e26b8e3100 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials.meta b/Assets/Plugins/ShaderGraphEssentials.meta new file mode 100644 index 0000000..b97f986 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bf3d25e31752a004cb3483acbc45007f +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/ChangeLog.txt b/Assets/Plugins/ShaderGraphEssentials/ChangeLog.txt new file mode 100644 index 0000000..447246e --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/ChangeLog.txt @@ -0,0 +1,87 @@ +Change Log: + +1.0.0 - Initial Release. + +1.0.1 - Fixed a bug in SGESimpleLit and SGEUnlit master nodes that made it impossible to work on Mac/Unix systems. + +1.0.2 - Uploaded a new 2019.1 compatible version. + - The 2018.3 version is unchanged. + +1.0.2b - Fixed an issue with permission which was creating errors on load with a 2019.1 project. +1.0.2c - Turns out the previous fix was working on windows only; so this version add the permission fix on mac. + +1.0.3 - Added support up to ShaderGraph 5.13.0. + +1.0.4 - 2019.1 - LWRP version now requires ShaderGraph 5.13.0 or newer (if you're on 2018.3 or on HDRP you're fine) + - If you don't want to update to 5.13.0, please contact me. + - Added new Custom Lighting master node (LWRP - 2019.1 only) + - Added new Toon Lighting master node example (LWRP - 2019.1 only) + - In all master nodes, added a "CustomEditor" setting so you can specify custom editor scripts like in regular shaders. + +1.0.5 - Updated SimpleLit master node to follow what Unity's been doing on LWRP/SimpleLit shader. + - Removed Glossiness node (it wasn't used) + - Renamed Shininess to Smoothness + Added a new fix for "Internal Errors" that some users were getting when opening ShaderGraphEssentials the first time (and sometimes on later open too). + +1.0.6 - Introduced the "Getting Started" window. It's useful to both existing and new users! + - Restructured how file are organized in the plugin. Also moved the entire plugin from Assets/ShaderGraphEssentials to Assets/Plugins/ShaderGraphEssentials. This has been requested by many users as to reduced the visual clutter of the root folder (as the plugin can't be moved at the moment!). + - Move the menu items from SGE to Tools/ShaderGraph Essentials for the same reasons. + +1.0.7 - Fixed a bug with the default custom lighting graph, referencing a wrong path (hlsl file). + - Fixed a minor bug that was throwing an GUI error the first time the Getting Started window was opened + - Fixed a bug that blocked the Getting Started window to import the HDRP package or demo scenes + +1.0.8 - If you're on Unity 2019.1.3 or newer and using LWRP, then you need to update to LWRP/ShaderGraph 5.16.1 when getting this version. + - Fixed a bug in SimpleLit / CustomLit shaders. The bug was giving errors in editor, but the shader was still working in editor and in builds. + - Fixed the version number in Getting Started window being wrong. + +1.0.9 - Only impacts 2019.2; if you're on 2018 or 2019.1 it's not useful to update. + - Add 2019.2 support (require ShaderGraph / SRP 6.9.1 and not 6.9.0 which contains a bug with custom functions and subgraphs). If you update from 2019.1, please delete the ShaderGraph Essentials folder and re-download the new one after upgrade to make sure there're no leftover files. + - Removed some demo shaders that were unused and fixed minor bugs in other demo shaders + +1.1.0 - Added new setting in all SGE master nodes: "Update Vertex Position". + - Added new water demo scene and shaders, with vertex displacement and depth-based foam to showcase the new setting + - Red-did the entire SGE asset store page, marketing visuals and added an extensive online doc + +1.1.1 - Added support for Unity 2019.3 (2019.3.0b11 and above). + +1.1.2 - Fixed a compilation error starting from 2019.3.0f6 (with URP 7.1.8). + - Improving SGE registration. This should solve errors when updating URP or Unity and getting "is inaccessible error". If you still have an issue similar to this, please contact me on the discord server. + - Better support if you have ShaderGraph package locally in your asset folder. + - Typo fix: "Periode" to "Period". + +1.1.3 - Only impact 2019.3: Fixed shader compilation error when using SGE master nodes on Android VR. + +1.1.4 - Only impact 2019.3: Now supports and requires URP / HDRP 7.2.1. + +1.1.5 - Added 2020.1 support. + - 2020.1 only: Completely changed how the plugin integrates with ShaderGraph. It is much more robust, and will be backported to 2019.x later if no issues are found. + - 2020.1 only: Fixed possible NaNs error when using 3D perlin Ridge noise node. Will be backported later. + - 2020.1 only: Renamed all "LWRP" instances to "URP". Will be backported to 2019.3 later. + - 2020.1 only: Fixed all scripts warnings. + +1.1.6 - Completely changed how the plugin integrates with ShaderGraph. It is much more robust and future proof! + - Fixed possible NaNs error when using 3D perlin Ridge noise node. + - Fixed all scripts warnings. + +1.1.7 - Added 2020.2 support. + +1.1.9 - Changes for 2020.2 only (so need to update if you're not on it). Updated version to support URP 10.3.1, which requires Unity 2020.2.4f1 and up. + If you are on 2020.2, please update to this plugin and Unity versions. + +1.1.10 - Fixes for 2020.2 / 2020.3 / 2021.1: fixed SGE Graphs settings not being upgrade properly from pre-2020.2 versions. + +1.1.11 - Fixed a visual artefact in Simplex noise implementation (all Unity versions). + +1.1.12 - Added support for Unity 2021.2. Doesn't change anything if you are on a previous version. + +1.1.13 - [2021.2] Fixed SimpleLit and CustomLit shaders not working with Vulkan rendering. Doesn't change anything if you are on a previous version. + +1.1.14 - [2021.2] Updated the 2021.2 version from 2021.2.0 to 2021.2.16, as the latest version introduced a breaking change. As such, 2021.2.16 is now needed as minimum version if you're on 2021.2. + +1.1.15 - Added support for 2022.1 + - [2021.2/3] Fixed Alpha blending mode not working properly with the SimpleLit and CustomLit master nodes. + +1.1.16 - Added support for 2022.2, 2022.3 and 2023.1. + +1.1.17 - Fixed realtime shadows in 2022.3 and 2023.1 \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/ChangeLog.txt.meta b/Assets/Plugins/ShaderGraphEssentials/ChangeLog.txt.meta new file mode 100644 index 0000000..9571b7d --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/ChangeLog.txt.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 01906810e0ab0264288634532a607697 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 141671 + packageName: ShaderGraph Essentials + packageVersion: 1.1.17 + assetPath: Assets/Plugins/ShaderGraphEssentials/ChangeLog.txt + uploadId: 607369 diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin.meta new file mode 100644 index 0000000..6ebf593 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 13ea453eb7829fa41983a355022348ad +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor.meta new file mode 100644 index 0000000..547b2a3 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 89bd8c9a72dfe7e40910f88c408c350e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted.meta new file mode 100644 index 0000000..c199a2f --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 73b310222da1fcf4fba1fa91066b58f2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/Data.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/Data.meta new file mode 100644 index 0000000..31ef217 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/Data.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ea6dabab92f8a1841baa2bb3320b840b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/Data/SGE_key_128x128.png b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/Data/SGE_key_128x128.png new file mode 100644 index 0000000..992cacd --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/Data/SGE_key_128x128.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e94441e0c2bcb7b7164053ff828e9134717b4a5256b91a4a82aa58f32b291b7f +size 36985 diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/Data/SGE_key_128x128.png.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/Data/SGE_key_128x128.png.meta new file mode 100644 index 0000000..6e736b2 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/Data/SGE_key_128x128.png.meta @@ -0,0 +1,108 @@ +fileFormatVersion: 2 +guid: 830d6e48d2c197a4aacb6e3da898cc28 +TextureImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 10 + mipmaps: + mipMapMode: 0 + enableMipMap: 0 + sRGBTexture: 1 + linearTexture: 0 + fadeOut: 0 + borderMipMap: 0 + mipMapsPreserveCoverage: 0 + alphaTestReferenceValue: 0.5 + mipMapFadeDistanceStart: 1 + mipMapFadeDistanceEnd: 3 + bumpmap: + convertToNormalMap: 0 + externalNormalMap: 0 + heightScale: 0.25 + normalMapFilter: 0 + isReadable: 0 + streamingMipmaps: 0 + streamingMipmapsPriority: 0 + grayScaleToAlpha: 0 + generateCubemap: 6 + cubemapConvolution: 0 + seamlessCubemap: 0 + textureFormat: 1 + maxTextureSize: 2048 + textureSettings: + serializedVersion: 2 + filterMode: -1 + aniso: -1 + mipBias: -100 + wrapU: -1 + wrapV: -1 + wrapW: -1 + nPOTScale: 1 + lightmap: 0 + compressionQuality: 50 + spriteMode: 0 + spriteExtrude: 1 + spriteMeshType: 1 + alignment: 0 + spritePivot: {x: 0.5, y: 0.5} + spritePixelsToUnits: 100 + spriteBorder: {x: 0, y: 0, z: 0, w: 0} + spriteGenerateFallbackPhysicsShape: 1 + alphaUsage: 1 + alphaIsTransparency: 0 + spriteTessellationDetail: -1 + textureType: 0 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 2 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: 3 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + - serializedVersion: 2 + buildTarget: Standalone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: 3 + textureCompression: 0 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: [] + physicsShape: [] + bones: [] + spriteID: + internalID: 0 + vertices: [] + indices: + edges: [] + weights: [] + secondaryTextures: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 141671 + packageName: ShaderGraph Essentials + packageVersion: 1.1.17 + assetPath: Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/Data/SGE_key_128x128.png + uploadId: 607369 diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/GettingStartedWindow.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/GettingStartedWindow.cs new file mode 100644 index 0000000..0973775 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/GettingStartedWindow.cs @@ -0,0 +1,481 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using UnityEditor; +using UnityEditor.SceneManagement; +using UnityEngine; +using UnityEngine.WSA; +using Application = UnityEngine.Application; + +namespace ShaderGraphEssentials +{ + [InitializeOnLoad] + public class GettingStartedWindowShow + { + private const string SettingsPath = "Assets/Plugins/ShaderGraphEssentials/Settings.asset"; + static GettingStartedWindowShow() + { + var settings = AssetDatabase.LoadAssetAtPath(SettingsPath, typeof(SGESettings)) as SGESettings; + bool showWindow = !(settings && !settings.OpenGettingStartedWindow); + if (showWindow) + { + EditorApplication.update += OnUpdate; + + } + } + + private static void OnUpdate() + { + EditorApplication.update -= OnUpdate; + + SGESettings newSettings = ScriptableObject.CreateInstance(); + AssetDatabase.CreateAsset(newSettings, SettingsPath); + AssetDatabase.SaveAssets(); + AssetDatabase.Refresh(); + GettingStartedWindow window = (GettingStartedWindow)EditorWindow.GetWindow(typeof(GettingStartedWindow)); + window.Show(); + } + } + + + public class GettingStartedWindow : EditorWindow + { + private const string SGEVersion = "1.1.17"; + + private const string SGEPath = "Assets/Plugins/ShaderGraphEssentials"; + private const string SGELogoFileName = "Plugin/Editor/GettingStarted/Data/SGE_key_128x128.png"; + private const string ManualFileName = "ShaderGraphEssentials_Documentation.pdf"; + private const string ChangeLogName = "ChangeLog.txt"; + + private const string NoiseScene = BaseDemoPath + "/Scenes/ShaderGraphEssentials_Demo.unity"; + private const string SimpleLitScene = URPDemoPath + "/Scenes/ShaderGraphEssentials_Showcase_SimpleLit.unity"; + private const string ToonLitScene = URPDemoPath + "/Scenes/ShaderGraphEssentials_Showcase_ToonLit.unity"; + private const string WaterScene = URPDemoPath + "/Scenes/ShaderGraphEssentials_Showcase_Water.unity"; + + private const string DemoFolderPath = "DemoScenes"; + private const string BaseDemoPath = "DemoScenes/Demo_Base"; + private const string URPDemoPath = "DemoScenes/Demo_URP"; + + private const string BasePluginPath = "Plugin/Editor/Plugin_Base"; + private const string URPPluginPath = "Plugin/Editor/Plugin_URP"; + + private const string URPPluginPackagePath = "Packages/SGE_URP.unitypackage"; + private const string URPDemoPackagePath = "Packages/SGE_URP_Demo.unitypackage"; + private const string HDRPPluginPackagePath = "Packages/SGE_HDRP.unitypackage"; + private const string HDRPDemoPackagePath = "Packages/SGE_HDRP_Demo.unitypackage"; + + private GUIStyle _wrapLabelStyle; + + private Texture2D _logoTexture; + + private bool _hasError; + + // various sizes + private const int LogoTextureSize = 128; + private const int Margin = 10; + private const int ButtonHeight = 30; + private const int ButtonWidth = 120; + private const int LargeButtonWidth = 160; + + private Vector2 _scrollPosition = Vector2.zero; + private Vector2 _defaultWindowSize = Vector2.zero; + + private bool _initialized = false; + + [MenuItem("Tools/ShaderGraph Essentials/Getting Started")] + static void Init() + { + // Get existing open window or if none, make a new one: + GettingStartedWindow window = (GettingStartedWindow)EditorWindow.GetWindow(typeof(GettingStartedWindow)); + window.Show(); + } + + private bool GetInternalFile(string pathFromSGE, out string fullPath) + { + fullPath = Path.Combine(SGEPath, pathFromSGE); + if (File.Exists(fullPath)) + return true; + + Debug.LogError("File " + fullPath + " doesn't exist. Did you move the ShaderGraphEssentials root folder from Assets/ ? Unfortunately this isn't supported yet."); + _hasError = true; + return false; + } + + private void Awake() + { + string fullLogoPath; + if (!GetInternalFile(SGELogoFileName, out fullLogoPath)) + { + return; + } + + _logoTexture = AssetDatabase.LoadAssetAtPath(fullLogoPath); + } + + private bool OpenFileWithDefaultEditor(string path) + { + string fullPath; + if (!GetInternalFile(path, out fullPath)) + { + return false; + } + + fullPath = Path.GetFullPath(fullPath); + + if (!File.Exists(fullPath)) + { + Debug.LogError("File " + fullPath + " doesn't exist. Did you move the ShaderGraphEssentials root folder from Assets/ ? Unfortunately this isn't supported yet."); + _hasError = true; + return false; + } + +#if UNITY_EDITOR_WIN + System.Diagnostics.Process.Start($@"{fullPath}"); +#elif UNITY_EDITOR_OSX + EditorUtility.RevealInFinder($@"{fullPath}"); +#endif + + return true; + } + + private bool CheckForErrors() + { + if (_hasError) + { + GUILayout.Label( + "There was an error constructing this window. Please check your console for errors. If you can't fix it, please don't hesitate to ask for support"); + return true; + } + + return false; + } + + private void InitializeWindow() + { + titleContent.text = "Getting Started"; + minSize = new Vector2(250, 400); + + _defaultWindowSize = new Vector2(520, 800); + Vector2 initialPosition = 0.5f * (new Vector2(Screen.currentResolution.width, Screen.currentResolution.height) - _defaultWindowSize); + position = new Rect(initialPosition, _defaultWindowSize); + + _wrapLabelStyle = new GUIStyle(EditorStyles.label) {wordWrap = true}; + } + + void OnGUI() + { + if (!_initialized) + { + InitializeWindow(); + _initialized = true; + } + + if (CheckForErrors()) return; + + _scrollPosition = GUI.BeginScrollView(new Rect(0, 0, position.width, position.height), _scrollPosition, + new Rect(0, 0, _defaultWindowSize.x - 10, _defaultWindowSize.y - 10), false, false); + + float yOffset = 0; + float defaultXSize = position.width - Margin - Margin; + + // Header + GUI.BeginGroup(new Rect(Margin, Margin, defaultXSize, LogoTextureSize)); + + float xOffset = 0; + GUI.DrawTexture(new Rect(xOffset, 0, LogoTextureSize, LogoTextureSize), _logoTexture); + xOffset += LogoTextureSize + Margin; + + GUI.Label(new Rect(xOffset, 0, 100, 30), "Version: " + SGEVersion); + if (GUI.Button(new Rect(xOffset, 30, ButtonWidth, ButtonHeight), "View Changelog")) + { + OpenChangelog(); + if (CheckForErrors()) return; + } + + if (GUI.Button(new Rect(xOffset, 30 + ButtonHeight + Margin, ButtonWidth, ButtonHeight), "View Manual")) + { + OpenManual(); + if (CheckForErrors()) return; + } + + xOffset += ButtonWidth + Margin; + + if (GUI.Button(new Rect(xOffset, 30, LargeButtonWidth, ButtonHeight), "View Offline Changelog")) + { + OpenFileWithDefaultEditor(ChangeLogName); + if (CheckForErrors()) return; + } + + if (GUI.Button(new Rect(xOffset, 30 + ButtonHeight + Margin, LargeButtonWidth, ButtonHeight), "View Offline Manual")) + { + OpenFileWithDefaultEditor(ManualFileName); + if (CheckForErrors()) return; + } + + GUI.EndGroup(); + + yOffset += Margin + LogoTextureSize; + + GUI.Label(new Rect(Margin, yOffset + Margin, defaultXSize, 10), "", GUI.skin.horizontalSlider); + + yOffset += Margin + Margin; + + // Getting started title + yOffset += Margin; + GUI.BeginGroup(new Rect(Margin, yOffset, defaultXSize, 20)); + + GUI.Label(new Rect(defaultXSize / 2f - 50, 0, 100, 20), "Getting Started", EditorStyles.largeLabel); + + GUI.EndGroup(); + + yOffset += Margin + 20; + + // URP + + GUI.BeginGroup(new Rect(Margin, yOffset, defaultXSize, 260)); + + GUI.Label(new Rect(0, 0, defaultXSize, 30), "URP", EditorStyles.boldLabel); + + if (GUI.Button(new Rect(0, 30, defaultXSize, ButtonHeight), "Import URP plugin")) + { + ImportURPPlugin(); + } + + bool isURPImported = IsURPImported(); + + using (new EditorGUI.DisabledScope(!isURPImported)) + { + if (GUI.Button(new Rect(0, ButtonHeight * 2 + Margin, defaultXSize, ButtonHeight), "Import URP Demo scenes")) + { + ImportURPScenes(); + } + } + + bool areURPScenesImported = AreURPScenesImported(); + + using (new EditorGUI.DisabledScope(!areURPScenesImported)) + { + if (GUI.Button(new Rect(0, ButtonHeight * 3 + Margin * 2, defaultXSize, ButtonHeight), "Open noise scene")) + { + OpenScene(NoiseScene); + } + if (GUI.Button(new Rect(0, ButtonHeight * 4 + Margin * 3, defaultXSize, ButtonHeight), "Open simple lit scene")) + { + OpenScene(SimpleLitScene); + } + if (GUI.Button(new Rect(0, ButtonHeight * 5 + Margin * 4, defaultXSize, ButtonHeight), "Open toon lit scene")) + { + OpenScene(ToonLitScene); + } + if (GUI.Button(new Rect(0, ButtonHeight * 6 + Margin * 5, defaultXSize, ButtonHeight), "Open water scene")) + { + OpenScene(WaterScene); + } + } + + GUI.EndGroup(); + + yOffset += 260; + + // HDRP + yOffset += Margin; + + GUI.BeginGroup(new Rect(Margin, yOffset, defaultXSize, 140)); + + GUI.Label(new Rect(0, 0, defaultXSize, 30), "HDRP", EditorStyles.boldLabel); + + if (GUI.Button(new Rect(0, 30, defaultXSize, ButtonHeight), "Import HDRP plugin")) + { + ImportHDRPPlugin(); + } + + bool isHDRPImported = IsHDRPImported(); + + using (new EditorGUI.DisabledScope(!isHDRPImported)) + { + if (GUI.Button(new Rect(0, ButtonHeight * 2 + Margin, defaultXSize, ButtonHeight), "Import HDRP Demo scenes")) + { + ImportHDRPScenes(); + } + } + + bool areHDRPScenesImported = AreHDRPScenesImported(); + + using (new EditorGUI.DisabledScope(!areHDRPScenesImported)) + { + if (GUI.Button(new Rect(0, ButtonHeight * 3 + Margin * 2, defaultXSize, ButtonHeight), "Open noise scene")) + { + OpenScene(NoiseScene); + } + } + + GUI.EndGroup(); + + yOffset += 140; + + // switch URP / HDRP + yOffset += Margin; + + GUI.BeginGroup(new Rect(Margin, yOffset, defaultXSize, 90)); + + GUI.Label(new Rect(0, 0, defaultXSize, 30), "Switch between URP / HDRP", EditorStyles.boldLabel); + + GUI.Label(new Rect(0, 30, defaultXSize, 30), "To switch between URP / HDRP, hit the button below and reimport the correct plugin" + , _wrapLabelStyle); + + if (GUI.Button(new Rect(0, 60, defaultXSize, ButtonHeight), "Remove plugins and demo scenes")) + { + CleanEverything(); + } + + GUI.EndGroup(); + + yOffset += 90; + + GUI.Label(new Rect(Margin, yOffset + Margin, defaultXSize, 10), "", GUI.skin.horizontalSlider); + + yOffset += Margin + Margin; + + // Help title + yOffset += Margin; + GUI.BeginGroup(new Rect(Margin, yOffset, defaultXSize, 30)); + + GUI.Label(new Rect(defaultXSize / 2f - 15, 0, 100, 20), "Help", EditorStyles.largeLabel); + + GUI.EndGroup(); + + yOffset += Margin + 20; + + // Help + GUI.BeginGroup(new Rect(Margin, yOffset, defaultXSize, ButtonHeight)); + + if (GUI.Button(new Rect(0, 0, defaultXSize / 2 - Margin, ButtonHeight), "Discord")) + { + OpenDiscordHelp(); + } + + if (GUI.Button(new Rect(defaultXSize / 2 + Margin, 0, defaultXSize / 2 - Margin, ButtonHeight), "Email")) + { + OpenEmailHelp(); + } + + + GUI.EndGroup(); + + GUI.EndScrollView(); + } + + private void OpenEmailHelp() + { + Application.OpenURL("mailto:ph.graphics.unity@gmail.com"); + } + + private void OpenDiscordHelp() + { + Application.OpenURL("https://discord.gg/ksURBah"); + } + + private void OpenManual() + { + Application.OpenURL("http://assetstore.phbarralis.com/sge/features.html"); + } + + private void OpenChangelog() + { + Application.OpenURL("http://assetstore.phbarralis.com/sge/changelog.html"); + } + + private void ImportHDRPScenes() + { + ImportPackage(HDRPDemoPackagePath); + } + + private bool AreHDRPScenesImported() + { + return Directory.Exists(Path.Combine(SGEPath, BaseDemoPath)); + } + + private bool IsHDRPImported() + { + return Directory.Exists(Path.Combine(SGEPath, BasePluginPath)); + } + + private void ImportHDRPPlugin() + { + ImportPackage(HDRPPluginPackagePath); + } + + private void OpenScene(string sceneName) + { + string fullPath; + if (!GetInternalFile(sceneName, out fullPath)) + return; + + EditorSceneManager.OpenScene(fullPath, OpenSceneMode.Single); + } + + private bool AreURPScenesImported() + { + return Directory.Exists(Path.Combine(SGEPath, URPDemoPath)); + } + + private bool IsURPImported() + { + return Directory.Exists(Path.Combine(SGEPath, URPPluginPath)); + } + + private void ImportURPScenes() + { + ImportPackage(URPDemoPackagePath); + } + + private void ImportURPPlugin() + { + ImportPackage(URPPluginPackagePath); + } + + private void ImportPackage(string packagePath) + { + string fullPath; + if (!GetInternalFile(packagePath, out fullPath)) + return; + + AssetDatabase.ImportPackage(fullPath, true); + } + + private void DeleteIfFolderExist(string directoryPath) + { + string fullpath = Path.Combine(SGEPath, directoryPath); + if (Directory.Exists(fullpath)) + FileUtil.DeleteFileOrDirectory(fullpath); + } + + private void CleanEverything() + { + DeleteIfFolderExist(DemoFolderPath); + + DeleteIfFolderExist(BasePluginPath); + DeleteIfFolderExist(URPPluginPath); + + AssetDatabase.Refresh(); + } + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/GettingStartedWindow.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/GettingStartedWindow.cs.meta new file mode 100644 index 0000000..f81e60b --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/GettingStartedWindow.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: 279d2f6664e4af347a537c4f9a9bd000 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 141671 + packageName: ShaderGraph Essentials + packageVersion: 1.1.17 + assetPath: Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/GettingStartedWindow.cs + uploadId: 607369 diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/SGESettings.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/SGESettings.cs new file mode 100644 index 0000000..952d3e4 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/SGESettings.cs @@ -0,0 +1,27 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using UnityEngine; + +namespace ShaderGraphEssentials +{ + public class SGESettings : ScriptableObject + { + [HideInInspector] + public bool OpenGettingStartedWindow = false; + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/SGESettings.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/SGESettings.cs.meta new file mode 100644 index 0000000..c8cfa63 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/SGESettings.cs.meta @@ -0,0 +1,18 @@ +fileFormatVersion: 2 +guid: f261da61669a6ab4bb6571eae406da7e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 141671 + packageName: ShaderGraph Essentials + packageVersion: 1.1.17 + assetPath: Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/GettingStarted/SGESettings.cs + uploadId: 607369 diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base.meta new file mode 100644 index 0000000..b2e772b --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ad68d7bf033528d4f9ac90b9c4cb8e30 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources.meta new file mode 100644 index 0000000..21a47e8 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: e2a68d368e9d9bd4e983b7b3c670977c +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles.meta new file mode 100644 index 0000000..f3fda78 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 588f9158ddf0fdb4e8d710476f605966 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls.meta new file mode 100644 index 0000000..d2316bd --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b01fbbe189ceed1459c201c1c00f079b +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoiseDimensionEnumControlView.uss b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoiseDimensionEnumControlView.uss new file mode 100644 index 0000000..abdd6a9 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoiseDimensionEnumControlView.uss @@ -0,0 +1,24 @@ +NoiseDimensionEnumControlView { + flex-direction: row; + align-items: center; +} + +.unity-base-field { + width: 80px; + flex:1; + margin-top: 4px; + margin-bottom: 4px; +} + +.unity-base-field__input { + flex:1; + margin-left: 0; + margin-right: 8px; +} + +NoiseDimensionEnumControlView > Label { + width: 94px; + -unity-text-align: middle-left; + margin-left: 8px; + margin-right: 8px; +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoiseDimensionEnumControlView.uss.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoiseDimensionEnumControlView.uss.meta new file mode 100644 index 0000000..397a266 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoiseDimensionEnumControlView.uss.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 54d755914ee66e1419d86ef8c20e4cae +ScriptedImporter: + fileIDToRecycleName: + 11400000: stylesheet + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoisePeriodicityEnumControlView.uss b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoisePeriodicityEnumControlView.uss new file mode 100644 index 0000000..89b65aa --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoisePeriodicityEnumControlView.uss @@ -0,0 +1,24 @@ +NoisePeriodicityEnumControlView { + flex-direction: row; + align-items: center; +} + +.unity-base-field { + width: 80px; + flex:1; + margin-top: 4px; + margin-bottom: 4px; +} + +.unity-base-field__input { + flex:1; + margin-left: 0; + margin-right: 8px; +} + +NoisePeriodicityEnumControlView > Label { + width: 94px; + -unity-text-align: middle-left; + margin-left: 8px; + margin-right: 8px; +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoisePeriodicityEnumControlView.uss.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoisePeriodicityEnumControlView.uss.meta new file mode 100644 index 0000000..7ecab2b --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Resources/Styles/Controls/NoisePeriodicityEnumControlView.uss.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 10a0af41f9362544e8a5c306f9942438 +ScriptedImporter: + fileIDToRecycleName: + 11400000: stylesheet + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts.meta new file mode 100644 index 0000000..ec76103 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: dea7a28dfc4a37340b641543d816e5b9 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/BakeTextureManager.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/BakeTextureManager.cs new file mode 100644 index 0000000..c1d7d54 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/BakeTextureManager.cs @@ -0,0 +1,289 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// +using System; +using System.Collections.Generic; +using UnityEditor; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEngine; +using UnityEngine.Rendering; + +namespace ShaderGraphEssentials +{ + class BakeShaderData + { + public BakeTextureNode Node { get; set; } + internal GraphData Graph { get; set; } + public Shader Shader { get; set; } + public string ShaderString { get; set; } + public bool HasError { get; set; } + public string OutputIdName { get; set; } + } + // Most of this class use copy pasted / inspired / modified versions of PreviewManager.cs in Unity's SG. + class BakeTextureManager + { + private const string DefaultPath = "SGE_DefaultBakedTexture.png"; + + BakeTextureManager() + { + } + + internal static void BakeShaderIntoTexture(BakeShaderData shaderData) + { + var node = shaderData.Node; + var renderTexture = new RenderTexture(node.Width, node.Height, 16, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default) { hideFlags = HideFlags.HideAndDontSave }; + renderTexture.Create(); + + // setup mesh + Mesh quadMesh = Resources.GetBuiltinResource(typeof(Mesh), "Quad.fbx") as Mesh; + Material bakeMaterial = new Material(shaderData.Shader); + MaterialPropertyBlock materialPropertyBlock = new MaterialPropertyBlock(); + + // setup camera + GameObject cameraGo = new GameObject(); + var camera = cameraGo.AddComponent(); + camera.cameraType = CameraType.Preview; + camera.enabled = false; + camera.clearFlags = CameraClearFlags.Depth; + camera.fieldOfView = 15; + camera.farClipPlane = 10.0f; + camera.nearClipPlane = 2.0f; + camera.backgroundColor = new Color(49.0f / 255.0f, 49.0f / 255.0f, 49.0f / 255.0f, 1.0f); + camera.renderingPath = RenderingPath.Forward; + camera.useOcclusionCulling = false; + camera.clearFlags = CameraClearFlags.Depth; + camera.transform.position = -Vector3.forward * 2; + camera.transform.rotation = Quaternion.identity; + camera.orthographicSize = 0.5f; + camera.orthographic = true; + camera.targetTexture = renderTexture; + + Stack tempNodeWave = new Stack(); + HashSet tempAddedToNodeWave = new HashSet(); + HashSet nodesToDraw = new HashSet(); + + // setup material and fill properties from all the previous nodes + var sources = new HashSet + { + node + }; + + PropagateNodes(sources, PropagationDirection.Upstream, tempNodeWave, tempAddedToNodeWave, nodesToDraw); + + PooledList perMaterialPreviewProperties = PooledList.Get(); + CollectPreviewProperties(shaderData.Graph, nodesToDraw, perMaterialPreviewProperties, materialPropertyBlock); + + AssignPerMaterialPreviewProperties(bakeMaterial, perMaterialPreviewProperties); + + // draw the quad into the camera's render texture + Graphics.DrawMesh(quadMesh, Matrix4x4.identity, bakeMaterial, 1, camera, 0, materialPropertyBlock, ShadowCastingMode.Off, false, null, false); + + camera.Render(); + + // get the render texture from GPU to CPU and save it as an asset + Texture2D texture = new Texture2D(renderTexture.width, renderTexture.height, TextureFormat.RGB24, false); + RenderTexture.active = renderTexture; + texture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0); + texture.Apply(); + + var textureBytes = texture.EncodeToPNG(); + + string path = ""; + bool textureFound = false; + if (node.OutputTexture != null && AssetDatabase.Contains(node.OutputTexture)) + { + try + { + path = AssetDatabase.GetAssetPath(node.OutputTexture); + System.IO.File.WriteAllBytes(path, textureBytes); + AssetDatabase.ImportAsset(path); + textureFound = true; + } catch (Exception e) + { + Debug.LogException(e); + } + } + + if (!textureFound) + { + path = Application.dataPath + "/" + DefaultPath; + System.IO.File.WriteAllBytes(path, textureBytes); + path = "Assets/" + DefaultPath; + AssetDatabase.ImportAsset(path); + Debug.LogWarning("No previous baked texture was found so a new one was created at Assets/" + DefaultPath + ". Please rename or move the texture as this specific texture path might be overriden."); + } + + node.OutputTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture2D)); + + // cleanup + RenderTexture.active = null; + UnityEngine.Object.DestroyImmediate(cameraGo); + UnityEngine.Object.DestroyImmediate(bakeMaterial); + } + + static void AssignPerMaterialPreviewProperties(Material mat, List perMaterialPreviewProperties) + { + foreach (var prop in perMaterialPreviewProperties) + { + switch (prop.propType) + { + case PropertyType.VirtualTexture: + + // setup the VT textures on the material + bool setAnyTextures = false; + var vt = prop.vtProperty.value; + for (int layer = 0; layer < vt.layers.Count; layer++) + { + var texture = vt.layers[layer].layerTexture?.texture; + int propIndex = mat.shader.FindPropertyIndex(vt.layers[layer].layerRefName); + if (propIndex != -1) + { + mat.SetTexture(vt.layers[layer].layerRefName, texture); + setAnyTextures = true; + } + } + // also put in a request for the VT tiles, since preview rendering does not have feedback enabled + if (setAnyTextures) + { +#if ENABLE_VIRTUALTEXTURES + int stackPropertyId = Shader.PropertyToID(prop.vtProperty.referenceName); + try + { + // Ensure we always request the mip sized 256x256 + int width, height; + UnityEngine.Rendering.VirtualTexturing.Streaming.GetTextureStackSize(mat, stackPropertyId, out width, out height); + int textureMip = (int)Math.Max(Mathf.Log(width, 2f), Mathf.Log(height, 2f)); + const int baseMip = 8; + int mip = Math.Max(textureMip - baseMip, 0); + UnityEngine.Rendering.VirtualTexturing.Streaming.RequestRegion(mat, stackPropertyId, new Rect(0.0f, 0.0f, 1.0f, 1.0f), mip, UnityEngine.Rendering.VirtualTexturing.System.AllMips); + } + catch (InvalidOperationException) + { + // This gets thrown when the system is in an indeterminate state (like a material with no textures assigned which can obviously never have a texture stack streamed). + // This is valid in this case as we're still authoring the material. + } +#endif // ENABLE_VIRTUALTEXTURES + } + break; + } + } + } + + static void CollectPreviewProperties(GraphData m_Graph, IEnumerable nodesToCollect, PooledList perMaterialPreviewProperties, + MaterialPropertyBlock mSharedPreviewPropertyBlock) + { + using (var tempPreviewProps = PooledList.Get()) + { + // collect from all of the changed nodes + foreach (var propNode in nodesToCollect) + propNode.CollectPreviewMaterialProperties(tempPreviewProps); + + // also grab all graph properties (they are updated every frame) + foreach (var prop in m_Graph.properties) + tempPreviewProps.Add(prop.GetPreviewMaterialProperty()); + + foreach (var previewProperty in tempPreviewProps) + { + previewProperty.SetValueOnMaterialPropertyBlock(mSharedPreviewPropertyBlock); + + // virtual texture assignments must be pushed to the materials themselves (MaterialPropertyBlocks not supported) + if ((previewProperty.propType == PropertyType.VirtualTexture) && + (previewProperty.vtProperty?.value?.layers != null)) + { + perMaterialPreviewProperties.Add(previewProperty); + } + } + } + } + + enum PropagationDirection + { + Upstream, + Downstream + } + + static void PropagateNodes(HashSet sources, PropagationDirection dir, Stack m_TempNodeWave, HashSet m_TempAddedToNodeWave, HashSet result) + { + Action AddNextLevelNodesToWave = + nextLevelNode => + { + if (!m_TempAddedToNodeWave.Contains(nextLevelNode)) + { + m_TempNodeWave.Push(nextLevelNode); + m_TempAddedToNodeWave.Add(nextLevelNode); + } + }; + + if (sources.Count > 0) + { + // NodeWave represents the list of nodes we still have to process and add to result + m_TempNodeWave.Clear(); + m_TempAddedToNodeWave.Clear(); + foreach (var node in sources) + { + m_TempNodeWave.Push(node); + m_TempAddedToNodeWave.Add(node); + } + + while (m_TempNodeWave.Count > 0) + { + var node = m_TempNodeWave.Pop(); + if (node == null) + continue; + + result.Add(node); + + // grab connected nodes in propagation direction, add them to the node wave + ForeachConnectedNode(node, dir, AddNextLevelNodesToWave); + } + + // clean up any temp data + m_TempNodeWave.Clear(); + m_TempAddedToNodeWave.Clear(); + } + } + + static void ForeachConnectedNode(AbstractMaterialNode node, PropagationDirection dir, Action action) + { + using (var tempEdges = PooledList.Get()) + using (var tempSlots = PooledList.Get()) + { + // Loop through all nodes that the node feeds into. + if (dir == PropagationDirection.Downstream) + node.GetOutputSlots(tempSlots); + else + node.GetInputSlots(tempSlots); + + foreach (var slot in tempSlots) + { + // get the edges out of each slot + tempEdges.Clear(); // and here we serialize another list, ouch! + node.owner.GetEdges(slot.slotReference, tempEdges); + foreach (var edge in tempEdges) + { + // We look at each node we feed into. + var connectedSlot = (dir == PropagationDirection.Downstream) ? edge.inputSlot : edge.outputSlot; + var connectedNode = connectedSlot.node; + + action(connectedNode); + } + } + } + } + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/BakeTextureManager.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/BakeTextureManager.cs.meta new file mode 100644 index 0000000..3885d1d --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/BakeTextureManager.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5137c095bd891b840abd2a0f12c5723e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls.meta new file mode 100644 index 0000000..e06b264 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: ba6f5b66a775b7a4d8abf1c7007d1890 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/LabelControl.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/LabelControl.cs new file mode 100644 index 0000000..342085d --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/LabelControl.cs @@ -0,0 +1,63 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using System.Reflection; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Drawing.Controls; +using UnityEngine.UIElements; + +namespace ShaderGraphEssentials +{ + [AttributeUsage(AttributeTargets.Property)] + class LabelControlAttribute : Attribute, IControlAttribute + { + string m_Label; + + public LabelControlAttribute(string label = null) + { + m_Label = label; + } + + public VisualElement InstantiateControl(AbstractMaterialNode node, PropertyInfo propertyInfo) + { + return new LabelControlView(m_Label, node, propertyInfo); + } + } + + class LabelControlView : VisualElement + { + AbstractMaterialNode m_Node; + PropertyInfo m_PropertyInfo; + + public LabelControlView(string label, AbstractMaterialNode node, PropertyInfo propertyInfo) + { + if (propertyInfo.PropertyType != typeof(string)) + throw new ArgumentException("Property must be of type string", nameof(propertyInfo)); + m_Node = node; + m_PropertyInfo = propertyInfo; + label = label ?? propertyInfo.Name; + + var labelText = (string) m_PropertyInfo.GetValue(m_Node, null); + + if (string.IsNullOrEmpty(label)) + Add(new Label { text = labelText }); + else + Add(new Label { text = label + ": " + labelText }); + } + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/LabelControl.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/LabelControl.cs.meta new file mode 100644 index 0000000..a049e5a --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/LabelControl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 31d397cf980147445a9e054fd7b13e38 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoiseDimensionEnumControl.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoiseDimensionEnumControl.cs new file mode 100644 index 0000000..664db92 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoiseDimensionEnumControl.cs @@ -0,0 +1,139 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using System.Collections.Generic; +using System.Reflection; +using UnityEditor; +using UnityEditor.Experimental.UIElements; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Drawing; +using UnityEditor.ShaderGraph.Drawing.Controls; +using UnityEditor.UIElements; +using UnityEngine; +using UnityEngine.UIElements; + + +namespace ShaderGraphEssentials +{ + [AttributeUsage(AttributeTargets.Property)] + class NoiseDimensionEnumControlAttribute : Attribute, IControlAttribute + { + string m_Label; + int m_SlotId; + + public NoiseDimensionEnumControlAttribute(string label = null, int slotId = 0) + { + m_Label = label; + m_SlotId = slotId; + } + + public VisualElement InstantiateControl(AbstractMaterialNode node, PropertyInfo propertyInfo) + { + return new NoiseDimensionEnumControlView(m_Label, m_SlotId, node, propertyInfo); + } + } + + class NoiseDimensionEnumControlView : VisualElement, AbstractMaterialNodeModificationListener + { + NoiseNode m_Node; + PropertyInfo m_PropertyInfo; + int m_SlotId; + + PopupField m_PopupField; + string[] m_ValueNames; + + NoiseDimension[] m_previousNoiseDimensions = new NoiseDimension[0]; + + public NoiseDimensionEnumControlView(string label, int slotId, AbstractMaterialNode node, PropertyInfo propertyInfo) + { + styleSheets.Add(Resources.Load("Styles/Controls/NoiseDimensionEnumControlView")); + m_PropertyInfo = propertyInfo; + m_SlotId = slotId; + if (!propertyInfo.PropertyType.IsEnum) + throw new ArgumentException("Property must be an enum.", "propertyInfo"); + NoiseNode noiseNode = node as NoiseNode; + if (noiseNode == null) + throw new ArgumentException("NoiseDimensionEnumControl can only be applied on NoiseNode.", "node"); + m_Node = noiseNode; + + Add(new Label(label ?? ObjectNames.NicifyVariableName(propertyInfo.Name))); + + m_ValueNames = NoiseDimensionUtils.GetDisplayNames(); + + CreatePopup(); + } + + void OnValueChanged(ChangeEvent evt) + { + var index = m_PopupField.index; + var value = (int)m_PropertyInfo.GetValue(m_Node, null); + if (!index.Equals(value)) + { + m_Node.owner.owner.RegisterCompleteObjectUndo("Change " + m_Node.name); + m_PropertyInfo.SetValue(m_Node, index, null); + } + + CreatePopup(); + } + + public void OnNodeModified(ModificationScope scope) + { + CreatePopup(); + m_PopupField.MarkDirtyRepaint(); + } + + void CreatePopup() + { + var supportedDimensions = m_Node.Noise.GetSupportedDimensions(); + + if (m_PopupField != null) + { + if (supportedDimensions.Length == m_previousNoiseDimensions.Length) + { + bool identical = true; + for (int i = 0; i < supportedDimensions.Length; i++) + { + if (supportedDimensions[i] == m_previousNoiseDimensions[i]) + continue; + identical = false; + break; + } + + if (identical) + return; + } + + Remove(m_PopupField); + } + + m_previousNoiseDimensions = supportedDimensions; + List popupEntries = new List(); + for (int i = 0; i < m_previousNoiseDimensions.Length; i++) + popupEntries.Add(m_ValueNames[i]); + + var value = (int)m_PropertyInfo.GetValue(m_Node, null); + if (value >= m_previousNoiseDimensions.Length) + value = 0; + + m_PopupField = new PopupField(popupEntries, value); + m_PopupField.RegisterValueChangedCallback(OnValueChanged); + Add(m_PopupField); + } + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoiseDimensionEnumControl.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoiseDimensionEnumControl.cs.meta new file mode 100644 index 0000000..4b28544 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoiseDimensionEnumControl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d05d9af0ac1bdb845888d9d4358dcd48 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoisePeriodicityEnumControl.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoisePeriodicityEnumControl.cs new file mode 100644 index 0000000..36e5a35 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoisePeriodicityEnumControl.cs @@ -0,0 +1,139 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using System.Collections.Generic; +using System.Reflection; +using UnityEditor; +using UnityEditor.Experimental.UIElements; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Drawing; +using UnityEditor.ShaderGraph.Drawing.Controls; +using UnityEditor.UIElements; +using UnityEngine; +using UnityEngine.UIElements; + + +namespace ShaderGraphEssentials +{ + [AttributeUsage(AttributeTargets.Property)] + class NoisePeriodicityEnumControlAttribute : Attribute, IControlAttribute + { + string m_Label; + int m_SlotId; + + public NoisePeriodicityEnumControlAttribute(string label = null, int slotId = 0) + { + m_Label = label; + m_SlotId = slotId; + } + + public VisualElement InstantiateControl(AbstractMaterialNode node, PropertyInfo propertyInfo) + { + return new NoisePeriodicityEnumControlView(m_Label, m_SlotId, node, propertyInfo); + } + } + + class NoisePeriodicityEnumControlView : VisualElement, AbstractMaterialNodeModificationListener + { + NoiseNode m_Node; + PropertyInfo m_PropertyInfo; + int m_SlotId; + + PopupField m_PopupField; + string[] m_ValueNames; + + NoisePeriodicity[] m_previousNoisePeriodicities = new NoisePeriodicity[0]; + + public NoisePeriodicityEnumControlView(string label, int slotId, AbstractMaterialNode node, PropertyInfo propertyInfo) + { + styleSheets.Add(Resources.Load("Styles/Controls/NoisePeriodicityEnumControlView")); + m_PropertyInfo = propertyInfo; + m_SlotId = slotId; + if (!propertyInfo.PropertyType.IsEnum) + throw new ArgumentException("Property must be an enum.", "propertyInfo"); + NoiseNode noiseNode = node as NoiseNode; + if (noiseNode == null) + throw new ArgumentException("NoisePeriodicityEnumControl can only be applied on NoiseNode.", "node"); + m_Node = noiseNode; + + Add(new Label(label ?? ObjectNames.NicifyVariableName(propertyInfo.Name))); + + m_ValueNames = NoisePeriodicityUtils.GetDisplayNames(); + + CreatePopup(); + } + + void OnValueChanged(ChangeEvent evt) + { + var index = m_PopupField.index; + var value = (int)m_PropertyInfo.GetValue(m_Node, null); + if (!index.Equals(value)) + { + m_Node.owner.owner.RegisterCompleteObjectUndo("Change " + m_Node.name); + m_PropertyInfo.SetValue(m_Node, index, null); + } + + CreatePopup(); + } + + public void OnNodeModified(ModificationScope scope) + { + CreatePopup(); + m_PopupField.MarkDirtyRepaint(); + } + + void CreatePopup() + { + var supportedPeriodicities = m_Node.Noise.GetSupportedPeriodicities(); + + if (m_PopupField != null) + { + if (supportedPeriodicities.Length == m_previousNoisePeriodicities.Length) + { + bool identical = true; + for (int i = 0; i < supportedPeriodicities.Length; i++) + { + if (supportedPeriodicities[i] == m_previousNoisePeriodicities[i]) + continue; + identical = false; + break; + } + + if (identical) + return; + } + + Remove(m_PopupField); + } + + m_previousNoisePeriodicities = supportedPeriodicities; + List popupEntries = new List(); + for (int i = 0; i < m_previousNoisePeriodicities.Length; i++) + popupEntries.Add(m_ValueNames[i]); + + var value = (int)m_PropertyInfo.GetValue(m_Node, null); + if (value >= m_previousNoisePeriodicities.Length) + value = 0; + + m_PopupField = new PopupField(popupEntries, value); + m_PopupField.RegisterValueChangedCallback(OnValueChanged); + Add(m_PopupField); + } + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoisePeriodicityEnumControl.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoisePeriodicityEnumControl.cs.meta new file mode 100644 index 0000000..ae391a6 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Controls/NoisePeriodicityEnumControl.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: bfd35b78c9062f948b58a867d5dead07 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes.meta new file mode 100644 index 0000000..fffa9b9 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3b5c559d9c416b44b8c04654489a5a25 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/BakeTextureNode.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/BakeTextureNode.cs new file mode 100644 index 0000000..9207aab --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/BakeTextureNode.cs @@ -0,0 +1,162 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using System.Collections.Generic; +using System.Reflection; +using UnityEditor; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Drawing.Controls; +using UnityEditor.ShaderGraph.Internal; +using UnityEngine; +using UnityEngine.UIElements; + + +namespace ShaderGraphEssentials +{ + class BakeTextureControlAttribute : Attribute, IControlAttribute + { + VisualElement IControlAttribute.InstantiateControl(AbstractMaterialNode node, PropertyInfo propertyInfo) + { + if (!(node is BakeTextureNode)) + throw new ArgumentException("Node must inherit from BakeTextureNode.", "node"); + return new BakeTextureControlView((BakeTextureNode)node); + } + } + + class BakeTextureControlView : VisualElement + { + BakeTextureNode m_Node; + + public BakeTextureControlView(BakeTextureNode node) + { + m_Node = node; + Add(new Button(OnBakeTexture) { text = "Bake Texture" }); + } + + void OnBakeTexture() + { + m_Node.OnBakeTexture(); + } + } + + [Title("Utility", "Bake Texture")] + class BakeTextureNode : CodeFunctionNode + { + public override bool hasPreview { get { return true; } } + + [SerializeField] + private int m_width = 256; + [IntegerControl("Width")] + public int Width + { + get { return m_width; } + set + { + if (m_width == value) + return; + + m_width = value; + + Dirty(ModificationScope.Node); + } + } + + [SerializeField] + private int m_height = 256; + [IntegerControl("Height")] + public int Height + { + get { return m_height; } + set + { + if (m_height == value) + return; + + m_height = value; + + Dirty(ModificationScope.Node); + } + } + + [SerializeField] + private SerializableTexture m_outputTexture = new SerializableTexture(); + + [TextureControl("Output texture")] + public Texture OutputTexture + { + get { return m_outputTexture.texture; } + set + { + if (m_outputTexture.texture == value) + return; + m_outputTexture.texture = value; + Dirty(ModificationScope.Node); + } + } + + [BakeTextureControl] + int controlDummy { get; set; } + + public BakeTextureNode() + { + name = "Bake Texture"; + } + + protected override MethodInfo GetFunctionToConvert() + { + return GetType().GetMethod("PreviewFunction", BindingFlags.Static | BindingFlags.NonPublic); + } + + + + static string PreviewFunction( + [Slot(0, Binding.None)] DynamicDimensionVector In, + [Slot(1, Binding.None)] out DynamicDimensionVector Out) + { + return + @" +{ + Out = In; +} +"; + } + + internal void OnBakeTexture() + { + var graph = owner; + var wasAsyncAllowed = ShaderUtil.allowAsyncCompilation; + // we don't handle async compilation here, the user is waiting for it anyway + ShaderUtil.allowAsyncCompilation = false; + + var generator = new Generator(owner, this, GenerationMode.Preview, $"hidden/preview/{this.GetVariableNameForNode()}", null); + + BakeShaderData shaderData = new BakeShaderData(); + shaderData.ShaderString = generator.generatedShader; // TODO maybe shader isn't generated yet? + shaderData.Shader = ShaderUtil.CreateShaderAsset(shaderData.ShaderString); + shaderData.Node = this; + shaderData.Graph = graph; + shaderData.HasError = false; // TODO handle shader errors + shaderData.OutputIdName = "Out"; + + BakeTextureManager.BakeShaderIntoTexture(shaderData); + + ShaderUtil.allowAsyncCompilation = wasAsyncAllowed; + } + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/BakeTextureNode.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/BakeTextureNode.cs.meta new file mode 100644 index 0000000..5e6fd9c --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/BakeTextureNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b7dbe737a5cf86a428ad601b0ed7dd02 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NoiseNode.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NoiseNode.cs new file mode 100644 index 0000000..1e205da --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NoiseNode.cs @@ -0,0 +1,419 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using System.Collections.Generic; +using UnityEditor.Graphing; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Drawing.Controls; +using UnityEditor.ShaderGraph.Internal; +using UnityEngine; + +namespace ShaderGraphEssentials +{ + [Title("Procedural", "Noise", "SGE Noise")] + class NoiseNode : AbstractMaterialNode, IGeneratesBodyCode, IGeneratesFunction, IMayRequireMeshUV + { + public override bool hasPreview { get { return true; } } + + const int UvSlotId = 0; + const int PeriodSlotId = 1; + const int PersistenceSlotId = 2; + const int LacunaritySlotId = 3; + const int SharpnessSlotId = 5; + const int OutputSlotId = 4; + const string kUvSlotName = "Uv"; + const string kPeriodSlotName = "Period"; + const string kPersistenceSlotName = "Persistence"; + const string kLacunaritySlotName = "Lacunarity"; + const string kSharpnessSlotName = "Sharpness"; + const string kOutputSlotName = "Out"; + + public NoiseBase Noise; + + [SerializeField] + private NoiseType m_noiseType = NoiseType.Value; + [EnumControl("Type")] + public NoiseType Type + { + get { return m_noiseType; } + set + { + if (m_noiseType == value) + return; + + m_noiseType = value; + InitializeNoiseAccordingToType(); + Dirty(ModificationScope.Graph); + } + } + + [SerializeField] + private NoiseCombine m_noiseCombine = NoiseCombine.Simple; + [EnumControl("Combine")] + public NoiseCombine Combine + { + get { return m_noiseCombine; } + set + { + if (m_noiseCombine == value) + return; + + m_noiseCombine = value; + Noise.Combine = value; + UpdateSlots(); + Dirty(ModificationScope.Graph); + } + } + + [SerializeField] + private NoiseDimension m_noiseDimension = NoiseDimension.D2; + [NoiseDimensionEnumControl("Dimension")] + public NoiseDimension Dimension + { + get + { + return m_noiseDimension; + } + set + { + if (m_noiseDimension == value) + return; + m_noiseDimension = value; + Noise.Dimension = value; + UpdateSlots(); + Dirty(ModificationScope.Graph); + } + } + + [SerializeField] + private NoisePeriodicity m_noisePeriodicity = NoisePeriodicity.NonPeriodic; + [NoisePeriodicityEnumControl("Periodicity")] + public NoisePeriodicity Periodicity + { + get + { + return m_noisePeriodicity; + } + set + { + if (m_noisePeriodicity == value) + return; + m_noisePeriodicity = value; + Noise.Periodicity = value; + UpdateSlots(); + Dirty(ModificationScope.Graph); + } + } + + public NoiseNode() + { + name = "SGE Noise"; + UpdateNodeAfterDeserialization(); + } + + private void InitializeNoiseAccordingToType() + { + switch (m_noiseType) + { + case NoiseType.Value: + Noise = new ValueNoise(m_noiseCombine, m_noiseDimension, m_noisePeriodicity); + break; + case NoiseType.Simplex: + Noise = new SimplexNoise(m_noiseCombine, m_noiseDimension, m_noisePeriodicity); + break; + case NoiseType.Perlin: + Noise = new PerlinNoise(m_noiseCombine, m_noiseDimension, m_noisePeriodicity); + break; + default: + throw new ArgumentOutOfRangeException(nameof(m_noiseType), m_noiseType, null); + } + + UpdateSlots(); + } + + private void ValidateNoisePeriodicity() + { + if (Noise == null) + return; + + var supported = Noise.GetSupportedPeriodicities(); + bool isCurrentPeriodicitySupported = false; + for (int i = 0; i < supported.Length; i++) + { + if (supported[i] == Periodicity) + { + isCurrentPeriodicitySupported = true; + break; + } + } + + if (!isCurrentPeriodicitySupported) + Periodicity = supported[0]; + } + + private void ValidateNoiseDimension() + { + if (Noise == null) + return; + + var supported = Noise.GetSupportedDimensions(); + bool isCurrentDimensionSupported = false; + for (int i = 0; i < supported.Length; i++) + { + if (supported[i] == Dimension) + { + isCurrentDimensionSupported = true; + break; + } + } + + if (!isCurrentDimensionSupported) + Dimension = supported[0]; + } + + private void UpdateSlots() + { + ValidateNoiseDimension(); + ValidateNoisePeriodicity(); + + var idList = new List { UvSlotId, OutputSlotId }; + + if (Dimension == NoiseDimension.D2) + AddSlot(new UVMaterialSlot(UvSlotId, kUvSlotName, kUvSlotName, UVChannel.UV0)); + else + AddSlot(new DynamicVectorMaterialSlot(UvSlotId, kUvSlotName, kUvSlotName, SlotType.Input, Vector4.zero)); + + AddSlot(new Vector1MaterialSlot(OutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, 0.0f)); + + if (IsNoiseSupported()) + { + if (m_noisePeriodicity == NoisePeriodicity.Periodic) + { + AddSlot(new Vector1MaterialSlot(PeriodSlotId, kPeriodSlotName, kPeriodSlotName, SlotType.Input, 1.0f)); + idList.Add(PeriodSlotId); + } + + if (m_noiseCombine == NoiseCombine.Fractal || m_noiseCombine == NoiseCombine.Turbulence || m_noiseCombine == NoiseCombine.Ridge) + { + AddSlot(new Vector1MaterialSlot(PersistenceSlotId, kPersistenceSlotName, kPersistenceSlotName, SlotType.Input, 0.5f)); + idList.Add(PersistenceSlotId); + AddSlot(new Vector1MaterialSlot(LacunaritySlotId, kLacunaritySlotName, kLacunaritySlotName, SlotType.Input, 2.0f)); + idList.Add(LacunaritySlotId); + } + + if (m_noiseCombine == NoiseCombine.Ridge) + { + AddSlot(new Vector1MaterialSlot(SharpnessSlotId, kSharpnessSlotName, kSharpnessSlotName, SlotType.Input, 1.0f)); + idList.Add(SharpnessSlotId); + } + } + + + RemoveSlotsNameNotMatching(idList, true); + + } + + public sealed override void UpdateNodeAfterDeserialization() + { + InitializeNoiseAccordingToType(); + UpdateSlots(); + } + + private bool IsNoiseSupported() + { + return Noise == null ? false : Noise.Support(); + } + + private string GetFunctionName() + { + bool isNoiseSupported = IsNoiseSupported(); + if (isNoiseSupported) + { + string functionName = "SGE_Noise"; + functionName += "_" + m_noiseType; + functionName += "_" + m_noisePeriodicity; + functionName += "_" + m_noiseCombine; + functionName += "_" + m_noiseDimension; + return functionName; + } + + return "SGE_UnsupportedNoise"; + } + + // generate how a node will be called in code + public void GenerateNodeCode(ShaderStringBuilder sb, GenerationMode generationMode) + { + bool isNoiseSupported = IsNoiseSupported(); + string inputValue = GetSlotValue(UvSlotId, generationMode); + string outputValue = GetSlotValue(OutputSlotId, generationMode); + + sb.AppendLine("{0} {1};", FindOutputSlot(OutputSlotId).concreteValueType.ToShaderString(ConcretePrecision.Single.ToShaderString()), GetVariableNameForSlot(OutputSlotId)); + + string functionCall = GetFunctionName() + "(" + inputValue + ", " + outputValue; + + if (isNoiseSupported) + { + if (m_noisePeriodicity == NoisePeriodicity.Periodic) + { + string periodValue = GetSlotValue(PeriodSlotId, generationMode); + functionCall += ", " + periodValue; + } + + if (m_noiseCombine == NoiseCombine.Fractal || m_noiseCombine == NoiseCombine.Turbulence || m_noiseCombine == NoiseCombine.Ridge) + { + string persistenceValue = GetSlotValue(PersistenceSlotId, generationMode); + string lacunarityValue = GetSlotValue(LacunaritySlotId, generationMode); + functionCall += ", " + persistenceValue + ", " + lacunarityValue; + } + + if (m_noiseCombine == NoiseCombine.Ridge) + { + string sharpnessValue = GetSlotValue(SharpnessSlotId, generationMode); + functionCall += ", " + sharpnessValue; + } + } + + functionCall += ");"; + + sb.AppendLine(functionCall); + } + + // generate the node's function + public void GenerateNodeFunction(FunctionRegistry registry, GenerationMode generationMode) + { + bool isNoiseSupported = IsNoiseSupported(); + string functionName = GetFunctionName(); + + if (isNoiseSupported) + Noise.RegisterFunctions(registry); + + registry.ProvideFunction(functionName, s => + { + var uvSlot = FindInputSlot(UvSlotId); + var outputSlot = FindOutputSlot(OutputSlotId); + + if (uvSlot == null) + throw new NullReferenceException("UvSlot null, how is it possible ?"); + if (outputSlot == null) + throw new NullReferenceException("outputSlot null, how is it possible ?"); + + s.Append("void {0}({1} {2}, out {3} {4}", + functionName, + uvSlot.concreteValueType.ToShaderString(ConcretePrecision.Single.ToShaderString()), + kUvSlotName, + outputSlot.concreteValueType.ToShaderString(ConcretePrecision.Single.ToShaderString()), + kOutputSlotName); + if (isNoiseSupported) + { + if (m_noisePeriodicity == NoisePeriodicity.Periodic) + { + var periodSlot = FindInputSlot(PeriodSlotId); + + if (periodSlot == null) + throw new NullReferenceException("periodSlot null, how is it possible ?"); + + s.Append(", {0} {1}", + periodSlot.concreteValueType.ToShaderString(ConcretePrecision.Single.ToShaderString()), + kPeriodSlotName); + } + if (m_noiseCombine == NoiseCombine.Fractal || m_noiseCombine == NoiseCombine.Turbulence || m_noiseCombine == NoiseCombine.Ridge) + { + var persistenceSlot = FindInputSlot(PersistenceSlotId); + var lacunaritySlot = FindInputSlot(LacunaritySlotId); + + if (persistenceSlot == null) + throw new NullReferenceException("persistenceSlot null, how is it possible ?"); + if (lacunaritySlot == null) + throw new NullReferenceException("lacunaritySlot null, how is it possible ?"); + + s.Append(", {0} {1}, {2} {3}", + persistenceSlot.concreteValueType.ToShaderString(ConcretePrecision.Single.ToShaderString()), + kPersistenceSlotName, + lacunaritySlot.concreteValueType.ToShaderString(ConcretePrecision.Single.ToShaderString()), + kLacunaritySlotName); + } + + if (m_noiseCombine == NoiseCombine.Ridge) + { + var sharpnessSlot = FindInputSlot(SharpnessSlotId); + + if (sharpnessSlot == null) + throw new NullReferenceException("sharpnessSlot null, how is it possible ?"); + + s.Append(", {0} {1}", + sharpnessSlot.concreteValueType.ToShaderString(ConcretePrecision.Single.ToShaderString()), + kSharpnessSlotName); + } + } + + s.AppendLine(")"); + + using (s.BlockScope()) + { + if (isNoiseSupported) + { + s.Append("{0} = {1}({2}", kOutputSlotName, Noise.GetNoiseFunctionName(), kUvSlotName); + + if (m_noisePeriodicity == NoisePeriodicity.Periodic) + { + s.Append(", pow(2, floor({0}))", kPeriodSlotName); + } + + if (m_noiseCombine == NoiseCombine.Fractal || m_noiseCombine == NoiseCombine.Turbulence || m_noiseCombine == NoiseCombine.Ridge) + { + s.Append(", {0}, {1}", kPersistenceSlotName, kLacunaritySlotName); + } + + if (m_noiseCombine == NoiseCombine.Ridge) + { + s.Append(", {0}", kSharpnessSlotName); + } + + s.Append(")"); + + if (Noise.NeedRemapTo0_1()) + s.Append(" * 0.5 + 0.5"); + s.AppendLine(";"); + } + else + { + s.AppendLine("{0} = {1};", kOutputSlotName, kUvSlotName); + } + } + }); + } + + public bool RequiresMeshUV(UVChannel channel, ShaderStageCapability stageCapability) + { + if (Dimension != NoiseDimension.D2) + return false; + + using (var tempSlots = PooledList.Get()) + { + GetInputSlots(tempSlots); + foreach (var slot in tempSlots) + { + if (slot.RequiresMeshUV(channel)) + return true; + } + + return false; + } + } + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NoiseNode.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NoiseNode.cs.meta new file mode 100644 index 0000000..499fb7f --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NoiseNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b03f53e47b88fc0479be04d4a28d0cde +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalFromHeightVectorNode.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalFromHeightVectorNode.cs new file mode 100644 index 0000000..1fcf73a --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalFromHeightVectorNode.cs @@ -0,0 +1,54 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System.Reflection; +using UnityEditor.ShaderGraph; +using UnityEngine; + +[Title("Artistic", "Normal", "Create Normal from Height vector")] +class NormalFromHeightVectorNode : CodeFunctionNode +{ + public NormalFromHeightVectorNode() + { + name = "Create Normal from Height vector"; + } + + protected override MethodInfo GetFunctionToConvert() + { + return GetType().GetMethod("NormalFromHeightVectorFunction", + BindingFlags.Static | BindingFlags.NonPublic); + } + + static string NormalFromHeightVectorFunction( + [Slot(0, Binding.None)] Vector1 Height, + [Slot(1, Binding.None)] Vector1 UOffset, + [Slot(2, Binding.None)] Vector1 VOffset, + [Slot(3, Binding.None, 1f, 1f, 1f, 1f)] Vector1 Strength, + [Slot(4, Binding.None)] out Vector3 Out) + { + Out = Vector3.forward; + return + + @" +{ + float3 va = float3(1, 0, (UOffset - Height) * Strength); + float3 vb = float3(0, 1, (VOffset - Height) * Strength); + Out = normalize(cross(va, vb)); +} +"; + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalFromHeightVectorNode.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalFromHeightVectorNode.cs.meta new file mode 100644 index 0000000..3a16a61 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalFromHeightVectorNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8ae5760f57c1a0144bc20ac7b0704c17 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalUOffsetNode.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalUOffsetNode.cs new file mode 100644 index 0000000..a969477 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalUOffsetNode.cs @@ -0,0 +1,51 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System.Reflection; +using UnityEditor.ShaderGraph; +using UnityEngine; + +[Title("Artistic", "Normal", "Create Normal U Offset")] +class NormalUOffsetNode : CodeFunctionNode +{ + public NormalUOffsetNode() + { + name = "Create Normal U Offset"; + } + + protected override MethodInfo GetFunctionToConvert() + { + return GetType().GetMethod("NormalUOffsetFunction", + BindingFlags.Static | BindingFlags.NonPublic); + } + + static string NormalUOffsetFunction( + [Slot(0, Binding.MeshUV0)] Vector2 Uv, + [Slot(1, Binding.None, 1f, 1f, 1f, 1f)] Vector1 Offset, + [Slot(2, Binding.None)] out Vector2 Out) + { + Out = Vector2.zero; + return + + @" +{ + float offset = pow(Offset, 3) * 0.1; + Out = float2(Uv.x + offset, Uv.y); +} +"; + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalUOffsetNode.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalUOffsetNode.cs.meta new file mode 100644 index 0000000..fb01c80 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalUOffsetNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f961cef2bf0bcd34f8b00182eef4458a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalVOffsetNode.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalVOffsetNode.cs new file mode 100644 index 0000000..6bb84f4 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalVOffsetNode.cs @@ -0,0 +1,51 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System.Reflection; +using UnityEditor.ShaderGraph; +using UnityEngine; + +[Title("Artistic", "Normal", "Create Normal V Offset")] +class NormalVOffsetNode : CodeFunctionNode +{ + public NormalVOffsetNode() + { + name = "Create Normal V Offset"; + } + + protected override MethodInfo GetFunctionToConvert() + { + return GetType().GetMethod("NormalVOffsetFunction", + BindingFlags.Static | BindingFlags.NonPublic); + } + + static string NormalVOffsetFunction( + [Slot(0, Binding.MeshUV0)] Vector2 Uv, + [Slot(1, Binding.None, 1f, 1f, 1f, 1f)] Vector1 Offset, + [Slot(2, Binding.None)] out Vector2 Out) + { + Out = Vector2.zero; + return + + @" +{ + float offset = pow(Offset, 3) * 0.1; + Out = float2(Uv.x, Uv.y + offset); +} +"; + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalVOffsetNode.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalVOffsetNode.cs.meta new file mode 100644 index 0000000..b6ff4e1 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Nodes/NormalVOffsetNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3dc125d912c9f31479400894ede9a199 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises.meta new file mode 100644 index 0000000..5917dc9 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 58e3529e56bdbc042a6cff97fc2d8885 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseBase.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseBase.cs new file mode 100644 index 0000000..403eb12 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseBase.cs @@ -0,0 +1,45 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using UnityEditor.ShaderGraph; + +namespace ShaderGraphEssentials +{ + public abstract class NoiseBase + { + public NoiseCombine Combine { get; set; } + public NoiseDimension Dimension { get; set; } + public NoisePeriodicity Periodicity { get; set; } + + protected NoiseBase(NoiseCombine combine, NoiseDimension dimension, NoisePeriodicity periodicity) + { + Combine = combine; + Dimension = dimension; + Periodicity = periodicity; + } + + public abstract bool Support(); + public abstract NoiseDimension[] GetSupportedDimensions(); + public abstract NoisePeriodicity[] GetSupportedPeriodicities(); + public abstract string GetNoiseFunctionName(); + internal abstract void RegisterFunctions(FunctionRegistry registry); + public virtual bool NeedRemapTo0_1() + { + return false; + } + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseBase.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseBase.cs.meta new file mode 100644 index 0000000..5081e62 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseBase.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e10efe297bc3aea4fbdc8e4147ab0178 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseCombine.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseCombine.cs new file mode 100644 index 0000000..451ccbc --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseCombine.cs @@ -0,0 +1,27 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +namespace ShaderGraphEssentials +{ + public enum NoiseCombine + { + Simple, + Fractal, + Turbulence, + Ridge + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseCombine.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseCombine.cs.meta new file mode 100644 index 0000000..bd35a64 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseCombine.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 468957cccb71d1a46985d58b77ee6f99 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseDimension.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseDimension.cs new file mode 100644 index 0000000..ddf4fa1 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseDimension.cs @@ -0,0 +1,60 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +namespace ShaderGraphEssentials +{ + public enum NoiseDimension + { + // you can have an enum value start with a figure + D2, + D3 + } + + public static class NoiseDimensionUtils + { + public static string ToDisplayName(this NoiseDimension dimension) + { + switch (dimension) + { + case NoiseDimension.D2: + return "2D"; + case NoiseDimension.D3: + return "3D"; + } + + return "Unknown Dimension"; + } + + public static string ToShaderVectorEquivalent(this NoiseDimension dimension) + { + switch (dimension) + { + case NoiseDimension.D2: + return "float2"; + case NoiseDimension.D3: + return "float3"; + } + + return "Unknown Dimension"; + } + + public static string[] GetDisplayNames() + { + return new[] {NoiseDimension.D2.ToDisplayName(), NoiseDimension.D3.ToDisplayName()}; + } + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseDimension.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseDimension.cs.meta new file mode 100644 index 0000000..be239e7 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseDimension.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d8584ab31558d994b9dfae34a08a8a58 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoisePeriodicity.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoisePeriodicity.cs new file mode 100644 index 0000000..131329c --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoisePeriodicity.cs @@ -0,0 +1,59 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +namespace ShaderGraphEssentials +{ + public enum NoisePeriodicity + { + NonPeriodic, + Periodic + } + + public static class NoisePeriodicityUtils + { + public static string ToDisplayName(this NoisePeriodicity dimension) + { + switch (dimension) + { + case NoisePeriodicity.NonPeriodic: + return "Non periodic"; + case NoisePeriodicity.Periodic: + return "Periodic"; + } + + return "Unknown Periodicity"; + } + + public static string ToFunctionNameEquivalent(this NoisePeriodicity dimension) + { + switch (dimension) + { + case NoisePeriodicity.NonPeriodic: + return ""; + case NoisePeriodicity.Periodic: + return "Periodic"; + } + + return "Unknown Periodicity"; + } + + public static string[] GetDisplayNames() + { + return new[] { NoisePeriodicity.NonPeriodic.ToDisplayName(), NoisePeriodicity.Periodic.ToDisplayName() }; + } + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoisePeriodicity.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoisePeriodicity.cs.meta new file mode 100644 index 0000000..77f4da4 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoisePeriodicity.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 6aaccfec24042f245a20bc72478add18 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseShaderUtils.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseShaderUtils.cs new file mode 100644 index 0000000..a70ad3a --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseShaderUtils.cs @@ -0,0 +1,606 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using UnityEditor.ShaderGraph; + +namespace ShaderGraphEssentials +{ + class ShaderUtils + { + public static void RandomValue2dTo1dFunction(FunctionRegistry registry) + { + registry.ProvideFunction("SGE_RandomValue2dTo1d", s => s.Append(@" +inline float SGE_RandomValue2dTo1d(float2 uv) +{ + return frac(sin(dot(uv, float2(12.9898, 78.233)))*43758.5453) * 2.0 - 1.0; +}")); + } + + public static void RandomValue2dTo2dFunction(FunctionRegistry registry) + { + registry.ProvideFunction("SGE_RandomValue2dTo2d", s => s.Append(@" +inline float2 SGE_RandomValue2dTo2d(float2 p) +{ + // Permutation and hashing used in webgl-nosie goo.gl/pX7HtC + p = p % 289; + float x = (34 * p.x + 1) * p.x % 289 + p.y; + x = (34 * x + 1) * x % 289; + x = frac(x / 41) * 2 - 1; + return normalize(float2(x - floor(x + 0.5), abs(x) - 0.5)); +}")); + } + + public static string ValueNoiseFunctionName = "SGE_ValueNoise"; + public static void ValueNoiseFunction(FunctionRegistry registry) + { + registry.ProvideFunction(ValueNoiseFunctionName, s => s.Append(@" +inline float " + ValueNoiseFunctionName + @"(float2 uv) +{ + float2 i = floor(uv); + float2 f = frac(uv); + float2 u = f*f*(3.0-2.0*f); + + return lerp(lerp(SGE_RandomValue2dTo1d(i), + SGE_RandomValue2dTo1d(i + float2(1.0, 0.0)), u.x), + lerp(SGE_RandomValue2dTo1d(i + float2(0.0, 1.0)), + SGE_RandomValue2dTo1d(i + float2(1.0, 1.0)), u.x), u.y); +}")); + } + + // from https://www.shadertoy.com/view/3d2GRh + // The MIT License + // Copyright © 2019 Inigo Quilez + // 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + public static string PeriodicValueNoiseFunctionName = "SGE_PeriodicValueNoise"; + public static void PeriodicValueNoiseFunction(FunctionRegistry registry) + { + registry.ProvideFunction(PeriodicValueNoiseFunctionName, s => s.Append(@" +inline float " + PeriodicValueNoiseFunctionName + @"(float2 uv, int p) +{ + float2 rescaledUv = uv * p; + int2 i = floor(rescaledUv); + float2 f = frac(rescaledUv); + float2 u = f*f*(3.0-2.0*f); + + return lerp(lerp(SGE_RandomValue2dTo1d(i &(p - 1)), + SGE_RandomValue2dTo1d((i + int2(1, 0)) &(p - 1)), u.x), + lerp(SGE_RandomValue2dTo1d((i + int2(0, 1)) &(p - 1)), + SGE_RandomValue2dTo1d((i + int2(1, 1)) &(p - 1)), u.x), u.y); +}")); + } + + public static string GradientNoiseFunctionName = "SGE_GradientNoise"; + public static void GradientNoiseFunction(FunctionRegistry registry) + { + registry.ProvideFunction(GradientNoiseFunctionName, s => s.Append(@" +inline float " + GradientNoiseFunctionName + @"(float2 uv) +{ + float2 i = floor(uv); + float2 f = frac(uv); + float2 u = f*f*(3.0-2.0*f); + + return lerp(lerp(dot(SGE_RandomValue2dTo2d(i), f), + dot(SGE_RandomValue2dTo2d(i + float2(1.0, 0.0)), f - float2(1.0,0.0)), u.x), + lerp(dot(SGE_RandomValue2dTo2d(i + float2(0.0, 1.0)), f - float2(0.0,1.0)), + dot(SGE_RandomValue2dTo2d(i + float2(1.0, 1.0)), f - float2(1.0,1.0)), u.x), u.y); +}")); + } + + public static string SimplexNoiseFunctionName = "SGE_SimplexNoise"; + // from https://www.shadertoy.com/view/Msf3WH + // The MIT License + // Copyright © 2013 Inigo Quilez + // 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: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + public static void SimplexNoiseFunction(FunctionRegistry registry) + { + registry.ProvideFunction(SimplexNoiseFunctionName, s => s.Append(@" +inline float " + SimplexNoiseFunctionName + @"(float2 uv) +{ + const float K1 = 0.366025404; // (sqrt(3) - 1)/ 2; + const float K2 = 0.211324865; // (3 - sqrt(3)) / 6; + + float2 i = floor(uv + (uv.x + uv.y) * K1); + + float2 a = uv - i + (i.x + i.y) * K2; + float m = step(a.y, a.x); + float2 o = float2(m, 1.0 - m); + float2 b = a - o + K2; + float2 c = a - 1.0 + 2.0 * K2; + + float3 h = max(0.5 - float3(dot(a, a), dot(b, b), dot(c, c)), 0.0); + + float3 n = h * h * h * h * float3(dot(a, SGE_RandomValue2dTo2d(i + 0.0)), + dot(b, SGE_RandomValue2dTo2d(i + o)), + dot(c, SGE_RandomValue2dTo2d(i + 1.0))); + + return dot(n, float3(70.0, 70.0, 70.0)); +}")); + } + + // + // Noise Shader Library for Unity - https://github.com/keijiro/NoiseShader + // + // Original work (webgl-noise) Copyright (C) 2011 Stefan Gustavson + // Translation and modification was made by Keijiro Takahashi. + // + // This shader is based on the webgl-noise GLSL shader. For further details + // of the original shader, please see the following description from the + // original source code. + // + + // + // GLSL textureless classic 2D noise "cnoise", + // with an RSL-style periodic variant "pnoise". + // Author: Stefan Gustavson (stefan.gustavson@liu.se) + // Version: 2011-08-22 + // + // Many thanks to Ian McEwan of Ashima Arts for the + // ideas for permutation and gradient selection. + // + // Copyright (c) 2011 Stefan Gustavson. All rights reserved. + // Distributed under the MIT license. See LICENSE file. + // https://github.com/ashima/webgl-noise + + public static void PerlinNoiseHelperFunction(FunctionRegistry registry) + { + registry.ProvideFunction("SGE_Mod_F4", s => s.Append(@" +inline float4 SGE_Mod_F4(float4 x, float4 y) +{ + return x - y * floor(x / y); +}")); + + registry.ProvideFunction("SGE_Mod_F3", s => s.Append(@" +inline float3 SGE_Mod_F3(float3 x, float3 y) +{ + return x - y * floor(x / y); +}")); + + registry.ProvideFunction("SGE_Mod289_F4", s => s.Append(@" +inline float4 SGE_Mod289_F4(float4 x) +{ + return x - floor(x / 289.0) * 289.0; +}")); + + registry.ProvideFunction("SGE_Mod289_F3", s => s.Append(@" +inline float3 SGE_Mod289_F3(float3 x) +{ + return x - floor(x / 289.0) * 289.0; +}")); + + registry.ProvideFunction("SGE_Permute", s => s.Append(@" +inline float4 SGE_Permute(float4 x) +{ + return SGE_Mod289_F4(((x*34.0)+1.0)*x); +}")); + + registry.ProvideFunction("SGE_TaylorInvSqrt", s => s.Append(@" +inline float4 SGE_TaylorInvSqrt(float4 r) +{ + return (float4)1.79284291400159 - r * 0.85373472095314; +}")); + + registry.ProvideFunction("SGE_Fade_F2", s => s.Append(@" +inline float2 SGE_Fade_F2(float2 t) +{ + return t*t*t*(t*(t*6.0-15.0)+10.0); +}")); + + registry.ProvideFunction("SGE_Fade_F3", s => s.Append(@" +inline float3 SGE_Fade_F3(float3 t) +{ + return t*t*t*(t*(t*6.0-15.0)+10.0); +}")); + } + + public static string PerlinNoiseFunctionName = "SGE_PerlinNoise"; + public static void PerlinNoiseFunction(FunctionRegistry registry) + { + PerlinNoiseHelperFunction(registry); + + registry.ProvideFunction(PerlinNoiseFunctionName, s => s.Append(@" +inline float " + PerlinNoiseFunctionName + @"(float2 uv) +{ + float4 Pi = floor(uv.xyxy) + float4(0.0, 0.0, 1.0, 1.0); + float4 Pf = frac (uv.xyxy) - float4(0.0, 0.0, 1.0, 1.0); + Pi = SGE_Mod289_F4(Pi); // To avoid truncation effects in permutation + float4 ix = Pi.xzxz; + float4 iy = Pi.yyww; + float4 fx = Pf.xzxz; + float4 fy = Pf.yyww; + + float4 i = SGE_Permute(SGE_Permute(ix) + iy); + + float4 gx = frac(i / 41.0) * 2.0 - 1.0 ; + float4 gy = abs(gx) - 0.5 ; + float4 tx = floor(gx + 0.5); + gx = gx - tx; + + float2 g00 = float2(gx.x,gy.x); + float2 g10 = float2(gx.y,gy.y); + float2 g01 = float2(gx.z,gy.z); + float2 g11 = float2(gx.w,gy.w); + + float4 norm = SGE_TaylorInvSqrt(float4(dot(g00, g00), dot(g01, g01), dot(g10, g10), dot(g11, g11))); + g00 *= norm.x; + g01 *= norm.y; + g10 *= norm.z; + g11 *= norm.w; + + float n00 = dot(g00, float2(fx.x, fy.x)); + float n10 = dot(g10, float2(fx.y, fy.y)); + float n01 = dot(g01, float2(fx.z, fy.z)); + float n11 = dot(g11, float2(fx.w, fy.w)); + + float2 fade_xy = SGE_Fade_F2(Pf.xy); + float2 n_x = lerp(float2(n00, n01), float2(n10, n11), fade_xy.x); + float n_xy = lerp(n_x.x, n_x.y, fade_xy.y); + return 2.3 * n_xy; +}")); + } + + public static string PeriodicPerlinNoiseFunctionName = "SGE_PeriodicPerlinNoise"; + public static void PeriodicPerlinNoiseFunction(FunctionRegistry registry) + { + PerlinNoiseHelperFunction(registry); + + registry.ProvideFunction(PeriodicPerlinNoiseFunctionName, s => s.Append(@" +inline float " + PeriodicPerlinNoiseFunctionName + @"(float2 uv, float2 period) +{ + float2 rescaledUv = uv * period; + float4 Pi = floor(rescaledUv.xyxy) + float4(0.0, 0.0, 1.0, 1.0); + float4 Pf = frac (rescaledUv.xyxy) - float4(0.0, 0.0, 1.0, 1.0); + Pi = SGE_Mod_F4(Pi, period.xyxy); // To create noise with explicit period + Pi = SGE_Mod289_F4(Pi); // To avoid truncation effects in permutation + float4 ix = Pi.xzxz; + float4 iy = Pi.yyww; + float4 fx = Pf.xzxz; + float4 fy = Pf.yyww; + + float4 i = SGE_Permute(SGE_Permute(ix) + iy); + + float4 gx = frac(i / 41.0) * 2.0 - 1.0 ; + float4 gy = abs(gx) - 0.5 ; + float4 tx = floor(gx + 0.5); + gx = gx - tx; + + float2 g00 = float2(gx.x,gy.x); + float2 g10 = float2(gx.y,gy.y); + float2 g01 = float2(gx.z,gy.z); + float2 g11 = float2(gx.w,gy.w); + + float4 norm = SGE_TaylorInvSqrt(float4(dot(g00, g00), dot(g01, g01), dot(g10, g10), dot(g11, g11))); + g00 *= norm.x; + g01 *= norm.y; + g10 *= norm.z; + g11 *= norm.w; + + float n00 = dot(g00, float2(fx.x, fy.x)); + float n10 = dot(g10, float2(fx.y, fy.y)); + float n01 = dot(g01, float2(fx.z, fy.z)); + float n11 = dot(g11, float2(fx.w, fy.w)); + + float2 fade_xy = SGE_Fade_F2(Pf.xy); + float2 n_x = lerp(float2(n00, n01), float2(n10, n11), fade_xy.x); + float n_xy = lerp(n_x.x, n_x.y, fade_xy.y); + return 2.3 * n_xy; +}")); + } + + // Copyright (c) 2011 Stefan Gustavson. All rights reserved. + // Distributed under the MIT license. See LICENSE file. + // https://github.com/stegu/webgl-noise + public static string Perlin3DNoiseFunctionName = "SGE_Perlin3DNoise"; + public static void Perlin3DNoiseFunction(FunctionRegistry registry) + { + PerlinNoiseHelperFunction(registry); + + registry.ProvideFunction(Perlin3DNoiseFunctionName, s => s.Append(@" +inline float " + Perlin3DNoiseFunctionName + @"(float3 uv) +{ + float3 Pi0 = floor(uv); // Integer part for indexing + float3 Pi1 = Pi0 + float3(1.0, 1.0, 1.0); // Integer part + 1 + Pi0 = SGE_Mod289_F3(Pi0); + Pi1 = SGE_Mod289_F3(Pi1); + float3 Pf0 = frac(uv); // Fractional part for interpolation + float3 Pf1 = Pf0 - float3(1.0, 1.0, 1.0); // Fractional part - 1.0 + float4 ix = float4(Pi0.x, Pi1.x, Pi0.x, Pi1.x); + float4 iy = float4(Pi0.yy, Pi1.yy); + float4 iz0 = Pi0.zzzz; + float4 iz1 = Pi1.zzzz; + + float4 ixy = SGE_Permute(SGE_Permute(ix) + iy); + float4 ixy0 = SGE_Permute(ixy + iz0); + float4 ixy1 = SGE_Permute(ixy + iz1); + + float4 gx0 = ixy0 * (1.0 / 7.0); + float4 gy0 = frac(floor(gx0) * (1.0 / 7.0)) - 0.5; + gx0 = frac(gx0); + float4 gz0 = float4(0.5, 0.5, 0.5, 0.5) - abs(gx0) - abs(gy0); + float4 sz0 = step(gz0, float4(0.0, 0.0, 0.0, 0.0)); + gx0 -= sz0 * (step(0.0, gx0) - 0.5); + gy0 -= sz0 * (step(0.0, gy0) - 0.5); + + float4 gx1 = ixy1 * (1.0 / 7.0); + float4 gy1 = frac(floor(gx1) * (1.0 / 7.0)) - 0.5; + gx1 = frac(gx1); + float4 gz1 = float4(0.5, 0.5, 0.5, 0.5) - abs(gx1) - abs(gy1); + float4 sz1 = step(gz1, float4(0.0, 0.0, 0.0, 0.0)); + gx1 -= sz1 * (step(0.0, gx1) - 0.5); + gy1 -= sz1 * (step(0.0, gy1) - 0.5); + + float3 g000 = float3(gx0.x,gy0.x,gz0.x); + float3 g100 = float3(gx0.y,gy0.y,gz0.y); + float3 g010 = float3(gx0.z,gy0.z,gz0.z); + float3 g110 = float3(gx0.w,gy0.w,gz0.w); + float3 g001 = float3(gx1.x,gy1.x,gz1.x); + float3 g101 = float3(gx1.y,gy1.y,gz1.y); + float3 g011 = float3(gx1.z,gy1.z,gz1.z); + float3 g111 = float3(gx1.w,gy1.w,gz1.w); + + float4 norm0 = SGE_TaylorInvSqrt(float4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110))); + g000 *= norm0.x; + g010 *= norm0.y; + g100 *= norm0.z; + g110 *= norm0.w; + float4 norm1 = SGE_TaylorInvSqrt(float4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111))); + g001 *= norm1.x; + g011 *= norm1.y; + g101 *= norm1.z; + g111 *= norm1.w; + + float n000 = dot(g000, Pf0); + float n100 = dot(g100, float3(Pf1.x, Pf0.yz)); + float n010 = dot(g010, float3(Pf0.x, Pf1.y, Pf0.z)); + float n110 = dot(g110, float3(Pf1.xy, Pf0.z)); + float n001 = dot(g001, float3(Pf0.xy, Pf1.z)); + float n101 = dot(g101, float3(Pf1.x, Pf0.y, Pf1.z)); + float n011 = dot(g011, float3(Pf0.x, Pf1.yz)); + float n111 = dot(g111, Pf1); + + float3 fade_xyz = SGE_Fade_F3(Pf0); + float4 n_z = lerp(float4(n000, n100, n010, n110), float4(n001, n101, n011, n111), fade_xyz.z); + float2 n_yz = lerp(n_z.xy, n_z.zw, fade_xyz.y); + float n_xyz = lerp(n_yz.x, n_yz.y, fade_xyz.x); + return 2.2 * n_xyz; +}")); + } + + public static string PeriodicPerlin3DNoiseFunctionName = "SGE_PeriodicPerlin3DNoise"; + public static void PeriodicPerlin3DNoiseFunction(FunctionRegistry registry) + { + PerlinNoiseHelperFunction(registry); + + registry.ProvideFunction(PeriodicPerlin3DNoiseFunctionName, s => s.Append(@" +inline float " + PeriodicPerlin3DNoiseFunctionName + @"(float3 uv, float3 period) +{ + float3 Pi0 = SGE_Mod_F3(floor(uv), period); // Integer part, modulo period + float3 Pi1 = SGE_Mod_F3(Pi0 + float3(1.0, 1.0, 1.0), period); // Integer part + 1, mod period + Pi0 = SGE_Mod289_F3(Pi0); + Pi1 = SGE_Mod289_F3(Pi1); + float3 Pf0 = frac(uv); // fracional part for interpolation + float3 Pf1 = Pf0 - float3(1.0, 1.0, 1.0); // fracional part - 1.0 + float4 ix = float4(Pi0.x, Pi1.x, Pi0.x, Pi1.x); + float4 iy = float4(Pi0.yy, Pi1.yy); + float4 iz0 = Pi0.zzzz; + float4 iz1 = Pi1.zzzz; + + float4 ixy = SGE_Permute(SGE_Permute(ix) + iy); + float4 ixy0 = SGE_Permute(ixy + iz0); + float4 ixy1 = SGE_Permute(ixy + iz1); + + float4 gx0 = ixy0 * (1.0 / 7.0); + float4 gy0 = frac(floor(gx0) * (1.0 / 7.0)) - 0.5; + gx0 = frac(gx0); + float4 gz0 = float4(0.5, 0.5, 0.5, 0.5) - abs(gx0) - abs(gy0); + float4 sz0 = step(gz0, float4(0.0, 0.0, 0.0, 0.0)); + gx0 -= sz0 * (step(0.0, gx0) - 0.5); + gy0 -= sz0 * (step(0.0, gy0) - 0.5); + + float4 gx1 = ixy1 * (1.0 / 7.0); + float4 gy1 = frac(floor(gx1) * (1.0 / 7.0)) - 0.5; + gx1 = frac(gx1); + float4 gz1 = float4(0.5, 0.5, 0.5, 0.5) - abs(gx1) - abs(gy1); + float4 sz1 = step(gz1, float4(0.0, 0.0, 0.0, 0.0)); + gx1 -= sz1 * (step(0.0, gx1) - 0.5); + gy1 -= sz1 * (step(0.0, gy1) - 0.5); + + float3 g000 = float3(gx0.x,gy0.x,gz0.x); + float3 g100 = float3(gx0.y,gy0.y,gz0.y); + float3 g010 = float3(gx0.z,gy0.z,gz0.z); + float3 g110 = float3(gx0.w,gy0.w,gz0.w); + float3 g001 = float3(gx1.x,gy1.x,gz1.x); + float3 g101 = float3(gx1.y,gy1.y,gz1.y); + float3 g011 = float3(gx1.z,gy1.z,gz1.z); + float3 g111 = float3(gx1.w,gy1.w,gz1.w); + + float4 norm0 = SGE_TaylorInvSqrt(float4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110))); + g000 *= norm0.x; + g010 *= norm0.y; + g100 *= norm0.z; + g110 *= norm0.w; + float4 norm1 = SGE_TaylorInvSqrt(float4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111))); + g001 *= norm1.x; + g011 *= norm1.y; + g101 *= norm1.z; + g111 *= norm1.w; + + float n000 = dot(g000, Pf0); + float n100 = dot(g100, float3(Pf1.x, Pf0.yz)); + float n010 = dot(g010, float3(Pf0.x, Pf1.y, Pf0.z)); + float n110 = dot(g110, float3(Pf1.xy, Pf0.z)); + float n001 = dot(g001, float3(Pf0.xy, Pf1.z)); + float n101 = dot(g101, float3(Pf1.x, Pf0.y, Pf1.z)); + float n011 = dot(g011, float3(Pf0.x, Pf1.yz)); + float n111 = dot(g111, Pf1); + + float3 fade_xyz = SGE_Fade_F3(Pf0); + float4 n_z = lerp(float4(n000, n100, n010, n110), float4(n001, n101, n011, n111), fade_xyz.z); + float2 n_yz = lerp(n_z.xy, n_z.zw, fade_xyz.y); + float n_xyz = lerp(n_yz.x, n_yz.y, fade_xyz.x); + return 2.2 * n_xyz; +}")); + } + + public static string GetFractalFunctionName(string noiseFunctionName) + { + return "SGE_Fractal" + noiseFunctionName; + } + + public static void FractalFunction(FunctionRegistry registry, string noiseFunctionName, string dimensionTypeName = "float2") + { + registry.ProvideFunction(GetFractalFunctionName(noiseFunctionName), s => s.Append(@" +inline float " + GetFractalFunctionName(noiseFunctionName) + @"(" + dimensionTypeName + @" uv, float persistence, float lacunarity) +{ + float currentPersistence = persistence; + " + dimensionTypeName + @" currentUV = uv; + float ret = 0.0; + for (uint i = 0; i < 4; i++) + { + ret += currentPersistence * " + noiseFunctionName + @"(currentUV); + currentPersistence *= persistence; + currentUV *= lacunarity; + } + + return ret; +}")); + } + + public static void PeriodicFractalFunction(FunctionRegistry registry, string noiseFunctionName, string dimensionTypeName = "float2") + { + registry.ProvideFunction(GetFractalFunctionName(noiseFunctionName), s => s.Append(@" +inline float " + GetFractalFunctionName(noiseFunctionName) + @"(" + dimensionTypeName + @" uv, int Period, float persistence, float lacunarity) +{ + float currentPersistence = persistence; + " + dimensionTypeName + @" currentUV = uv; + float ret = 0.0; + int p = pow(2, Period); + for (uint i = 0; i < 4; i++) + { + ret += currentPersistence * " + noiseFunctionName + @"(currentUV, p); + currentPersistence *= persistence; + currentUV *= lacunarity; + p *= 2; + } + + return ret; +}")); + } + + public static string GetTurbulenceFunctionName(string noiseFunctionName) + { + return "SGE_Turbulence" + noiseFunctionName; + } + + public static void TurbulenceFunction(FunctionRegistry registry, string noiseFunctionName, string dimensionTypeName = "float2") + { + registry.ProvideFunction(GetTurbulenceFunctionName(noiseFunctionName), s => s.Append(@" +inline float " + GetTurbulenceFunctionName(noiseFunctionName) + @"(" + dimensionTypeName + @" uv, float persistence, float lacunarity) +{ + float currentPersistence = persistence; + " + dimensionTypeName + @" currentUV = uv; + float ret = 0.0; + for (uint i = 0; i < 4; i++) + { + ret += currentPersistence * abs(" + noiseFunctionName + @"(currentUV)); + currentPersistence *= persistence; + currentUV *= lacunarity; + } + + return ret; +}")); + } + + public static void PeriodicTurbulenceFunction(FunctionRegistry registry, string noiseFunctionName, string dimensionTypeName = "float2") + { + registry.ProvideFunction(GetTurbulenceFunctionName(noiseFunctionName), s => s.Append(@" +inline float " + GetTurbulenceFunctionName(noiseFunctionName) + @"(" + dimensionTypeName + @" uv, int Period, float persistence, float lacunarity) +{ + float currentPersistence = persistence; + " + dimensionTypeName + @" currentUV = uv; + float ret = 0.0; + int p = pow(2, Period); + for (uint i = 0; i < 4; i++) + { + ret += currentPersistence * abs(" + noiseFunctionName + @"(currentUV, p)); + currentPersistence *= persistence; + currentUV *= lacunarity; + p *= 2; + } + + return ret; +}")); + } + + public static string GetRidgeFunctionName(string noiseFunctionName) + { + return "SGE_Ridge" + noiseFunctionName; + } + + public static void RidgeFunction(FunctionRegistry registry, string noiseFunctionName, string dimensionTypeName = "float2") + { + registry.ProvideFunction(GetRidgeFunctionName(noiseFunctionName), s => s.Append(@" +inline float " + GetRidgeFunctionName(noiseFunctionName) + @"(" + dimensionTypeName + @" uv, float persistence, float lacunarity, float sharpness) +{ + float currentPersistence = persistence; + " + dimensionTypeName + @" currentUV = uv; + float ret = 0.0; + for (uint i = 0; i < 4; i++) + { + // create creases + float n = saturate(abs(" + noiseFunctionName + @"(currentUV))); + // invert so creases are at top + n = 1.0 - n + 0.0001f; + // sharpen creases + n = pow(n, sharpness); + ret += currentPersistence * n; + currentPersistence *= persistence; + currentUV *= lacunarity; + } + + return ret; +}")); + } + + public static void PeriodicRidgeFunction(FunctionRegistry registry, string noiseFunctionName, string dimensionTypeName = "float2") + { + registry.ProvideFunction(GetRidgeFunctionName(noiseFunctionName), s => s.Append(@" +inline float " + GetRidgeFunctionName(noiseFunctionName) + @"(" + dimensionTypeName + @" uv, int Period, float persistence, float lacunarity, float sharpness) +{ + float currentPersistence = persistence; + " + dimensionTypeName + @" currentUV = uv; + float ret = 0.0; + int p = pow(2, Period); + for (uint i = 0; i < 4; i++) + { + // create creases + float n = saturate(abs(" + noiseFunctionName + @"(currentUV, p))); + // invert so creases are at top + n = 1.0 - n + 0.0001f; + // sharpen creases + n = pow(n, sharpness); + ret += currentPersistence * n; + currentPersistence *= persistence; + currentUV *= lacunarity; + p *= 2; + } + + return ret; +}")); + } + + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseShaderUtils.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseShaderUtils.cs.meta new file mode 100644 index 0000000..3edd345 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseShaderUtils.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 09d3fd444facb7a45b576c88924dfb1d +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseType.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseType.cs new file mode 100644 index 0000000..3f2643e --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseType.cs @@ -0,0 +1,26 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +namespace ShaderGraphEssentials +{ + public enum NoiseType + { + Value, + Simplex, + Perlin + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseType.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseType.cs.meta new file mode 100644 index 0000000..b70f3bd --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/NoiseType.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4cd8d6f4683cded4b9a027cb00372149 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/PerlinNoise.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/PerlinNoise.cs new file mode 100644 index 0000000..2ca5970 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/PerlinNoise.cs @@ -0,0 +1,129 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using UnityEditor.ShaderGraph; + +namespace ShaderGraphEssentials +{ + class PerlinNoise : NoiseBase + { + public PerlinNoise(NoiseCombine combine, NoiseDimension dimension, NoisePeriodicity periodicity) : base(combine, dimension, periodicity) + { + } + + public override bool Support() + { + return true; + } + + public override NoiseDimension[] GetSupportedDimensions() + { + return new[] { NoiseDimension.D2, NoiseDimension.D3 }; + } + + public override NoisePeriodicity[] GetSupportedPeriodicities() + { + return new[] { NoisePeriodicity.NonPeriodic, NoisePeriodicity.Periodic }; + } + + public override string GetNoiseFunctionName() + { + switch (Combine) + { + case NoiseCombine.Simple: + return GetSimpleNoiseFunctionName(); + case NoiseCombine.Fractal: + return ShaderUtils.GetFractalFunctionName(GetSimpleNoiseFunctionName()); + case NoiseCombine.Turbulence: + return ShaderUtils.GetTurbulenceFunctionName(GetSimpleNoiseFunctionName()); + case NoiseCombine.Ridge: + return ShaderUtils.GetRidgeFunctionName(GetSimpleNoiseFunctionName()); + default: + throw new ArgumentOutOfRangeException(); + } + } + + // function name of the noise, with the combine if any + private string GetSimpleNoiseFunctionName() + { + switch (Periodicity) + { + case NoisePeriodicity.NonPeriodic: + return Dimension == NoiseDimension.D2 ? ShaderUtils.PerlinNoiseFunctionName : ShaderUtils.Perlin3DNoiseFunctionName; + case NoisePeriodicity.Periodic: + return Dimension == NoiseDimension.D2 ? ShaderUtils.PeriodicPerlinNoiseFunctionName : ShaderUtils.PeriodicPerlin3DNoiseFunctionName; + default: + throw new ArgumentOutOfRangeException(); + } + } + + internal override void RegisterFunctions(FunctionRegistry registry) + { + switch (Periodicity) + { + case NoisePeriodicity.NonPeriodic: + switch (Dimension) + { + case NoiseDimension.D2: + ShaderUtils.PerlinNoiseFunction(registry); + break; + case NoiseDimension.D3: + ShaderUtils.Perlin3DNoiseFunction(registry); + break; + default: + throw new ArgumentOutOfRangeException(); + } + + if (Combine == NoiseCombine.Fractal) + ShaderUtils.FractalFunction(registry, GetSimpleNoiseFunctionName(), Dimension.ToShaderVectorEquivalent()); + else if (Combine == NoiseCombine.Turbulence) + ShaderUtils.TurbulenceFunction(registry, GetSimpleNoiseFunctionName(), Dimension.ToShaderVectorEquivalent()); + else if (Combine == NoiseCombine.Ridge) + ShaderUtils.RidgeFunction(registry, GetSimpleNoiseFunctionName(), Dimension.ToShaderVectorEquivalent()); + break; + case NoisePeriodicity.Periodic: + switch (Dimension) + { + case NoiseDimension.D2: + ShaderUtils.PeriodicPerlinNoiseFunction(registry); + break; + case NoiseDimension.D3: + ShaderUtils.PeriodicPerlin3DNoiseFunction(registry); + break; + default: + throw new ArgumentOutOfRangeException(); + } + + if (Combine == NoiseCombine.Fractal) + ShaderUtils.PeriodicFractalFunction(registry, GetSimpleNoiseFunctionName(), Dimension.ToShaderVectorEquivalent()); + else if (Combine == NoiseCombine.Turbulence) + ShaderUtils.PeriodicTurbulenceFunction(registry, GetSimpleNoiseFunctionName(), Dimension.ToShaderVectorEquivalent()); + else if (Combine == NoiseCombine.Ridge) + ShaderUtils.PeriodicRidgeFunction(registry, GetSimpleNoiseFunctionName(), Dimension.ToShaderVectorEquivalent()); + break; + default: + throw new ArgumentOutOfRangeException(); + } + } + + public override bool NeedRemapTo0_1() + { + return Combine != NoiseCombine.Turbulence && Combine != NoiseCombine.Ridge; + } + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/PerlinNoise.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/PerlinNoise.cs.meta new file mode 100644 index 0000000..ab5dff7 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/PerlinNoise.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 10a8ecb717008aa4c965b032befb38a0 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/SimplexNoise.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/SimplexNoise.cs new file mode 100644 index 0000000..83bc72a --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/SimplexNoise.cs @@ -0,0 +1,85 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using UnityEditor.ShaderGraph; + +namespace ShaderGraphEssentials +{ + class SimplexNoise : NoiseBase + { + public SimplexNoise(NoiseCombine combine, NoiseDimension dimension, NoisePeriodicity periodicity) : base(combine, dimension, periodicity) + { + } + + public override bool Support() + { + return Dimension == NoiseDimension.D2 && Periodicity == NoisePeriodicity.NonPeriodic; + } + + public override NoiseDimension[] GetSupportedDimensions() + { + return new[] { NoiseDimension.D2 }; + } + + public override NoisePeriodicity[] GetSupportedPeriodicities() + { + return new[] {NoisePeriodicity.NonPeriodic}; + } + + public override string GetNoiseFunctionName() + { + switch (Combine) + { + case NoiseCombine.Simple: + return GetSimpleNoiseFunctionName(); + case NoiseCombine.Fractal: + return ShaderUtils.GetFractalFunctionName(GetSimpleNoiseFunctionName()); + case NoiseCombine.Turbulence: + return ShaderUtils.GetTurbulenceFunctionName(GetSimpleNoiseFunctionName()); + case NoiseCombine.Ridge: + return ShaderUtils.GetRidgeFunctionName(GetSimpleNoiseFunctionName()); + default: + throw new ArgumentOutOfRangeException(); + } + } + + // function name of the noise, with the combine if any + private string GetSimpleNoiseFunctionName() + { + return ShaderUtils.SimplexNoiseFunctionName; + } + + internal override void RegisterFunctions(FunctionRegistry registry) + { + ShaderUtils.RandomValue2dTo2dFunction(registry); + ShaderUtils.SimplexNoiseFunction(registry); + + if (Combine == NoiseCombine.Fractal) + ShaderUtils.FractalFunction(registry, GetSimpleNoiseFunctionName()); + else if (Combine == NoiseCombine.Turbulence) + ShaderUtils.TurbulenceFunction(registry, GetSimpleNoiseFunctionName()); + else if (Combine == NoiseCombine.Ridge) + ShaderUtils.RidgeFunction(registry, GetSimpleNoiseFunctionName()); + } + + public override bool NeedRemapTo0_1() + { + return Combine != NoiseCombine.Turbulence && Combine != NoiseCombine.Ridge; + } + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/SimplexNoise.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/SimplexNoise.cs.meta new file mode 100644 index 0000000..b157faa --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/SimplexNoise.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ae75eec60c9735740a8df0661e9b8398 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/ValueNoise.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/ValueNoise.cs new file mode 100644 index 0000000..8f48958 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/ValueNoise.cs @@ -0,0 +1,101 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using UnityEditor.ShaderGraph; + +namespace ShaderGraphEssentials +{ + class ValueNoise : NoiseBase + { + public ValueNoise(NoiseCombine combine, NoiseDimension dimension, NoisePeriodicity periodicity) : base(combine, dimension, periodicity) + { + } + + public override bool Support() + { + return Dimension == NoiseDimension.D2; + } + + public override NoiseDimension[] GetSupportedDimensions() + { + return new[] {NoiseDimension.D2}; + } + + public override NoisePeriodicity[] GetSupportedPeriodicities() + { + return new[] { NoisePeriodicity.NonPeriodic, NoisePeriodicity.Periodic }; + } + + public override string GetNoiseFunctionName() + { + switch (Combine) + { + case NoiseCombine.Simple: + return GetSimpleNoiseFunctionName(); + case NoiseCombine.Fractal: + return ShaderUtils.GetFractalFunctionName(GetSimpleNoiseFunctionName()); + case NoiseCombine.Turbulence: + return ShaderUtils.GetTurbulenceFunctionName(GetSimpleNoiseFunctionName()); + case NoiseCombine.Ridge: + return ShaderUtils.GetRidgeFunctionName(GetSimpleNoiseFunctionName()); + default: + throw new ArgumentOutOfRangeException(); + } + } + + // function name of the noise, with the combine if any + private string GetSimpleNoiseFunctionName() + { + return Periodicity == NoisePeriodicity.NonPeriodic ? ShaderUtils.ValueNoiseFunctionName : ShaderUtils.PeriodicValueNoiseFunctionName; + } + + internal override void RegisterFunctions(FunctionRegistry registry) + { + ShaderUtils.RandomValue2dTo1dFunction(registry); + + switch (Periodicity) + { + case NoisePeriodicity.NonPeriodic: + ShaderUtils.ValueNoiseFunction(registry); + if (Combine == NoiseCombine.Fractal) + ShaderUtils.FractalFunction(registry, GetSimpleNoiseFunctionName()); + else if (Combine == NoiseCombine.Turbulence) + ShaderUtils.TurbulenceFunction(registry, GetSimpleNoiseFunctionName()); + else if (Combine == NoiseCombine.Ridge) + ShaderUtils.RidgeFunction(registry, GetSimpleNoiseFunctionName()); + break; + case NoisePeriodicity.Periodic: + ShaderUtils.PeriodicValueNoiseFunction(registry); + if (Combine == NoiseCombine.Fractal) + ShaderUtils.PeriodicFractalFunction(registry, GetSimpleNoiseFunctionName()); + else if (Combine == NoiseCombine.Turbulence) + ShaderUtils.PeriodicTurbulenceFunction(registry, GetSimpleNoiseFunctionName()); + else if (Combine == NoiseCombine.Ridge) + ShaderUtils.PeriodicRidgeFunction(registry, GetSimpleNoiseFunctionName()); + break; + default: + throw new ArgumentOutOfRangeException(); + } + } + + public override bool NeedRemapTo0_1() + { + return Combine != NoiseCombine.Turbulence && Combine != NoiseCombine.Ridge; + } + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/ValueNoise.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/ValueNoise.cs.meta new file mode 100644 index 0000000..33cfc7c --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_Base/Scripts/Noises/ValueNoise.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 26ddce98423a567458e119ab7d919160 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP.meta new file mode 100644 index 0000000..4721276 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: f6a355c2bd4f8924bac91d0e229365dd +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes.meta new file mode 100644 index 0000000..561a514 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d281b2ab1eaf7a645b6dcab48b0aeebe +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/CustomLit.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/CustomLit.meta new file mode 100644 index 0000000..b1db6b6 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/CustomLit.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 65879b152d0758649b06703d79e60cdb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/CustomLit/SGECustomLitMasterNode.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/CustomLit/SGECustomLitMasterNode.cs new file mode 100644 index 0000000..1421661 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/CustomLit/SGECustomLitMasterNode.cs @@ -0,0 +1,36 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Legacy; +using RenderQueue = UnityEditor.ShaderGraph.RenderQueue; + +namespace ShaderGraphEssentials.Legacy +{ + [FormerName("ShaderGraphEssentials.SGECustomLitMasterNode")] + class SGECustomLitMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public RenderType m_renderType; + public RenderQueue m_renderQueue; + public BlendMode m_blendMode; + public CullMode m_cullMode; + public ZWrite m_zwrite; + public ZTest m_ztest; + public NormalDropOffSpace m_NormalDropOffSpace; + public string m_customEditor; + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/CustomLit/SGECustomLitMasterNode.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/CustomLit/SGECustomLitMasterNode.cs.meta new file mode 100644 index 0000000..84d1509 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/CustomLit/SGECustomLitMasterNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: be3830ad503e7ab4cbb800382c00ea98 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/SimpleLit.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/SimpleLit.meta new file mode 100644 index 0000000..5a3f4dd --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/SimpleLit.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7ed365abd470c62479184d2f8e2c3879 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/SimpleLit/SGESimpleLitMasterNode.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/SimpleLit/SGESimpleLitMasterNode.cs new file mode 100644 index 0000000..5b2b986 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/SimpleLit/SGESimpleLitMasterNode.cs @@ -0,0 +1,36 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Legacy; +using RenderQueue = UnityEditor.ShaderGraph.RenderQueue; + +namespace ShaderGraphEssentials.Legacy +{ + [FormerName("ShaderGraphEssentials.SGESimpleLitMasterNode")] + class SGESimpleLitMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public RenderType m_renderType; + public RenderQueue m_renderQueue; + public BlendMode m_blendMode; + public CullMode m_cullMode; + public ZWrite m_zwrite; + public ZTest m_ztest; + public NormalDropOffSpace m_NormalDropOffSpace; + public string m_customEditor; + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/SimpleLit/SGESimpleLitMasterNode.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/SimpleLit/SGESimpleLitMasterNode.cs.meta new file mode 100644 index 0000000..88385fd --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/SimpleLit/SGESimpleLitMasterNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8b07f9a0feadeb144b67bc728b12c3a2 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/Unlit.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/Unlit.meta new file mode 100644 index 0000000..19b6df9 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/Unlit.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: bee0e3d65a4bc434db601704c490e8fb +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/Unlit/SGEUnlitMasterNode.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/Unlit/SGEUnlitMasterNode.cs new file mode 100644 index 0000000..7aaecaa --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/Unlit/SGEUnlitMasterNode.cs @@ -0,0 +1,53 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Legacy; +using RenderQueue = UnityEditor.ShaderGraph.RenderQueue; + +namespace ShaderGraphEssentials.Legacy +{ + public enum BlendMode + { + Off = 0, + Alpha = 1, + Premultiply = 2, + Additive = 3, + Multiply = 4 + } + public enum CullMode + { + Back, + Front, + Off + } + + + [FormerName("ShaderGraphEssentials.SGEUnlitMasterNode")] + class SGEUnlitMasterNode1 : AbstractMaterialNode, IMasterNode1 + { + public RenderType m_renderType; + public RenderQueue m_renderQueue; + public BlendMode m_blendMode; + public CullMode m_cullMode; + public ZWrite m_zwrite; + public ZTest m_ztest; + public string m_customEditor; + + + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/Unlit/SGEUnlitMasterNode.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/Unlit/SGEUnlitMasterNode.cs.meta new file mode 100644 index 0000000..36e61a8 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Master_Nodes/Unlit/SGEUnlitMasterNode.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: da3d3f2a8d7d85e449a9c0012d1a5fed +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders.meta new file mode 100644 index 0000000..8b25f6c --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: d04914cc1d29a5b4c81c638af78bc0e4 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitForwardPass.hlsl b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitForwardPass.hlsl new file mode 100644 index 0000000..5f970bb --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitForwardPass.hlsl @@ -0,0 +1,194 @@ +void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData) +{ + inputData = (InputData)0; + + inputData.positionWS = input.positionWS; + + #ifdef _NORMALMAP + // IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped. + float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale(); + float3 bitangent = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz); + + inputData.tangentToWorld = half3x3(input.tangentWS.xyz, bitangent.xyz, input.normalWS.xyz); + + #if _NORMAL_DROPOFF_TS + inputData.normalWS = TransformTangentToWorld(surfaceDescription.NormalTS, inputData.tangentToWorld); + #elif _NORMAL_DROPOFF_OS + inputData.normalWS = TransformObjectToWorldNormal(surfaceDescription.NormalOS); + #elif _NORMAL_DROPOFF_WS + inputData.normalWS = surfaceDescription.NormalWS; + #endif + #else + inputData.normalWS = input.normalWS; + #endif + inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS); + inputData.viewDirectionWS = GetWorldSpaceNormalizeViewDir(input.positionWS); + + #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR) + inputData.shadowCoord = input.shadowCoord; + #elif defined(MAIN_LIGHT_CALCULATE_SHADOWS) + inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS); + #else + inputData.shadowCoord = float4(0, 0, 0, 0); + #endif + + inputData.fogCoord = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactorAndVertexLight.x); + inputData.vertexLighting = input.fogFactorAndVertexLight.yzw; +#if defined(DYNAMICLIGHTMAP_ON) + inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.dynamicLightmapUV.xy, input.sh, inputData.normalWS); +#elif !defined(LIGHTMAP_ON) && (defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2)) + inputData.bakedGI = SAMPLE_GI(input.sh, + GetAbsolutePositionWS(inputData.positionWS), + inputData.normalWS, + inputData.viewDirectionWS, + input.positionCS.xy); +#else + inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.sh, inputData.normalWS); +#endif + inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS); + inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV); + + #if defined(DEBUG_DISPLAY) + #if defined(DYNAMICLIGHTMAP_ON) + inputData.dynamicLightmapUV = input.dynamicLightmapUV.xy; + #endif + #if defined(LIGHTMAP_ON) + inputData.staticLightmapUV = input.staticLightmapUV; + #else + inputData.vertexSH = input.sh; + #endif + #endif +} + +PackedVaryings vert(Attributes input) +{ + Varyings output = (Varyings)0; + output = BuildVaryings(input); + PackedVaryings packedOutput = (PackedVaryings)0; + packedOutput = PackVaryings(output); + return packedOutput; +} + +half4 SGE_UniversalFragmentCustom(InputData inputData, SGECustomLightingData data) +{ + #if defined(DEBUG_DISPLAY) + half4 debugColor; + + if (CanDebugOverrideOutputColor(inputData, surfaceData, debugColor)) + { + return debugColor; + } + #endif + + uint meshRenderingLayers = GetMeshRenderingLayer(); + half4 shadowMask = CalculateShadowMask(inputData); + AmbientOcclusionFactor aoFactor = GetScreenSpaceAmbientOcclusion(inputData.normalizedScreenSpaceUV); + Light mainLight = GetMainLight(inputData, shadowMask, aoFactor); + + MixRealtimeAndBakedGI(mainLight, inputData.normalWS, inputData.bakedGI, aoFactor); + + half3 diffuseColor = inputData.bakedGI; + half3 specularColor = half3(0, 0, 0); + +#ifdef _LIGHT_LAYERS + if (IsMatchingLightLayer(mainLight.layerMask, meshRenderingLayers)) +#endif + { + diffuseColor = inputData.bakedGI + SGE_DiffuseLightingCustom(mainLight, data); + specularColor = SGE_SpecularLightingCustom(mainLight, inputData.viewDirectionWS, data); + } + +#ifdef _ADDITIONAL_LIGHTS + uint pixelLightCount = GetAdditionalLightsCount(); + LIGHT_LOOP_BEGIN(pixelLightCount) + Light light = GetAdditionalLight(lightIndex, inputData, shadowMask, aoFactor); + if (IsMatchingLightLayer(light.layerMask, meshRenderingLayers)) + { + diffuseColor += SGE_DiffuseLightingCustom(light, data); + specularColor += SGE_SpecularLightingCustom(light, inputData.viewDirectionWS, data); + } + LIGHT_LOOP_END +#endif + +#ifdef _ADDITIONAL_LIGHTS_VERTEX + diffuseColor += inputData.vertexLighting; +#endif + + half3 finalColor = diffuseColor * data.albedo + data.emission; + +#if defined(_SPECGLOSSMAP) || defined(_SPECULAR_COLOR) + finalColor += specularColor; +#endif + + return half4(finalColor, data.alpha); +} + +void frag( + PackedVaryings packedInput + , out half4 outColor : SV_Target0 +#ifdef _WRITE_RENDERING_LAYERS + , out float4 outRenderingLayers : SV_Target1 +#endif +) +{ + Varyings unpacked = UnpackVaryings(packedInput); + UNITY_SETUP_INSTANCE_ID(unpacked); + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked); + + SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked); + +#if defined(_SURFACE_TYPE_TRANSPARENT) + bool isTransparent = true; +#else + bool isTransparent = false; +#endif + +#if defined(_ALPHATEST_ON) + half alpha = AlphaDiscard(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold); +#elif defined(_SURFACE_TYPE_TRANSPARENT) + half alpha = surfaceDescription.Alpha; +#else + half alpha = half(1.0); +#endif + + #if defined(LOD_FADE_CROSSFADE) && USE_UNITY_CROSSFADE + LODFadeCrossFade(unpacked.positionCS); + #endif + + InputData inputData; + InitializeInputData(unpacked, surfaceDescription, inputData); + // TODO: Mip debug modes would require this, open question how to do this on ShaderGraph. + //SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.texCoord1.xy, _MainTex); + + half3 normalTS = half3(0, 0, 0); + #if defined(_NORMALMAP) && defined(_NORMAL_DROPOFF_TS) + normalTS = surfaceDescription.NormalTS; + #endif + + + // SGECustomLightingData remap + SGECustomLightingData data; + data.albedo = surfaceDescription.BaseColor; + data.normal = inputData.normalWS; + data.specular = surfaceDescription.Specular; + data.glossiness = surfaceDescription.Glossiness; + data.smoothness = surfaceDescription.Shininess * 128.0; + data.emission = surfaceDescription.Emission; + data.alpha = alpha; + data.customLightingData1 = surfaceDescription.CustomLightingData1; + data.customLightingData2 = surfaceDescription.CustomLightingData2; + + // custom lit style + half4 color = SGE_UniversalFragmentCustom(inputData, data); + + color.rgb = MixFog(color.rgb, inputData.fogCoord); + + color.a = OutputAlpha(color.a, isTransparent); + + outColor = color; + +#ifdef _WRITE_RENDERING_LAYERS + uint renderingLayers = GetMeshRenderingLayer(); + outRenderingLayers = float4(EncodeMeshRenderingLayer(renderingLayers), 0, 0, 0); +#endif +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitForwardPass.hlsl.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitForwardPass.hlsl.meta new file mode 100644 index 0000000..90ac317 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitForwardPass.hlsl.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 02c6e7a62fa4a1043bfbdfea0d508a7c +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitGBufferPass.hlsl b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitGBufferPass.hlsl new file mode 100644 index 0000000..e8a453b --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitGBufferPass.hlsl @@ -0,0 +1,138 @@ + +void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData) +{ + inputData = (InputData)0; + + inputData.positionWS = input.positionWS; + inputData.positionCS = input.positionCS; + + #ifdef _NORMALMAP + // IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped. + float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale(); + float3 bitangent = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz); + + inputData.tangentToWorld = half3x3(input.tangentWS.xyz, bitangent.xyz, input.normalWS.xyz); + #if _NORMAL_DROPOFF_TS + inputData.normalWS = TransformTangentToWorld(surfaceDescription.NormalTS, inputData.tangentToWorld); + #elif _NORMAL_DROPOFF_OS + inputData.normalWS = TransformObjectToWorldNormal(surfaceDescription.NormalOS); + #elif _NORMAL_DROPOFF_WS + inputData.normalWS = surfaceDescription.NormalWS; + #endif + #else + inputData.normalWS = input.normalWS; + #endif + inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS); + inputData.viewDirectionWS = GetWorldSpaceNormalizeViewDir(input.positionWS); + +#if defined(MAIN_LIGHT_CALCULATE_SHADOWS) + inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS); +#else + inputData.shadowCoord = float4(0, 0, 0, 0); +#endif + + inputData.fogCoord = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactorAndVertexLight.x); + inputData.vertexLighting = input.fogFactorAndVertexLight.yzw; +#if defined(DYNAMICLIGHTMAP_ON) + inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.dynamicLightmapUV.xy, input.sh, inputData.normalWS); +#elif !defined(LIGHTMAP_ON) && (defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2)) + inputData.bakedGI = SAMPLE_GI(input.sh, + GetAbsolutePositionWS(inputData.positionWS), + inputData.normalWS, + inputData.viewDirectionWS, + inputData.positionCS.xy); +#else + inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.sh, inputData.normalWS); +#endif + inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS); + inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV); + + #if defined(DEBUG_DISPLAY) + #if defined(DYNAMICLIGHTMAP_ON) + inputData.dynamicLightmapUV = input.dynamicLightmapUV.xy; + #endif + #if defined(LIGHTMAP_ON) + inputData.staticLightmapUV = input.staticLightmapUV; + #else + inputData.vertexSH = input.sh; + #endif + #endif +} + +PackedVaryings vert(Attributes input) +{ + Varyings output = (Varyings)0; + output = BuildVaryings(input); + PackedVaryings packedOutput = (PackedVaryings)0; + packedOutput = PackVaryings(output); + return packedOutput; +} + + +void PatchSimpleLitSurfaceData(SurfaceDescription surfaceDescription, out SurfaceData outSurfaceData) +{ + outSurfaceData = (SurfaceData)0; + + #if _ALPHATEST_ON + half alpha = surfaceDescription.Alpha; + clip(alpha - surfaceDescription.AlphaClipThreshold); + #elif _SURFACE_TYPE_TRANSPARENT + half alpha = surfaceDescription.Alpha; + #else + half alpha = 1; + #endif + + outSurfaceData.alpha = alpha; + + outSurfaceData.albedo = surfaceDescription.BaseColor.rgb; +#ifdef _ALPHAPREMULTIPLY_ON + outSurfaceData.albedo *= outSurfaceData.alpha; +#endif + + half4 specularSmoothness = half4(surfaceDescription.Specular, surfaceDescription.Shininess * 128.0); + outSurfaceData.metallic = 0.0; // unused + outSurfaceData.specular = specularSmoothness.rgb; + outSurfaceData.smoothness = specularSmoothness.a; + outSurfaceData.normalTS = surfaceDescription.NormalTS; + outSurfaceData.occlusion = 1.0; + outSurfaceData.emission = surfaceDescription.Emission; +} + +FragmentOutput frag(PackedVaryings packedInput) +{ + Varyings unpacked = UnpackVaryings(packedInput); + UNITY_SETUP_INSTANCE_ID(unpacked); + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked); + + SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked); + + SurfaceData surfaceData; + PatchSimpleLitSurfaceData(surfaceDescription, surfaceData); + + #if defined(LOD_FADE_CROSSFADE) && USE_UNITY_CROSSFADE + LODFadeCrossFade(unpacked.positionCS); + #endif + + InputData inputData; + InitializeInputData(unpacked, surfaceDescription, inputData); + // TODO: Mip debug modes would require this, open question how to do this on ShaderGraph. + //SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.uv, _MainTex); + + float3 specular = surfaceDescription.Specular; + +#ifdef _DBUFFER + ApplyDecal(unpacked.positionCS, + surfaceDescription.BaseColor, + specular, + inputData.normalWS, + 1, + surfaceDescription.Occlusion, + surfaceDescription.Smoothness); +#endif + + Light mainLight = GetMainLight(inputData.shadowCoord, inputData.positionWS, inputData.shadowMask); + MixRealtimeAndBakedGI(mainLight, inputData.normalWS, inputData.bakedGI, inputData.shadowMask); + half4 color = half4(inputData.bakedGI * surfaceData.albedo + surfaceData.emission, surfaceData.alpha); + + return SurfaceDataToGbuffer(surfaceData, inputData, color.rgb, kLightingSimpleLit); +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitGBufferPass.hlsl.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitGBufferPass.hlsl.meta new file mode 100644 index 0000000..6463d67 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitGBufferPass.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 512d43598c2b0804188d603a2937acbb +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternal.hlsl b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternal.hlsl new file mode 100644 index 0000000..e5b67ae --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternal.hlsl @@ -0,0 +1,33 @@ +#ifndef UNIVERSAL_LIGHTING_INCLUDED +#define UNIVERSAL_LIGHTING_INCLUDED +// necessary otherwise it'll throw en error on the node itself in the graph +// because the node HAS to compile by itself +// so without this, the master node is fine but this node itself won't compile because it doesn't know what "Light" is +struct Light +{ + half3 direction; + half3 color; + half distanceAttenuation; + half shadowAttenuation; + uint layerMask; +}; +// struct copied from "Packages/com.unity.render-pipelines.lightweight/ShaderLibrary/Lighting.hlsl" +#endif + +#ifndef SGE_CUSTOM_LIGHTING_INTERNAL_INCLUDED +#define SGE_CUSTOM_LIGHTING_INTERNAL_INCLUDED + +struct SGECustomLightingData +{ + float3 albedo; + float3 normal; + float3 specular; + float glossiness; + float smoothness; // converted from shininess + float3 emission; + float alpha; + float4 customLightingData1; // custom data you can use how you want (pass texture UV, vertex color ...etc) + float4 customLightingData2; +}; + +#endif \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternal.hlsl.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternal.hlsl.meta new file mode 100644 index 0000000..885597d --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternal.hlsl.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 88bc0d7c5620cfd42b495c5b08e2a4c3 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternalFull.hlsl b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternalFull.hlsl new file mode 100644 index 0000000..40b18a3 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternalFull.hlsl @@ -0,0 +1,33 @@ +#ifndef UNIVERSAL_LIGHTING_INCLUDED +#define UNIVERSAL_LIGHTING_INCLUDED +// necessary otherwise it'll throw en error on the node itself in the graph +// because the node HAS to compile by itself +// so without this, the master node is fine but this node itself won't compile because it doesn't know what "Light" is +struct Light +{ + half3 direction; + half3 color; + half distanceAttenuation; + half shadowAttenuation; + uint layerMask; +}; +// struct copied from "Packages/com.unity.render-pipelines.lightweight/ShaderLibrary/Lighting.hlsl" +#endif + +// the only difference with this file and SGE_CustomLightingDataInternal.hlsl +// is that this one doens't #ifdef out the struct below. +// This file is included automatically in the graph using CustomLit +// whereas the SGE_CustomLightingDataInternal.hlsl is only there to get the user-defined custom function to compile. +#define SGE_CUSTOM_LIGHTING_INTERNAL_INCLUDED +struct SGECustomLightingData +{ + float3 albedo; + float3 normal; + float3 specular; + float glossiness; + float smoothness; // converted from shininess + float3 emission; + float alpha; + float4 customLightingData1; // custom data you can use how you want (pass texture UV, vertex color ...etc) + float4 customLightingData2; +}; diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternalFull.hlsl.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternalFull.hlsl.meta new file mode 100644 index 0000000..f25da98 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternalFull.hlsl.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 63cbeb35240376b4b8f71e4ccfc027a4 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLighting.hlsl b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLighting.hlsl new file mode 100644 index 0000000..3ba85e3 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLighting.hlsl @@ -0,0 +1,63 @@ +#include "Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternal.hlsl" + +/* + * This is what you can access in the custom functions +struct Light +{ + half3 direction; + half3 color; + half distanceAttenuation; + half shadowAttenuation; + uint layerMask; +}; + +struct SGECustomLightingData +{ + float3 albedo; + float3 normal; // world space + float3 specular; + float glossiness; + float smoothness; // automatically converted from shininess + float3 emission; + float alpha; + float4 customLightingData1; // custom data you can use how you want (pass texture UV, properties / uniforms, vertex color ...etc) + float4 customLightingData2; +}; +*/ + +/* + * NOTES: + * Both of SGE_DiffuseLightingCustom and SGE_SpecularLightingCustom functions are called for each pixel light + * The name is hardcoded and very important, don't change it ! + * Also, you can't access Uniforms / Properties directly in there, + nor pass it to the custom function node + trying either of this will throw an error + but you can pass it through data.customLightingData1 and use it how you see fit. + (there's an example of this in SGE_ToonLighting.hlsl) +*/ + +// this will function is called for every light +half3 SGE_DiffuseLightingCustom(Light light, SGECustomLightingData data) +{ + float NdotL = saturate(dot(data.normal, light.direction)); + return light.color * NdotL * light.distanceAttenuation * light.shadowAttenuation; +} + +// this will function is called for every light +half3 SGE_SpecularLightingCustom(Light light, half3 viewDir, SGECustomLightingData data) +{ + float3 halfVec = SafeNormalize(light.direction + viewDir); + float NdotH = saturate(dot(data.normal, halfVec)); + float modifier = pow(NdotH, data.smoothness); + half3 specularReflection = data.specular * modifier; + return light.color * specularReflection * light.distanceAttenuation * light.shadowAttenuation; +} + +// necessary function because at the moment a custom function node NEEDS to output a result in the graph +// otherwise it can be optimized out +// here we don't do anything, so it doesn't matter where you plug this node, +// because the custom lighting function will be called by the master node +void Passthrough_float(float4 In, out float4 Out) +{ + Out = In; +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLighting.hlsl.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLighting.hlsl.meta new file mode 100644 index 0000000..c4455ff --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLighting.hlsl.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: ff58d7bda841877438d1453d66f77790 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLightingGraph.shadergraph b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLightingGraph.shadergraph new file mode 100644 index 0000000..b03e6c5 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLightingGraph.shadergraph @@ -0,0 +1,965 @@ +{ + "m_SGVersion": 2, + "m_Type": "UnityEditor.ShaderGraph.GraphData", + "m_ObjectId": "ed63c6b375e749ffa7267e5d1c22d817", + "m_Properties": [], + "m_Keywords": [], + "m_Nodes": [ + { + "m_Id": "7efba297d0b74c8093d51218c6f395ff" + }, + { + "m_Id": "a1d3bed2f71e4821a066eb16fb345c3f" + }, + { + "m_Id": "cf9f37c16f3c4b809a112290771e909b" + }, + { + "m_Id": "fadf2392448a4c6d9ba3d4f0c3686b9c" + }, + { + "m_Id": "56729bfb24fb4e2ca951b1ddeb07c3f2" + }, + { + "m_Id": "99b4dba4390b4069b70670fafb064690" + }, + { + "m_Id": "acee2fabfe6146e9a2d3fdc348ff3c56" + }, + { + "m_Id": "91cc7052d79a4ab2be1ade76e4a5dce1" + }, + { + "m_Id": "f15775cdc4104f7aa5f3557417344d44" + }, + { + "m_Id": "334cac89a1a1416d906a58e7e7e3edc7" + }, + { + "m_Id": "dd567d54bd034347a473820fc6d86736" + }, + { + "m_Id": "eb4eb88d62ad4999be29d2e49ae8c0f8" + }, + { + "m_Id": "96bb2fb4f91942bb9606c4f2d40cb78a" + } + ], + "m_GroupDatas": [], + "m_StickyNoteDatas": [ + { + "m_Id": "198c71c014be406aaf84152cf667c598" + } + ], + "m_Edges": [ + { + "m_OutputSlot": { + "m_Node": { + "m_Id": "96bb2fb4f91942bb9606c4f2d40cb78a" + }, + "m_SlotId": 0 + }, + "m_InputSlot": { + "m_Node": { + "m_Id": "eb4eb88d62ad4999be29d2e49ae8c0f8" + }, + "m_SlotId": 0 + } + }, + { + "m_OutputSlot": { + "m_Node": { + "m_Id": "eb4eb88d62ad4999be29d2e49ae8c0f8" + }, + "m_SlotId": 1 + }, + "m_InputSlot": { + "m_Node": { + "m_Id": "fadf2392448a4c6d9ba3d4f0c3686b9c" + }, + "m_SlotId": 0 + } + } + ], + "m_VertexContext": { + "m_Position": { + "x": 0.0, + "y": 0.0 + }, + "m_Blocks": [ + { + "m_Id": "7efba297d0b74c8093d51218c6f395ff" + }, + { + "m_Id": "a1d3bed2f71e4821a066eb16fb345c3f" + }, + { + "m_Id": "cf9f37c16f3c4b809a112290771e909b" + } + ] + }, + "m_FragmentContext": { + "m_Position": { + "x": 0.0, + "y": 200.0 + }, + "m_Blocks": [ + { + "m_Id": "fadf2392448a4c6d9ba3d4f0c3686b9c" + }, + { + "m_Id": "56729bfb24fb4e2ca951b1ddeb07c3f2" + }, + { + "m_Id": "99b4dba4390b4069b70670fafb064690" + }, + { + "m_Id": "acee2fabfe6146e9a2d3fdc348ff3c56" + }, + { + "m_Id": "91cc7052d79a4ab2be1ade76e4a5dce1" + }, + { + "m_Id": "f15775cdc4104f7aa5f3557417344d44" + }, + { + "m_Id": "334cac89a1a1416d906a58e7e7e3edc7" + }, + { + "m_Id": "dd567d54bd034347a473820fc6d86736" + } + ] + }, + "m_PreviewData": { + "serializedMesh": { + "m_SerializedMesh": "{\"mesh\":{\"instanceID\":0}}", + "m_Guid": "" + } + }, + "m_Path": "Shader Graphs", + "m_ConcretePrecision": 0, + "m_OutputNode": { + "m_Id": "" + }, + "m_ActiveTargets": [ + { + "m_Id": "41bfb34880a24490aa9f630f92947111" + } + ] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.StickyNoteData", + "m_ObjectId": "198c71c014be406aaf84152cf667c598", + "m_Title": "Custom Lighting", + "m_Content": "Input your own color in the custom function node.", + "m_TextSize": 0, + "m_Theme": 0, + "m_Position": { + "serializedVersion": "2", + "x": -606.0, + "y": 85.0, + "width": 200.0, + "height": 100.0 + }, + "m_Group": { + "m_Id": "" + } +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.NormalMaterialSlot", + "m_ObjectId": "32073861999f411d875ed672cf22d495", + "m_Id": 0, + "m_DisplayName": "Normal", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "Normal", + "m_StageCapability": 1, + "m_Value": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_Labels": [], + "m_Space": 0 +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "334cac89a1a1416d906a58e7e7e3edc7", + "m_Group": { + "m_Id": "" + }, + "m_Name": "SurfaceDescription.CustomLightingData1", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": 0.0, + "y": 0.0, + "width": 0.0, + "height": 0.0 + } + }, + "m_Slots": [ + { + "m_Id": "44d74a125bc04035ababff9dfef7aa9b" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "SurfaceDescription.CustomLightingData1" +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.ColorRGBMaterialSlot", + "m_ObjectId": "37e6fe3777ab46b39febcb17b4cf8cee", + "m_Id": 0, + "m_DisplayName": "Base Color", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "BaseColor", + "m_StageCapability": 2, + "m_Value": { + "x": 0.5, + "y": 0.5, + "z": 0.5 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_Labels": [], + "m_ColorMode": 0, + "m_DefaultColor": { + "r": 0.5, + "g": 0.5, + "b": 0.5, + "a": 1.0 + } +} + +{ + "m_SGVersion": 0, + "m_Type": "ShaderGraphEssentials.SGEUniversalTarget", + "m_ObjectId": "41bfb34880a24490aa9f630f92947111", + "m_ActiveSubTarget": { + "m_Id": "f4544c958fd04f12890669c1c6416df8" + }, + "m_RenderType": 0, + "m_RenderQueue": 1, + "m_BlendMode": 0, + "m_AlphaClip": false, + "m_CullMode": 2, + "m_ZWrite": 0, + "m_ZTest": 0, + "m_CustomEditorGUI": "" +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Vector4MaterialSlot", + "m_ObjectId": "41d4ebdb0347493295537c91fadca239", + "m_Id": 0, + "m_DisplayName": "In", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "In", + "m_StageCapability": 3, + "m_Value": { + "x": 0.0, + "y": 0.0, + "z": 0.0, + "w": 0.0 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0, + "w": 0.0 + }, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.ColorRGBAMaterialSlot", + "m_ObjectId": "44d74a125bc04035ababff9dfef7aa9b", + "m_Id": 0, + "m_DisplayName": "Custom Lighting Data 1", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "CustomLightingData1", + "m_StageCapability": 2, + "m_Value": { + "x": 0.0, + "y": 0.0, + "z": 0.0, + "w": 0.0 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0, + "w": 0.0 + }, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Vector1MaterialSlot", + "m_ObjectId": "4f090433c2c0473ea7f82f52dd28f272", + "m_Id": 0, + "m_DisplayName": "Shininess", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "Shininess", + "m_StageCapability": 2, + "m_Value": 0.5, + "m_DefaultValue": 0.5, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "56729bfb24fb4e2ca951b1ddeb07c3f2", + "m_Group": { + "m_Id": "" + }, + "m_Name": "SurfaceDescription.NormalTS", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": 0.0, + "y": 0.0, + "width": 0.0, + "height": 0.0 + } + }, + "m_Slots": [ + { + "m_Id": "74c8581c218e42f39a7b136a5909a73a" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "SurfaceDescription.NormalTS" +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.ColorRGBAMaterialSlot", + "m_ObjectId": "5e43231d43cf43c8b11726d431c9599f", + "m_Id": 0, + "m_DisplayName": "Custom Lighting Data 2", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "CustomLightingData2", + "m_StageCapability": 2, + "m_Value": { + "x": 0.0, + "y": 0.0, + "z": 0.0, + "w": 0.0 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0, + "w": 0.0 + }, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Vector4MaterialSlot", + "m_ObjectId": "6067176e41b94c17bc90dcec5989cc90", + "m_Id": 1, + "m_DisplayName": "Out", + "m_SlotType": 1, + "m_Hidden": false, + "m_ShaderOutputName": "Out", + "m_StageCapability": 3, + "m_Value": { + "x": 0.0, + "y": 0.0, + "z": 0.0, + "w": 0.0 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0, + "w": 0.0 + }, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.ColorRGBMaterialSlot", + "m_ObjectId": "661dd35371b440999c429205ad2bc785", + "m_Id": 0, + "m_DisplayName": "Emission", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "Emission", + "m_StageCapability": 2, + "m_Value": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_Labels": [], + "m_ColorMode": 1, + "m_DefaultColor": { + "r": 0.0, + "g": 0.0, + "b": 0.0, + "a": 1.0 + } +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.PositionMaterialSlot", + "m_ObjectId": "67c05795a65d45948a77418a30bec828", + "m_Id": 0, + "m_DisplayName": "Position", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "Position", + "m_StageCapability": 1, + "m_Value": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_Labels": [], + "m_Space": 0 +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Vector4MaterialSlot", + "m_ObjectId": "72b1d677aa644b8db16037e65b02c0ba", + "m_Id": 0, + "m_DisplayName": "Out", + "m_SlotType": 1, + "m_Hidden": false, + "m_ShaderOutputName": "Out", + "m_StageCapability": 3, + "m_Value": { + "x": 0.0, + "y": 0.0, + "z": 0.0, + "w": 0.0 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0, + "w": 0.0 + }, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.NormalMaterialSlot", + "m_ObjectId": "74c8581c218e42f39a7b136a5909a73a", + "m_Id": 0, + "m_DisplayName": "Normal (Tangent Space)", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "NormalTS", + "m_StageCapability": 2, + "m_Value": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_Labels": [], + "m_Space": 3 +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "7efba297d0b74c8093d51218c6f395ff", + "m_Group": { + "m_Id": "" + }, + "m_Name": "VertexDescription.Position", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": 0.0, + "y": 0.0, + "width": 0.0, + "height": 0.0 + } + }, + "m_Slots": [ + { + "m_Id": "67c05795a65d45948a77418a30bec828" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "VertexDescription.Position" +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.TangentMaterialSlot", + "m_ObjectId": "84ee1b81a59c46808dc179d24ac2c8ef", + "m_Id": 0, + "m_DisplayName": "Tangent", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "Tangent", + "m_StageCapability": 1, + "m_Value": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_Labels": [], + "m_Space": 0 +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "91cc7052d79a4ab2be1ade76e4a5dce1", + "m_Group": { + "m_Id": "" + }, + "m_Name": "SurfaceDescription.Glossiness", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": 0.0, + "y": 0.0, + "width": 0.0, + "height": 0.0 + } + }, + "m_Slots": [ + { + "m_Id": "c27c68ef6f594ce7896102b6980775f3" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "SurfaceDescription.Glossiness" +} + +{ + "m_SGVersion": 1, + "m_Type": "UnityEditor.ShaderGraph.ColorNode", + "m_ObjectId": "96bb2fb4f91942bb9606c4f2d40cb78a", + "m_Group": { + "m_Id": "" + }, + "m_Name": "Color", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": -609.0, + "y": 191.0, + "width": 208.0, + "height": 127.0 + } + }, + "m_Slots": [ + { + "m_Id": "72b1d677aa644b8db16037e65b02c0ba" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_Color": { + "color": { + "r": 0.5094339847564697, + "g": 0.5094339847564697, + "b": 0.5094339847564697, + "a": 0.0 + }, + "mode": 0 + } +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "99b4dba4390b4069b70670fafb064690", + "m_Group": { + "m_Id": "" + }, + "m_Name": "SurfaceDescription.Emission", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": 0.0, + "y": 0.0, + "width": 0.0, + "height": 0.0 + } + }, + "m_Slots": [ + { + "m_Id": "661dd35371b440999c429205ad2bc785" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "SurfaceDescription.Emission" +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "a1d3bed2f71e4821a066eb16fb345c3f", + "m_Group": { + "m_Id": "" + }, + "m_Name": "VertexDescription.Normal", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": 0.0, + "y": 0.0, + "width": 0.0, + "height": 0.0 + } + }, + "m_Slots": [ + { + "m_Id": "32073861999f411d875ed672cf22d495" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "VertexDescription.Normal" +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "acee2fabfe6146e9a2d3fdc348ff3c56", + "m_Group": { + "m_Id": "" + }, + "m_Name": "SurfaceDescription.Specular", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": 0.0, + "y": 0.0, + "width": 0.0, + "height": 0.0 + } + }, + "m_Slots": [ + { + "m_Id": "f87e65b98538435aaa6ddda4c9232e61" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "SurfaceDescription.Specular" +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Vector1MaterialSlot", + "m_ObjectId": "c27c68ef6f594ce7896102b6980775f3", + "m_Id": 0, + "m_DisplayName": "Glossiness", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "Glossiness", + "m_StageCapability": 2, + "m_Value": 0.5, + "m_DefaultValue": 0.5, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "cf9f37c16f3c4b809a112290771e909b", + "m_Group": { + "m_Id": "" + }, + "m_Name": "VertexDescription.Tangent", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": 0.0, + "y": 0.0, + "width": 0.0, + "height": 0.0 + } + }, + "m_Slots": [ + { + "m_Id": "84ee1b81a59c46808dc179d24ac2c8ef" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "VertexDescription.Tangent" +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "dd567d54bd034347a473820fc6d86736", + "m_Group": { + "m_Id": "" + }, + "m_Name": "SurfaceDescription.CustomLightingData2", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": 0.0, + "y": 0.0, + "width": 0.0, + "height": 0.0 + } + }, + "m_Slots": [ + { + "m_Id": "5e43231d43cf43c8b11726d431c9599f" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "SurfaceDescription.CustomLightingData2" +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.CustomFunctionNode", + "m_ObjectId": "eb4eb88d62ad4999be29d2e49ae8c0f8", + "m_Group": { + "m_Id": "" + }, + "m_Name": "Custom Function", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": -314.0, + "y": 194.0, + "width": 142.0, + "height": 94.0 + } + }, + "m_Slots": [ + { + "m_Id": "41d4ebdb0347493295537c91fadca239" + }, + { + "m_Id": "6067176e41b94c17bc90dcec5989cc90" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": false, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SourceType": 0, + "m_FunctionName": "Passthrough", + "m_FunctionSource": "ff58d7bda841877438d1453d66f77790", + "m_FunctionBody": "Enter function body here..." +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "f15775cdc4104f7aa5f3557417344d44", + "m_Group": { + "m_Id": "" + }, + "m_Name": "SurfaceDescription.Shininess", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": 0.0, + "y": 0.0, + "width": 0.0, + "height": 0.0 + } + }, + "m_Slots": [ + { + "m_Id": "4f090433c2c0473ea7f82f52dd28f272" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "SurfaceDescription.Shininess" +} + +{ + "m_SGVersion": 0, + "m_Type": "ShaderGraphEssentials.SGEUniversalCustomLitSubTarget", + "m_ObjectId": "f4544c958fd04f12890669c1c6416df8", + "m_NormalDropOffSpace": 0 +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.ColorRGBMaterialSlot", + "m_ObjectId": "f87e65b98538435aaa6ddda4c9232e61", + "m_Id": 0, + "m_DisplayName": "Specular Color", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "Specular", + "m_StageCapability": 2, + "m_Value": { + "x": 0.5, + "y": 0.5, + "z": 0.5 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_Labels": [], + "m_ColorMode": 0, + "m_DefaultColor": { + "r": 0.5, + "g": 0.5, + "b": 0.5, + "a": 1.0 + } +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "fadf2392448a4c6d9ba3d4f0c3686b9c", + "m_Group": { + "m_Id": "" + }, + "m_Name": "SurfaceDescription.BaseColor", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": 0.0, + "y": 0.0, + "width": 0.0, + "height": 0.0 + } + }, + "m_Slots": [ + { + "m_Id": "37e6fe3777ab46b39febcb17b4cf8cee" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "SurfaceDescription.BaseColor" +} + diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLightingGraph.shadergraph.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLightingGraph.shadergraph.meta new file mode 100644 index 0000000..267622f --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLightingGraph.shadergraph.meta @@ -0,0 +1,10 @@ +fileFormatVersion: 2 +guid: 823db6a430339504f989cd2b15452ae7 +ScriptedImporter: + internalIDToNameTable: [] + externalObjects: {} + serializedVersion: 2 + userData: + assetBundleName: + assetBundleVariant: + script: {fileID: 11500000, guid: 625f186215c104763be7675aa2d941aa, type: 3} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_ToonLighting.hlsl b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_ToonLighting.hlsl new file mode 100644 index 0000000..6a38385 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_ToonLighting.hlsl @@ -0,0 +1,72 @@ +#include "Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternal.hlsl" + +/* + * This is what you can access in the custom functions +struct Light +{ + half3 direction; + half3 color; + half distanceAttenuation; + half shadowAttenuation; + uint layerMask; +}; + +struct SGECustomLightingData +{ + float3 albedo; + float3 normal; // world space + float3 specular; + float glossiness; + float smoothness; // automatically converted from shininess + float3 emission; + float alpha; + float4 customLightingData1; // custom data you can use how you want (pass texture UV, properties / uniforms, vertex color ...etc) + float4 customLightingData2; +}; +*/ + +// this will function is called for every light +half3 SGE_DiffuseLightingCustom(Light light, SGECustomLightingData data) +{ + half NdotL = saturate(dot(data.normal, light.direction)); + half lightIntensity = smoothstep(0, 0.01, NdotL); + return light.color * lightIntensity * light.distanceAttenuation * light.shadowAttenuation; +} + +// this will function is called for every light +// you can't access Uniforms directly in there, +// nor pass it to the custom function node +// trying either of this will throw an error +// but you can pass it through data.customLightingData1 and use it how you see fit here. +half3 SGE_SpecularLightingCustom(Light light, half3 viewDir, SGECustomLightingData data) +{ + const float EPSILON = 0.01f; + // compute specular + half NdotL = saturate(dot(data.normal, light.direction)); + half lightIntensity = smoothstep(0, EPSILON, NdotL); + float3 halfVec = SafeNormalize(light.direction + viewDir); + float NdotH = saturate(dot(data.normal, halfVec)); + float modifier = pow(NdotH * lightIntensity, data.smoothness); + float modifierSmooth = smoothstep(EPSILON * 0.5, EPSILON, modifier); + half3 specularReflection = data.specular * modifierSmooth; + + // compute rimlight + // data.customLightingData1: xyz = _RimColor + // data.customLightingData2: x = _RimThreshold, y = _RimAmount + half rimDot = 1 - dot(viewDir, data.normal); + half rimIntensity = rimDot * pow(NdotL, (half)data.customLightingData2.x); + rimIntensity = smoothstep(data.customLightingData2.y - EPSILON, data.customLightingData2.y + EPSILON, rimIntensity); + half3 rim = rimIntensity * data.customLightingData1.xyz; + + // I chose to have the rim affected by the light's color, but feel free to improvise! + return light.color * (specularReflection * light.distanceAttenuation * light.shadowAttenuation + rim); +} + +// necessary function because at the moment a custom function node NEEDS to output a result in the graph +// otherwise it can be optimized out +// here we don't do anything, so it doesn't matter where you plug this node, +// because the custom lighting function will be called by the master node +void Passthrough_float(float4 In, out float4 Out) +{ + Out = In; +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_ToonLighting.hlsl.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_ToonLighting.hlsl.meta new file mode 100644 index 0000000..bad6897 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_ToonLighting.hlsl.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: 3957bbcf7c3a3a748a82a440dcc9ea67 +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitForwardPass.hlsl b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitForwardPass.hlsl new file mode 100644 index 0000000..2c416b9 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitForwardPass.hlsl @@ -0,0 +1,137 @@ +void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData) +{ + inputData = (InputData)0; + + inputData.positionWS = input.positionWS; + + #ifdef _NORMALMAP + // IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped. + float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale(); + float3 bitangent = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz); + + inputData.tangentToWorld = half3x3(input.tangentWS.xyz, bitangent.xyz, input.normalWS.xyz); + + #if _NORMAL_DROPOFF_TS + inputData.normalWS = TransformTangentToWorld(surfaceDescription.NormalTS, inputData.tangentToWorld); + #elif _NORMAL_DROPOFF_OS + inputData.normalWS = TransformObjectToWorldNormal(surfaceDescription.NormalOS); + #elif _NORMAL_DROPOFF_WS + inputData.normalWS = surfaceDescription.NormalWS; + #endif + #else + inputData.normalWS = input.normalWS; + #endif + inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS); + inputData.viewDirectionWS = GetWorldSpaceNormalizeViewDir(input.positionWS); + + #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR) + inputData.shadowCoord = input.shadowCoord; + #elif defined(MAIN_LIGHT_CALCULATE_SHADOWS) + inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS); + #else + inputData.shadowCoord = float4(0, 0, 0, 0); + #endif + + inputData.fogCoord = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactorAndVertexLight.x); + inputData.vertexLighting = input.fogFactorAndVertexLight.yzw; +#if defined(DYNAMICLIGHTMAP_ON) + inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.dynamicLightmapUV.xy, input.sh, inputData.normalWS); +#elif !defined(LIGHTMAP_ON) && (defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2)) + inputData.bakedGI = SAMPLE_GI(input.sh, + GetAbsolutePositionWS(inputData.positionWS), + inputData.normalWS, + inputData.viewDirectionWS, + input.positionCS.xy); +#else + inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.sh, inputData.normalWS); +#endif + inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS); + inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV); + + #if defined(DEBUG_DISPLAY) + #if defined(DYNAMICLIGHTMAP_ON) + inputData.dynamicLightmapUV = input.dynamicLightmapUV.xy; + #endif + #if defined(LIGHTMAP_ON) + inputData.staticLightmapUV = input.staticLightmapUV; + #else + inputData.vertexSH = input.sh; + #endif + #endif +} + +PackedVaryings vert(Attributes input) +{ + Varyings output = (Varyings)0; + output = BuildVaryings(input); + PackedVaryings packedOutput = (PackedVaryings)0; + packedOutput = PackVaryings(output); + return packedOutput; +} + +void frag( + PackedVaryings packedInput + , out half4 outColor : SV_Target0 +#ifdef _WRITE_RENDERING_LAYERS + , out float4 outRenderingLayers : SV_Target1 +#endif +) +{ + Varyings unpacked = UnpackVaryings(packedInput); + UNITY_SETUP_INSTANCE_ID(unpacked); + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked); + + SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked); + +#if defined(_SURFACE_TYPE_TRANSPARENT) + bool isTransparent = true; +#else + bool isTransparent = false; +#endif + +#if defined(_ALPHATEST_ON) + half alpha = AlphaDiscard(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold); +#elif defined(_SURFACE_TYPE_TRANSPARENT) + half alpha = surfaceDescription.Alpha; +#else + half alpha = half(1.0); +#endif + + #if defined(LOD_FADE_CROSSFADE) && USE_UNITY_CROSSFADE + LODFadeCrossFade(unpacked.positionCS); + #endif + + InputData inputData; + InitializeInputData(unpacked, surfaceDescription, inputData); + // TODO: Mip debug modes would require this, open question how to do this on ShaderGraph. + //SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.texCoord1.xy, _MainTex); + + half3 normalTS = half3(0, 0, 0); + #if defined(_NORMALMAP) && defined(_NORMAL_DROPOFF_TS) + normalTS = surfaceDescription.NormalTS; + #endif + + alpha = saturate(alpha); + half3 baseColor = AlphaModulate(surfaceDescription.BaseColor, alpha); + + half4 color = UniversalFragmentBlinnPhong( + inputData, + baseColor, + half4(surfaceDescription.Specular, surfaceDescription.Smoothness), + surfaceDescription.Smoothness, + surfaceDescription.Emission, + alpha, + normalTS); + + + color.rgb = MixFog(color.rgb, inputData.fogCoord); + + color.a = OutputAlpha(color.a, isTransparent); + + outColor = color; + +#ifdef _WRITE_RENDERING_LAYERS + uint renderingLayers = GetMeshRenderingLayer(); + outRenderingLayers = float4(EncodeMeshRenderingLayer(renderingLayers), 0, 0, 0); +#endif +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitForwardPass.hlsl.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitForwardPass.hlsl.meta new file mode 100644 index 0000000..ea2b55e --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitForwardPass.hlsl.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: fda4d5a52149e5a499b247360d8702fc +ShaderImporter: + externalObjects: {} + defaultTextures: [] + nonModifiableTextures: [] + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitGBufferPass.hlsl b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitGBufferPass.hlsl new file mode 100644 index 0000000..5c19b51 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitGBufferPass.hlsl @@ -0,0 +1,138 @@ + +void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData) +{ + inputData = (InputData)0; + + inputData.positionWS = input.positionWS; + inputData.positionCS = input.positionCS; + + #ifdef _NORMALMAP + // IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped. + float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale(); + float3 bitangent = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz); + + inputData.tangentToWorld = half3x3(input.tangentWS.xyz, bitangent.xyz, input.normalWS.xyz); + #if _NORMAL_DROPOFF_TS + inputData.normalWS = TransformTangentToWorld(surfaceDescription.NormalTS, inputData.tangentToWorld); + #elif _NORMAL_DROPOFF_OS + inputData.normalWS = TransformObjectToWorldNormal(surfaceDescription.NormalOS); + #elif _NORMAL_DROPOFF_WS + inputData.normalWS = surfaceDescription.NormalWS; + #endif + #else + inputData.normalWS = input.normalWS; + #endif + inputData.normalWS = NormalizeNormalPerPixel(inputData.normalWS); + inputData.viewDirectionWS = GetWorldSpaceNormalizeViewDir(input.positionWS); + +#if defined(MAIN_LIGHT_CALCULATE_SHADOWS) + inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS); +#else + inputData.shadowCoord = float4(0, 0, 0, 0); +#endif + + inputData.fogCoord = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactorAndVertexLight.x); + inputData.vertexLighting = input.fogFactorAndVertexLight.yzw; +#if defined(DYNAMICLIGHTMAP_ON) + inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.dynamicLightmapUV.xy, input.sh, inputData.normalWS); +#elif !defined(LIGHTMAP_ON) && (defined(PROBE_VOLUMES_L1) || defined(PROBE_VOLUMES_L2)) + inputData.bakedGI = SAMPLE_GI(input.sh, + GetAbsolutePositionWS(inputData.positionWS), + inputData.normalWS, + inputData.viewDirectionWS, + inputData.positionCS.xy); +#else + inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.sh, inputData.normalWS); +#endif + inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS); + inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV); + + #if defined(DEBUG_DISPLAY) + #if defined(DYNAMICLIGHTMAP_ON) + inputData.dynamicLightmapUV = input.dynamicLightmapUV.xy; + #endif + #if defined(LIGHTMAP_ON) + inputData.staticLightmapUV = input.staticLightmapUV; + #else + inputData.vertexSH = input.sh; + #endif + #endif +} + +PackedVaryings vert(Attributes input) +{ + Varyings output = (Varyings)0; + output = BuildVaryings(input); + PackedVaryings packedOutput = (PackedVaryings)0; + packedOutput = PackVaryings(output); + return packedOutput; +} + + +void PatchSimpleLitSurfaceData(SurfaceDescription surfaceDescription, out SurfaceData outSurfaceData) +{ + outSurfaceData = (SurfaceData)0; + + #if _ALPHATEST_ON + half alpha = surfaceDescription.Alpha; + clip(alpha - surfaceDescription.AlphaClipThreshold); + #elif _SURFACE_TYPE_TRANSPARENT + half alpha = surfaceDescription.Alpha; + #else + half alpha = 1; + #endif + + outSurfaceData.alpha = alpha; + + outSurfaceData.albedo = AlphaModulate(surfaceDescription.BaseColor, alpha);; +#ifdef _ALPHAPREMULTIPLY_ON + outSurfaceData.albedo *= outSurfaceData.alpha; +#endif + + half4 specularSmoothness = half4(surfaceDescription.Specular, surfaceDescription.Smoothness); + outSurfaceData.metallic = 0.0; // unused + outSurfaceData.specular = specularSmoothness.rgb; + outSurfaceData.smoothness = specularSmoothness.a; + outSurfaceData.normalTS = surfaceDescription.NormalTS; + outSurfaceData.occlusion = 1.0; + outSurfaceData.emission = surfaceDescription.Emission; +} + +FragmentOutput frag(PackedVaryings packedInput) +{ + Varyings unpacked = UnpackVaryings(packedInput); + UNITY_SETUP_INSTANCE_ID(unpacked); + UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked); + + SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked); + + SurfaceData surfaceData; + PatchSimpleLitSurfaceData(surfaceDescription, surfaceData); + + #if defined(LOD_FADE_CROSSFADE) && USE_UNITY_CROSSFADE + LODFadeCrossFade(unpacked.positionCS); + #endif + + InputData inputData; + InitializeInputData(unpacked, surfaceDescription, inputData); + // TODO: Mip debug modes would require this, open question how to do this on ShaderGraph. + //SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.uv, _MainTex); + + float3 specular = surfaceDescription.Specular; + +#ifdef _DBUFFER + ApplyDecal(unpacked.positionCS, + surfaceDescription.BaseColor, + specular, + inputData.normalWS, + 1, + surfaceDescription.Occlusion, + surfaceDescription.Smoothness); +#endif + + Light mainLight = GetMainLight(inputData.shadowCoord, inputData.positionWS, inputData.shadowMask); + MixRealtimeAndBakedGI(mainLight, inputData.normalWS, inputData.bakedGI, inputData.shadowMask); + half4 color = half4(inputData.bakedGI * surfaceData.albedo + surfaceData.emission, surfaceData.alpha); + + return SurfaceDataToGbuffer(surfaceData, inputData, color.rgb, kLightingSimpleLit); +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitGBufferPass.hlsl.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitGBufferPass.hlsl.meta new file mode 100644 index 0000000..50ea13c --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitGBufferPass.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: be0a8589dbc698548aeb21bac1b72c73 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Templates.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Templates.meta new file mode 100644 index 0000000..8aecb20 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Templates.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7a5534129ff657d45a4274b7585aa066 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Templates/PassMesh.template b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Templates/PassMesh.template new file mode 100644 index 0000000..db86fb7 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Templates/PassMesh.template @@ -0,0 +1,130 @@ +Pass +{ + $splice(PassName) + Tags + { + $splice(LightMode) + } + + // Render State + $splice(Blending) + $splice(Culling) + $splice(ZTest) + $splice(ZWrite) + $splice(ColorMask) + $splice(Stencil) + + HLSLPROGRAM + #pragma vertex vert + #pragma fragment frag + + // Debug + $splice(Debug) + + // -------------------------------------------------- + // Pass + + // Pragmas + $splice(PassPragmas) + + // Keywords + $splice(PassKeywords) + $splice(GraphKeywords) + + // Defines + $SurfaceType.Transparent: #define _SURFACE_TYPE_TRANSPARENT 1 + $AlphaClip: #define _AlphaClip 1 + $SpecularColor: #define _SPECULAR_COLOR 1 + $Normal: #define _NORMALMAP 1 + $BlendMode.Add: #define _BLENDMODE_ADD 1 + $BlendMode.Premultiply: #define _ALPHAPREMULTIPLY_ON 1 + $features.NormalDropOffTS: #define _NORMAL_DROPOFF_TS 1 + $features.NormalDropOffOS: #define _NORMAL_DROPOFF_OS 1 + $features.NormalDropOffWS: #define _NORMAL_DROPOFF_WS 1 + $Attributes.normalOS: #define ATTRIBUTES_NEED_NORMAL + $Attributes.tangentOS: #define ATTRIBUTES_NEED_TANGENT + $Attributes.uv0: #define ATTRIBUTES_NEED_TEXCOORD0 + $Attributes.uv1: #define ATTRIBUTES_NEED_TEXCOORD1 + $Attributes.uv2: #define ATTRIBUTES_NEED_TEXCOORD2 + $Attributes.uv3: #define ATTRIBUTES_NEED_TEXCOORD3 + $Attributes.color: #define ATTRIBUTES_NEED_COLOR + $Varyings.positionWS: #define VARYINGS_NEED_POSITION_WS + $Varyings.positionPredisplacementWS: #define VARYINGS_NEED_POSITIONPREDISPLACEMENT_WS + $Varyings.normalWS: #define VARYINGS_NEED_NORMAL_WS + $Varyings.tangentWS: #define VARYINGS_NEED_TANGENT_WS + $Varyings.texCoord0: #define VARYINGS_NEED_TEXCOORD0 + $Varyings.texCoord1: #define VARYINGS_NEED_TEXCOORD1 + $Varyings.texCoord2: #define VARYINGS_NEED_TEXCOORD2 + $Varyings.texCoord3: #define VARYINGS_NEED_TEXCOORD3 + $Varyings.color: #define VARYINGS_NEED_COLOR + $Varyings.viewDirectionWS: #define VARYINGS_NEED_VIEWDIRECTION_WS + $Varyings.bitangentWS: #define VARYINGS_NEED_BITANGENT_WS + $Varyings.screenPosition: #define VARYINGS_NEED_SCREENPOSITION + $Varyings.fogFactorAndVertexLight: #define VARYINGS_NEED_FOG_AND_VERTEX_LIGHT + $Varyings.cullFace: #define VARYINGS_NEED_CULLFACE + $features.graphVertex: #define FEATURES_GRAPH_VERTEX + $splice(PassInstancing) + $splice(GraphDefines) + $splice(DotsInstancingVars) + + // Includes + $splice(CustomInterpolatorPreInclude) + + $splice(PassIncludes) + + // -------------------------------------------------- + // Graph + + // Graph Properties + $splice(GraphProperties) + + // Graph Includes + $splice(GraphIncludes) + + // -- Property used by ScenePickingPass + #ifdef SCENEPICKINGPASS + float4 _SelectionID; + #endif + + // -- Properties used by SceneSelectionPass + #ifdef SCENESELECTIONPASS + int _ObjectId; + int _PassValue; + #endif + + + // Graph Functions + $splice(GraphFunctions) + + $splice(CustomInterpolatorPreVertex) + + // Graph Vertex + $splice(GraphVertex) + + $splice(CustomInterpolatorPreSurface) + + // Graph Pixel + $splice(GraphPixel) + + // -------------------------------------------------- + // Structs and Packing + + $splice(CustomInterpolatorPrePacking) + + $buildType(Attributes) + + $buildType(Varyings) + + // -------------------------------------------------- + // Build Graph Inputs + + $features.graphVertex: $include("BuildVertexDescriptionInputs.template.hlsl") + $features.graphPixel: $include("BuildSurfaceDescriptionInputs.template.hlsl") + + // -------------------------------------------------- + // Main + + $splice(MainInclude) + + ENDHLSL +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Templates/PassMesh.template.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Templates/PassMesh.template.meta new file mode 100644 index 0000000..f0b29ac --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Templates/PassMesh.template.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 7f48c3f430bfe574a86851f4ba45d6f6 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific.meta new file mode 100644 index 0000000..10bbaa1 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: a66ba68fb8bca1a479afdf340430c9ca +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks.meta new file mode 100644 index 0000000..6c27036 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 3651e0c7d29b0bf49a967294422e9d79 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGECustomLitShaderGraph.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGECustomLitShaderGraph.cs new file mode 100644 index 0000000..7b90e6f --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGECustomLitShaderGraph.cs @@ -0,0 +1,76 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using UnityEditor; +using UnityEditor.ProjectWindowCallback; +using UnityEditor.ShaderGraph; +using UnityEngine; + +namespace ShaderGraphEssentials +{ + class CreateSGECustomLitShaderGraph : EndNameEditAction + { + private const string DefaultCustomLightingGraphPath = + "Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_DefaultCustomLightingGraph.shadergraph"; + + [MenuItem("Assets/Create/Shader Graph/ShaderGraphEssentials/SGE CustomLit Shader Graph", false, 303)] + public static void CreateMaterialGraph() + { + ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, CreateInstance(), + string.Format("New Shader Graph.{0}", ShaderGraphImporter.Extension), null, null); + } + + public override void Action(int instanceId, string pathName, string resourceFile) + { + // we try to copy the default already have the custom lighting function node setup + bool success = AssetDatabase.CopyAsset(DefaultCustomLightingGraphPath, pathName); + // if it fails we fallback to the "official" method + if (!success) + { + Debug.LogWarning("ShaderGraphEssentials couldn't create the new custom lit graph by copying the default from " + DefaultCustomLightingGraphPath + + " to " + pathName + ". An empty graph has been created instead, you now have to create the custom lighting function node before it will compile correctly."); + CreateEmptyGraph(); + } + + AssetDatabase.Refresh(); + } + + private void CreateEmptyGraph() + { + var target = (SGEUniversalTarget)Activator.CreateInstance(typeof(SGEUniversalTarget)); + target.TrySetActiveSubTarget(typeof(SGEUniversalCustomLitSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.Specular, + SGEFields.SurfaceDescription.Glossiness, + SGEFields.SurfaceDescription.Shininess, + BlockFields.SurfaceDescription.Emission, + SGEFields.SurfaceDescription.CustomLightingData1, + SGEFields.SurfaceDescription.CustomLightingData2, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + } + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGECustomLitShaderGraph.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGECustomLitShaderGraph.cs.meta new file mode 100644 index 0000000..19b813b --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGECustomLitShaderGraph.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3168e2865266f4a4fbe1e9f901ea1ca7 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGESimpleLitShaderGraph.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGESimpleLitShaderGraph.cs new file mode 100644 index 0000000..1d926cc --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGESimpleLitShaderGraph.cs @@ -0,0 +1,47 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using UnityEditor; +using UnityEditor.ShaderGraph; + +namespace ShaderGraphEssentials +{ + static class CreateSGESimpleLitShaderGraph + { + [MenuItem("Assets/Create/Shader Graph/ShaderGraphEssentials/SGE SimpleLit Shader Graph", false, 302)] + public static void CreateSGESimpleLitGraph() + { + var target = (SGEUniversalTarget)Activator.CreateInstance(typeof(SGEUniversalTarget)); + target.TrySetActiveSubTarget(typeof(SGEUniversalSimpleLitSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.Specular, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Emission, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + } + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGESimpleLitShaderGraph.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGESimpleLitShaderGraph.cs.meta new file mode 100644 index 0000000..b7a2c79 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGESimpleLitShaderGraph.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 181f91f2a09234547a2987a1b8f3c4be +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGEUnlitShaderGraph.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGEUnlitShaderGraph.cs new file mode 100644 index 0000000..fee6dfd --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGEUnlitShaderGraph.cs @@ -0,0 +1,43 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using UnityEditor; +using UnityEditor.ShaderGraph; + +namespace ShaderGraphEssentials +{ + static class CreateSGEUnlitShaderGraph + { + [MenuItem("Assets/Create/Shader Graph/ShaderGraphEssentials/SGE Unlit Shader Graph", false, 301)] + public static void CreateSGEUnlitGraph() + { + var target = (SGEUniversalTarget)Activator.CreateInstance(typeof(SGEUniversalTarget)); + target.TrySetActiveSubTarget(typeof(SGEUniversalUnlitSubTarget)); + + var blockDescriptors = new [] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + BlockFields.SurfaceDescription.BaseColor, + }; + + GraphUtil.CreateNewGraphWithOutputs(new [] {target}, blockDescriptors); + } + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGEUnlitShaderGraph.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGEUnlitShaderGraph.cs.meta new file mode 100644 index 0000000..68b6a8e --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/AssetCallbacks/CreateSGEUnlitShaderGraph.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f15a3720b3659ef4eaba93127ede1aa8 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/SGEUniversal.asmref b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/SGEUniversal.asmref new file mode 100644 index 0000000..583b71c --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/SGEUniversal.asmref @@ -0,0 +1,3 @@ +{ + "reference": "GUID:c579267770062bf448e75eb160330b7f" +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/SGEUniversal.asmref.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/SGEUniversal.asmref.meta new file mode 100644 index 0000000..c2d0429 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/SGEUniversal.asmref.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 93556a0f2aef48643b8357eac6f4a112 +AssemblyDefinitionReferenceImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets.meta new file mode 100644 index 0000000..e6c845d --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 832d7150527f81846a2f442962283294 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEFields.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEFields.cs new file mode 100644 index 0000000..e7bb61e --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEFields.cs @@ -0,0 +1,67 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using UnityEditor.ShaderGraph; +using UnityEngine; + +namespace ShaderGraphEssentials +{ + static class SGEFields + { + public static FieldDescriptor BlendModeOff = new FieldDescriptor(string.Empty, "BlendModeOff", "_BLEND_MODE_OFF 1"); + public static FieldDescriptor BlendModeAlpha = new FieldDescriptor(string.Empty, "BlendModeAlpha", "_BLEND_MODE_ALPHA 1"); + public static FieldDescriptor BlendModePremultiply = new FieldDescriptor(string.Empty, "BlendModePremultiply", "_BLEND_MODE_PREMULTIPLY 1"); + public static FieldDescriptor BlendModeAdditive = new FieldDescriptor(string.Empty, "BlendModeAdditive", "_BLEND_MODE_ADDITIVE 1"); + public static FieldDescriptor BlendModeMultiply = new FieldDescriptor(string.Empty, "BlendModeMultiply", "_BLEND_MODE_MULTIPLY 1"); + + public static FieldDescriptor CullModeOff = new FieldDescriptor(string.Empty, "CullModeOff", "_CULL_MODE_OFF 1"); + public static FieldDescriptor CullModeFront = new FieldDescriptor(string.Empty, "CullModeFront", "_CULL_MODE_FRONT 1"); + public static FieldDescriptor CullModeBack = new FieldDescriptor(string.Empty, "CullModeBack", "_CULL_MODE_BACK 1"); + + public static FieldDescriptor ZWrite = new FieldDescriptor(string.Empty, "ZWrite", "_ZWRITE 1"); + + public static FieldDescriptor ZTestLess = new FieldDescriptor(string.Empty, "ZTestLess", "_ZTEST_LESS 1"); + public static FieldDescriptor ZTestGreater = new FieldDescriptor(string.Empty, "ZTestGreater", "_ZTEST_GREATER 1"); + public static FieldDescriptor ZTestLEqual = new FieldDescriptor(string.Empty, "ZTestLEqual", "_ZTEST_LEQUAL 1"); + public static FieldDescriptor ZTestGEqual = new FieldDescriptor(string.Empty, "ZTestGEqual", "_ZTEST_GEQUAL 1"); + public static FieldDescriptor ZTestEqual = new FieldDescriptor(string.Empty, "ZTestEqual", "_ZTEST_EQUAL 1"); + public static FieldDescriptor ZTestNotEqual = new FieldDescriptor(string.Empty, "ZTestNotEqual", "_ZTEST_NOTEQUAL 1"); + public static FieldDescriptor ZTestAlways = new FieldDescriptor(string.Empty, "ZTestAlways", "_ZTEST_ALWAYS 1"); + + public static FieldDescriptor AlphaClip = new FieldDescriptor(string.Empty, "AlphaClip", "_AlphaClip 1"); + + [GenerateBlocks("SGE Universal")] + public struct SurfaceDescription + { + private static string name = "SurfaceDescription"; + + public static BlockFieldDescriptor Shininess = new BlockFieldDescriptor(SGEFields.SurfaceDescription.name, "Shininess", "Shininess", "SURFACEDESCRIPTION_SHININESS", + new FloatControl(0.5f), ShaderStage.Fragment); + + public static BlockFieldDescriptor Glossiness = new BlockFieldDescriptor(SGEFields.SurfaceDescription.name, "Glossiness", "Glossiness", "SURFACEDESCRIPTION_GLOSSINESS", + new FloatControl(0.5f), ShaderStage.Fragment); + + public static BlockFieldDescriptor CustomLightingData1 = new BlockFieldDescriptor(SGEFields.SurfaceDescription.name, "CustomLightingData1", "Custom Lighting Data 1", + "SURFACEDESCRIPTION_CUSTOMLIGHTINGDATA1", + new ColorRGBAControl(Vector4.zero), ShaderStage.Fragment); + + public static BlockFieldDescriptor CustomLightingData2 = new BlockFieldDescriptor(SGEFields.SurfaceDescription.name, "CustomLightingData2", "Custom Lighting Data 2", + "SURFACEDESCRIPTION_CUSTOMLIGHTINGDATA2", + new ColorRGBAControl(Vector4.zero), ShaderStage.Fragment); + } + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEFields.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEFields.cs.meta new file mode 100644 index 0000000..52ff37a --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEFields.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c1495eb42a050bb4b981d9bb7dae11ca +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEShaderUtils.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEShaderUtils.cs new file mode 100644 index 0000000..7a3f235 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEShaderUtils.cs @@ -0,0 +1,34 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +namespace ShaderGraphEssentials +{ + public static class SGEShaderUtils + { + internal enum SGEShaderID + { + // ShaderGraph IDs start at 1000, correspond to subtargets + //SG_Unlit = 1000, // UniversalUnlitSubTarget + //SG_Lit, // UniversalLitSubTarget + + // we start much higher + SGE_SimpleLit = 1030, + SGE_CustomLit, + SGE_Unlit, + } + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEShaderUtils.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEShaderUtils.cs.meta new file mode 100644 index 0000000..70fe2c7 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEShaderUtils.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d5888b0953181f440b21ede04ebaeda6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalCustomLitSubTarget.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalCustomLitSubTarget.cs new file mode 100644 index 0000000..3054a79 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalCustomLitSubTarget.cs @@ -0,0 +1,855 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using System.Collections.Generic; +using System.Linq; +using ShaderGraphEssentials.Legacy; +using UnityEditor; +using UnityEditor.Rendering.Universal.ShaderGraph; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.ShaderGraph.Serialization; + +using UnityEngine; +using UnityEngine.Assertions; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; +using UnityEngine.UIElements; +using static ShaderGraphEssentials.SGESubShaderUtils; +using static ShaderGraphEssentials.SGEShaderUtils; + +namespace ShaderGraphEssentials +{ + sealed class SGEUniversalCustomLitSubTarget : SGEUniversalSubTarget, ILegacyTarget + { + static readonly GUID kSourceCodeGuid = new GUID("1586b3525f0fc80429dc737b7f7c754c"); // SGEUniversalCustomLitSubTarget.cs + static readonly GUID kInternalSourceCodeGuid = new GUID("88bc0d7c5620cfd42b495c5b08e2a4c3"); // SGE_CustomLightingInternal.cs + static readonly GUID kInternalFullSourceCodeGuid = new GUID("63cbeb35240376b4b8f71e4ccfc027a4"); // SGE_CustomLightingInternalFull.cs + + public override int latestVersion => 2; + + [SerializeField] + private NormalDropOffSpace m_NormalDropOffSpace = NormalDropOffSpace.Tangent; + + [SerializeField] + bool m_BlendModePreserveSpecular = true; + + public SGEUniversalCustomLitSubTarget() + { + displayName = "SGE CustomLit"; + } + + protected override SGEShaderID shaderID => SGEShaderID.SGE_CustomLit; + + public NormalDropOffSpace normalDropOffSpace + { + get => m_NormalDropOffSpace; + set => m_NormalDropOffSpace = value; + } + + public bool blendModePreserveSpecular + { + get => m_BlendModePreserveSpecular; + set => m_BlendModePreserveSpecular = value; + } + + public override bool IsActive() => true; + + public override void Setup(ref TargetSetupContext context) + { + context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency); + context.AddAssetDependency(kInternalSourceCodeGuid, AssetCollection.Flags.SourceDependency); + context.AddAssetDependency(kInternalFullSourceCodeGuid, AssetCollection.Flags.SourceDependency); + + base.Setup(ref context); + + // Process SubShaders + context.AddSubShader(PostProcessSubShader(SubShaders.LitSubShader(target, target.renderType.ToString(), target.renderQueue.ToString(), target.disableBatching.ToString(), blendModePreserveSpecular))); + } + + public override void ProcessPreviewMaterial(Material material) + { + /*if (target.allowMaterialOverride) + { + // copy our target's default settings into the material + // (technically not necessary since we are always recreating the material from the shader each time, + // which will pull over the defaults from the shader definition) + // but if that ever changes, this will ensure the defaults are set + material.SetFloat(Property.SpecularWorkflowMode, (float)workflowMode); + material.SetFloat(Property.CastShadows, target.castShadows ? 1.0f : 0.0f); + material.SetFloat(Property.ReceiveShadows, target.receiveShadows ? 1.0f : 0.0f); + material.SetFloat(Property.SurfaceType, (float)target.surfaceType); + material.SetFloat(Property.BlendMode, (float)target.alphaMode); + material.SetFloat(Property.AlphaClip, target.alphaClip ? 1.0f : 0.0f); + material.SetFloat(Property.CullMode, (int)target.renderFace); + material.SetFloat(Property.ZWriteControl, (float)target.zWriteControl); + material.SetFloat(Property.ZTest, (float)target.zTestMode); + }*/ + + // call the full unlit material setup function + //ShaderGraphLitGUI.UpdateMaterial(material, Unity.Rendering.Universal.ShaderUtils.MaterialUpdateType.CreatedNewMaterial); + } + + public override void GetFields(ref TargetFieldContext context) + { + base.GetFields(ref context); + + var descs = context.blocks.Select(x => x.descriptor); + + // Lit + context.AddField(UniversalFields.NormalDropOffOS, normalDropOffSpace == NormalDropOffSpace.Object); + context.AddField(UniversalFields.NormalDropOffTS, normalDropOffSpace == NormalDropOffSpace.Tangent); + context.AddField(UniversalFields.NormalDropOffWS, normalDropOffSpace == NormalDropOffSpace.World); + context.AddField(UniversalFields.Normal, descs.Contains(BlockFields.SurfaceDescription.NormalOS) || + descs.Contains(BlockFields.SurfaceDescription.NormalTS) || + descs.Contains(BlockFields.SurfaceDescription.NormalWS)); + + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + context.AddBlock(BlockFields.SurfaceDescription.NormalOS, normalDropOffSpace == NormalDropOffSpace.Object); + context.AddBlock(BlockFields.SurfaceDescription.NormalTS, normalDropOffSpace == NormalDropOffSpace.Tangent); + context.AddBlock(BlockFields.SurfaceDescription.NormalWS, normalDropOffSpace == NormalDropOffSpace.World); + context.AddBlock(BlockFields.SurfaceDescription.Emission); + context.AddBlock(BlockFields.SurfaceDescription.Specular); + context.AddBlock(SGEFields.SurfaceDescription.Glossiness); + context.AddBlock(SGEFields.SurfaceDescription.Shininess); + context.AddBlock(SGEFields.SurfaceDescription.CustomLightingData1); + context.AddBlock(SGEFields.SurfaceDescription.CustomLightingData2); + } + + public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) + { + // if using material control, add the material property to control workflow mode + /*if (target.allowMaterialOverride) + { + collector.AddFloatProperty(Property.SpecularWorkflowMode, (float)workflowMode); + collector.AddFloatProperty(Property.CastShadows, target.castShadows ? 1.0f : 0.0f); + collector.AddFloatProperty(Property.ReceiveShadows, target.receiveShadows ? 1.0f : 0.0f); + + // setup properties using the defaults + collector.AddFloatProperty(Property.SurfaceType, (float)target.surfaceType); + collector.AddFloatProperty(Property.BlendMode, (float)target.alphaMode); + collector.AddFloatProperty(Property.AlphaClip, target.alphaClip ? 1.0f : 0.0f); + collector.AddFloatProperty(Property.SrcBlend, 1.0f); // always set by material inspector, ok to have incorrect values here + collector.AddFloatProperty(Property.DstBlend, 0.0f); // always set by material inspector, ok to have incorrect values here + collector.AddToggleProperty(Property.ZWrite, (target.surfaceType == SurfaceType.Opaque)); + collector.AddFloatProperty(Property.ZWriteControl, (float)target.zWriteControl); + collector.AddFloatProperty(Property.ZTest, (float)target.zTestMode); // ztest mode is designed to directly pass as ztest + collector.AddFloatProperty(Property.CullMode, (float)target.renderFace); // render face enum is designed to directly pass as a cull mode + + bool enableAlphaToMask = (target.alphaClip && (target.surfaceType == SurfaceType.Opaque)); + collector.AddFloatProperty(Property.AlphaToMask, enableAlphaToMask ? 1.0f : 0.0f); + }*/ + } + + public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) + { + context.AddProperty("Fragment Normal Space", new EnumField(NormalDropOffSpace.Tangent) { value = normalDropOffSpace }, (evt) => + { + if (Equals(normalDropOffSpace, evt.newValue)) + return; + + registerUndo("Change Fragment Normal Space"); + normalDropOffSpace = (NormalDropOffSpace)evt.newValue; + onChange(); + }); + + if (target.blendMode != BlendMode.Off) + { + if (target.blendMode == BlendMode.Alpha || target.blendMode == BlendMode.Additive) + context.AddProperty("Preserve Specular Lighting", new Toggle() { value = blendModePreserveSpecular }, (evt) => + { + if (Equals(blendModePreserveSpecular, evt.newValue)) + return; + + registerUndo("Change Preserve Specular"); + blendModePreserveSpecular = evt.newValue; + onChange(); + }); + } + } + + protected override int ComputeMaterialNeedsUpdateHash() + { + int hash = base.ComputeMaterialNeedsUpdateHash(); + hash = hash * 23 /*+ target.allowMaterialOverride.GetHashCode()*/; + return hash; + } + + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + if(!(masterNode is SGECustomLitMasterNode1 sgeCustomLitMasterNode)) + return false; + + m_NormalDropOffSpace = sgeCustomLitMasterNode.m_NormalDropOffSpace; + + // Handle mapping of Normal block specifically + BlockFieldDescriptor normalBlock; + switch(m_NormalDropOffSpace) + { + case NormalDropOffSpace.Object: + normalBlock = BlockFields.SurfaceDescription.NormalOS; + break; + case NormalDropOffSpace.World: + normalBlock = BlockFields.SurfaceDescription.NormalWS; + break; + default: + normalBlock = BlockFields.SurfaceDescription.NormalTS; + break; + } + + // Set blockmap + blockMap = new Dictionary() + { + { BlockFields.VertexDescription.Position, 8 }, + { BlockFields.VertexDescription.Normal, 11 }, + { BlockFields.VertexDescription.Tangent, 12 }, + { BlockFields.SurfaceDescription.BaseColor, 0 }, + { BlockFields.SurfaceDescription.Specular, 1 }, + { SGEFields.SurfaceDescription.Shininess, 2 }, + { SGEFields.SurfaceDescription.Glossiness, 3 }, + { normalBlock, 4 }, + { BlockFields.SurfaceDescription.Emission, 5 }, + { BlockFields.SurfaceDescription.Alpha, 6 }, + { BlockFields.SurfaceDescription.AlphaClipThreshold, 7 }, + { SGEFields.SurfaceDescription.CustomLightingData1, 9 }, + { SGEFields.SurfaceDescription.CustomLightingData2, 10 }, + }; + + return true; + } + + internal override void OnAfterParentTargetDeserialized() + { + Assert.IsNotNull(target); + + if (this.sgVersion < latestVersion) + { + // Upgrade old incorrect Premultiplied blend into + // equivalent Alpha + Preserve Specular blend mode. + if (this.sgVersion < 1) + { + if (target.blendMode == BlendMode.Premultiply) + { + target.blendMode= BlendMode.Alpha; + blendModePreserveSpecular = true; + } + else + blendModePreserveSpecular = false; + } + ChangeVersion(latestVersion); + } + } + + +#region SubShader + static class SubShaders + { + // SM 4.5, compute with dots instancing + public static SubShaderDescriptor LitSubShader(SGEUniversalTarget target, string renderType, string renderQueue, string disableBatchingTag, bool blendModePreserveSpecular) + { + SubShaderDescriptor result = new SubShaderDescriptor() + { + pipelineTag = UniversalTarget.kPipelineTag, + customTags = UniversalTarget.kLitMaterialTypeTag, + renderType = renderType, + renderQueue = renderQueue, + disableBatchingTag = disableBatchingTag, + generatesPreview = true, + passes = new PassCollection() + }; + + result.passes.Add(LitPasses.Forward(target, blendModePreserveSpecular, CorePragmas.Forward, LitKeywords.Forward)); + + result.passes.Add(LitPasses.GBuffer(target, blendModePreserveSpecular)); + + // cull the shadowcaster pass if we know it will never be used + if (target.castShadows) + result.passes.Add(PassVariant(CorePasses.ShadowCaster(target), CorePragmas.Instanced)); + + if (target.zWrite == ZWrite.On) + result.passes.Add(PassVariant(CorePasses.DepthOnly(target), CorePragmas.Instanced)); + + result.passes.Add(PassVariant(LitPasses.DepthNormal(target), CorePragmas.Instanced)); + + result.passes.Add(PassVariant(LitPasses.Meta(target), CorePragmas.Default)); + + // Currently neither of these passes (selection/picking) can be last for the game view for + // UI shaders to render correctly. Verify [1352225] before changing this order. + result.passes.Add(PassVariant(CorePasses.SceneSelection(target), CorePragmas.Default)); + result.passes.Add(PassVariant(CorePasses.ScenePicking(target), CorePragmas.Default)); + result.passes.Add(PassVariant(LitPasses._2D(target), CorePragmas.Default)); + + return result; + } + } +#endregion + +#region Passes + static class LitPasses + { + static void AddReceiveShadowsControlToPass(ref PassDescriptor pass, bool receiveShadows) + { + if (!receiveShadows) + pass.defines.Add(LitKeywords.ReceiveShadowsOff, 1); + } + + static void AddSimpleLitDefinesToPass(ref PassDescriptor pass) + { + pass.defines.Add(CustomLitDefines.CustomLit); + } + + public static PassDescriptor Forward( + SGEUniversalTarget target, + bool blendModePreserveSpecular, + PragmaCollection pragmas, + KeywordCollection keywords) + { + var result = new PassDescriptor() + { + // Definition + displayName = "SGE SimpleLit Forward", + referenceName = "SHADERPASS_FORWARD", + lightMode = "UniversalForward", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentLit, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = LitRequiredFields.Forward, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.UberSwitchedRenderState(target, blendModePreserveSpecular), + pragmas = pragmas ?? CorePragmas.Forward, // NOTE: SM 2.0 only GL + defines = new DefineCollection { CoreDefines.UseFragmentFog }, + keywords = new KeywordCollection { keywords }, + includes = new IncludeCollection { LitIncludes.Forward }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddSimpleLitDefinesToPass(ref result); + CorePasses.AddTargetSurfaceControlsToPass(ref result, target, blendModePreserveSpecular); + CorePasses.AddAlphaToMaskControlToPass(ref result, target); + AddReceiveShadowsControlToPass(ref result, target.receiveShadows); + CorePasses.AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + public static PassDescriptor ForwardOnly( + SGEUniversalTarget target, + BlockFieldDescriptor[] vertexBlocks, + BlockFieldDescriptor[] pixelBlocks, + bool blendModePreserveSpecular, + PragmaCollection pragmas, + KeywordCollection keywords) + { + var result = new PassDescriptor + { + // Definition + displayName = "SGE SimpleLit Forward Only", + referenceName = "SHADERPASS_FORWARDONLY", + lightMode = "UniversalForwardOnly", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = vertexBlocks, + validPixelBlocks = pixelBlocks, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = LitRequiredFields.Forward, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.UberSwitchedRenderState(target, blendModePreserveSpecular), + pragmas = pragmas, + defines = new DefineCollection { CoreDefines.UseFragmentFog }, + keywords = new KeywordCollection { keywords }, + includes = new IncludeCollection { LitIncludes.Forward }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddSimpleLitDefinesToPass(ref result); + CorePasses.AddTargetSurfaceControlsToPass(ref result, target, blendModePreserveSpecular); + CorePasses.AddAlphaToMaskControlToPass(ref result, target); + AddReceiveShadowsControlToPass(ref result, target.receiveShadows); + CorePasses.AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + // Deferred only in SM4.5 + public static PassDescriptor GBuffer(SGEUniversalTarget target, bool blendModePreserveSpecular) + { + var result = new PassDescriptor + { + // Definition + displayName = "SGE SimpleLit GBuffer", + referenceName = "SHADERPASS_GBUFFER", + lightMode = "UniversalGBuffer", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentLit, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = LitRequiredFields.GBuffer, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.UberSwitchedRenderState(target, blendModePreserveSpecular), + pragmas = CorePragmas.GBuffer, + defines = new DefineCollection { CoreDefines.UseFragmentFog }, + keywords = new KeywordCollection { LitKeywords.GBuffer }, + includes = new IncludeCollection { LitIncludes.GBuffer }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddSimpleLitDefinesToPass(ref result); + CorePasses.AddTargetSurfaceControlsToPass(ref result, target, blendModePreserveSpecular); + AddReceiveShadowsControlToPass(ref result, target.receiveShadows); + CorePasses.AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + public static PassDescriptor Meta(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "SGE SimpleLit Meta", + referenceName = "SHADERPASS_META", + lightMode = "Meta", + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentMeta, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = LitRequiredFields.Meta, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.Meta, + pragmas = CorePragmas.Default, + defines = new DefineCollection() { CoreDefines.UseFragmentFog }, + keywords = new KeywordCollection() { CoreKeywordDescriptors.EditorVisualization }, + includes = LitIncludes.Meta, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddSimpleLitDefinesToPass(ref result); + CorePasses.AddAlphaClipControlToPass(ref result, target); + + return result; + } + + public static PassDescriptor _2D(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + referenceName = "SHADERPASS_2D", + lightMode = "Universal2D", + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentColorAlpha, + + // Fields + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.UberSwitchedRenderState(target), + pragmas = CorePragmas.Instanced, + defines = new DefineCollection(), + keywords = new KeywordCollection(), + includes = LitIncludes._2D, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddSimpleLitDefinesToPass(ref result); + CorePasses.AddAlphaClipControlToPass(ref result, target); + + return result; + } + + public static PassDescriptor DepthNormal(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "DepthNormals", + referenceName = "SHADERPASS_DEPTHNORMALS", + lightMode = "DepthNormals", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentDepthNormals, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.DepthNormals, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.DepthNormalsOnly(target), + pragmas = CorePragmas.Instanced, + defines = new DefineCollection(), + keywords = new KeywordCollection(), + includes = new IncludeCollection { CoreIncludes.DepthNormalsOnly }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + CorePasses.AddAlphaClipControlToPass(ref result, target); + CorePasses.AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + + public static PassDescriptor DepthNormalOnly(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "DepthNormalsOnly", + referenceName = "SHADERPASS_DEPTHNORMALSONLY", + lightMode = "DepthNormalsOnly", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentDepthNormals, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.DepthNormals, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.DepthNormalsOnly(target), + pragmas = CorePragmas.Instanced, + defines = new DefineCollection(), + keywords = new KeywordCollection(), + includes = new IncludeCollection { CoreIncludes.DepthNormalsOnly }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + CorePasses.AddAlphaClipControlToPass(ref result, target); + CorePasses.AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + } +#endregion + + +#region PortMasks + static class LitBlockMasks + { + public static readonly BlockFieldDescriptor[] FragmentLit = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalOS, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Specular, + SGEFields.SurfaceDescription.Shininess, + SGEFields.SurfaceDescription.Glossiness, + SGEFields.SurfaceDescription.CustomLightingData1, + SGEFields.SurfaceDescription.CustomLightingData2, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold + }; + + public static readonly BlockFieldDescriptor[] FragmentMeta = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + }; + } +#endregion + +#region RequiredFields + static class LitRequiredFields + { + public static readonly FieldCollection Forward = new FieldCollection() + { + StructFields.Attributes.uv1, // needed for meta vertex position + StructFields.Attributes.uv2, + StructFields.Varyings.positionWS, + StructFields.Varyings.normalWS, + StructFields.Varyings.tangentWS, // needed for vertex lighting + UniversalStructFields.Varyings.staticLightmapUV, + UniversalStructFields.Varyings.dynamicLightmapUV, + UniversalStructFields.Varyings.sh, + UniversalStructFields.Varyings.fogFactorAndVertexLight, // fog and vertex lighting, vert input is dependency + UniversalStructFields.Varyings.shadowCoord, // shadow coord, vert input is dependency + }; + + public static readonly FieldCollection GBuffer = new FieldCollection() + { + StructFields.Attributes.uv1, // needed for meta vertex position + StructFields.Attributes.uv2, + StructFields.Varyings.positionWS, + StructFields.Varyings.normalWS, + StructFields.Varyings.tangentWS, // needed for vertex lighting + UniversalStructFields.Varyings.staticLightmapUV, + UniversalStructFields.Varyings.dynamicLightmapUV, + UniversalStructFields.Varyings.sh, + UniversalStructFields.Varyings.fogFactorAndVertexLight, // fog and vertex lighting, vert input is dependency + UniversalStructFields.Varyings.shadowCoord, // shadow coord, vert input is dependency + }; + + public static readonly FieldCollection Meta = new FieldCollection() + { + StructFields.Attributes.positionOS, + StructFields.Attributes.normalOS, + StructFields.Attributes.uv0, // + StructFields.Attributes.uv1, // needed for meta vertex position + StructFields.Attributes.uv2, // needed for meta UVs + StructFields.Attributes.instanceID, // needed for rendering instanced terrain + StructFields.Varyings.positionCS, + StructFields.Varyings.texCoord0, // needed for meta UVs + StructFields.Varyings.texCoord1, // VizUV + StructFields.Varyings.texCoord2, // LightCoord + }; + } +#endregion + +#region Defines +static class CustomLitDefines +{ + public static readonly KeywordDescriptor SpecularColor = new KeywordDescriptor() + { + displayName = "Specular Color", + referenceName = "_SPECULAR_COLOR 1", + type = KeywordType.Boolean, + definition = KeywordDefinition.ShaderFeature, + scope = KeywordScope.Local, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly DefineCollection CustomLit = new DefineCollection() + { + {SpecularColor, 1}, + }; +} +#endregion + +#region Keywords + static class LitKeywords + { + public static readonly KeywordDescriptor ReceiveShadowsOff = new KeywordDescriptor() + { + displayName = "Receive Shadows Off", + referenceName = ShaderKeywordStrings._RECEIVE_SHADOWS_OFF, + type = KeywordType.Boolean, + definition = KeywordDefinition.ShaderFeature, + scope = KeywordScope.Local, + }; + + public static readonly KeywordCollection Forward = new KeywordCollection + { + { CoreKeywordDescriptors.ScreenSpaceAmbientOcclusion }, + { CoreKeywordDescriptors.StaticLightmap }, + { CoreKeywordDescriptors.DynamicLightmap }, + { CoreKeywordDescriptors.DirectionalLightmapCombined }, + { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.AdditionalLights }, + { CoreKeywordDescriptors.AdditionalLightShadows }, + { CoreKeywordDescriptors.ReflectionProbeBlending }, + { CoreKeywordDescriptors.ReflectionProbeBoxProjection }, + { CoreKeywordDescriptors.ShadowsSoft }, + { CoreKeywordDescriptors.LightmapShadowMixing }, + { CoreKeywordDescriptors.ShadowsShadowmask }, + { CoreKeywordDescriptors.DBuffer }, + { CoreKeywordDescriptors.LightLayers }, + { CoreKeywordDescriptors.DebugDisplay }, + { CoreKeywordDescriptors.LightCookies }, + { CoreKeywordDescriptors.ForwardPlus }, + }; + + public static readonly KeywordCollection GBuffer = new KeywordCollection + { + { CoreKeywordDescriptors.StaticLightmap }, + { CoreKeywordDescriptors.DynamicLightmap }, + { CoreKeywordDescriptors.DirectionalLightmapCombined }, + { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.ReflectionProbeBlending }, + { CoreKeywordDescriptors.ReflectionProbeBoxProjection }, + { CoreKeywordDescriptors.ShadowsSoft }, + { CoreKeywordDescriptors.LightmapShadowMixing }, + { CoreKeywordDescriptors.ShadowsShadowmask }, + { CoreKeywordDescriptors.MixedLightingSubtractive }, + { CoreKeywordDescriptors.DBuffer }, + { CoreKeywordDescriptors.GBufferNormalsOct }, + { CoreKeywordDescriptors.RenderPassEnabled }, + { CoreKeywordDescriptors.DebugDisplay }, + }; + } +#endregion + +#region Includes + static class LitIncludes + { + const string kShadows = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl"; + const string kMetaInput = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/MetaInput.hlsl"; + const string kForwardPass = "Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitForwardPass.hlsl"; + const string kCustomLitInternal = "Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SGE_CustomLightingInternalFull.hlsl"; + const string kGBuffer = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/UnityGBuffer.hlsl"; + const string kPBRGBufferPass = "Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/CustomLitGBufferPass.hlsl"; + const string kLightingMetaPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl"; + const string k2DPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBR2DPass.hlsl"; + + public static readonly IncludeCollection Forward = new IncludeCollection + { + // Pre-graph + { CoreIncludes.DOTSPregraph }, + { CoreIncludes.WriteRenderLayersPregraph }, + { CoreIncludes.ProbeVolumePregraph }, + { CoreIncludes.CorePregraph }, + { kCustomLitInternal, IncludeLocation.Pregraph }, + { kShadows, IncludeLocation.Pregraph }, + { CoreIncludes.ShaderGraphPregraph }, + { CoreIncludes.DBufferPregraph }, + + // Post-graph + { CoreIncludes.CorePostgraph }, + { kForwardPass, IncludeLocation.Postgraph }, + }; + + public static readonly IncludeCollection GBuffer = new IncludeCollection + { + // Pre-graph + { CoreIncludes.DOTSPregraph }, + { CoreIncludes.WriteRenderLayersPregraph }, + { CoreIncludes.ProbeVolumePregraph }, + { CoreIncludes.CorePregraph }, + { kShadows, IncludeLocation.Pregraph }, + { kCustomLitInternal, IncludeLocation.Pregraph }, + { CoreIncludes.ShaderGraphPregraph }, + { CoreIncludes.DBufferPregraph }, + + // Post-graph + { CoreIncludes.CorePostgraph }, + { kGBuffer, IncludeLocation.Postgraph }, + { kPBRGBufferPass, IncludeLocation.Postgraph }, + }; + + public static readonly IncludeCollection Meta = new IncludeCollection + { + // Pre-graph + { CoreIncludes.CorePregraph }, + { CoreIncludes.ShaderGraphPregraph }, + { kCustomLitInternal, IncludeLocation.Pregraph }, + { kMetaInput, IncludeLocation.Pregraph }, + + // Post-graph + { CoreIncludes.CorePostgraph }, + { kLightingMetaPass, IncludeLocation.Postgraph }, + }; + + public static readonly IncludeCollection _2D = new IncludeCollection + { + // Pre-graph + { CoreIncludes.CorePregraph }, + { kCustomLitInternal, IncludeLocation.Pregraph }, + { CoreIncludes.ShaderGraphPregraph }, + + // Post-graph + { CoreIncludes.CorePostgraph }, + { k2DPass, IncludeLocation.Postgraph }, + }; + + public static readonly IncludeCollection DepthNormalsOnly = new IncludeCollection + { + // Pre-graph + { CoreIncludes.CorePregraph }, + { kCustomLitInternal, IncludeLocation.Pregraph }, + { CoreIncludes.ShaderGraphPregraph }, + + // Post-graph + { CoreIncludes.CorePostgraph }, + { CoreIncludes.kDepthNormalsOnlyPass, IncludeLocation.Postgraph }, + }; + } +#endregion + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalCustomLitSubTarget.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalCustomLitSubTarget.cs.meta new file mode 100644 index 0000000..04249b3 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalCustomLitSubTarget.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1586b3525f0fc80429dc737b7f7c754c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSimpleLitSubTarget.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSimpleLitSubTarget.cs new file mode 100644 index 0000000..d8b4aa5 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSimpleLitSubTarget.cs @@ -0,0 +1,821 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using System.Collections.Generic; +using System.Linq; +using ShaderGraphEssentials.Legacy; +using UnityEditor; +using UnityEditor.Rendering.Universal.ShaderGraph; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.ShaderGraph.Serialization; + +using UnityEngine; +using UnityEngine.Assertions; +using UnityEngine.Rendering.Universal; +using UnityEngine.UIElements; +using static ShaderGraphEssentials.SGESubShaderUtils; +using static ShaderGraphEssentials.SGEShaderUtils; + +namespace ShaderGraphEssentials +{ + sealed class SGEUniversalSimpleLitSubTarget : SGEUniversalSubTarget, ILegacyTarget + { + static readonly GUID kSourceCodeGuid = new GUID("b2ef7193bf665d442a86af14307c3fbf"); // SGEUniversalSimpleLitSubTarget.cs + + public override int latestVersion => 2; + + [SerializeField] + private NormalDropOffSpace m_NormalDropOffSpace = NormalDropOffSpace.Tangent; + + [SerializeField] + bool m_BlendModePreserveSpecular = true; + + public SGEUniversalSimpleLitSubTarget() + { + displayName = "SGE SimpleLit"; + } + + protected override SGEShaderID shaderID => SGEShaderID.SGE_SimpleLit; + + public NormalDropOffSpace normalDropOffSpace + { + get => m_NormalDropOffSpace; + set => m_NormalDropOffSpace = value; + } + + public bool blendModePreserveSpecular + { + get => m_BlendModePreserveSpecular; + set => m_BlendModePreserveSpecular = value; + } + + public override bool IsActive() => true; + + public override void Setup(ref TargetSetupContext context) + { + context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency); + + base.Setup(ref context); + + // Process SubShaders + context.AddSubShader(PostProcessSubShader(SubShaders.LitSubShader(target, target.renderType.ToString(), target.renderQueue.ToString(), target.disableBatching.ToString(), blendModePreserveSpecular))); + } + + public override void ProcessPreviewMaterial(Material material) + { + /*if (target.allowMaterialOverride) + { + // copy our target's default settings into the material + // (technically not necessary since we are always recreating the material from the shader each time, + // which will pull over the defaults from the shader definition) + // but if that ever changes, this will ensure the defaults are set + material.SetFloat(Property.SpecularWorkflowMode, (float)workflowMode); + material.SetFloat(Property.CastShadows, target.castShadows ? 1.0f : 0.0f); + material.SetFloat(Property.ReceiveShadows, target.receiveShadows ? 1.0f : 0.0f); + material.SetFloat(Property.SurfaceType, (float)target.surfaceType); + material.SetFloat(Property.BlendMode, (float)target.alphaMode); + material.SetFloat(Property.AlphaClip, target.alphaClip ? 1.0f : 0.0f); + material.SetFloat(Property.CullMode, (int)target.renderFace); + material.SetFloat(Property.ZWriteControl, (float)target.zWriteControl); + material.SetFloat(Property.ZTest, (float)target.zTestMode); + }*/ + + // call the full unlit material setup function + //ShaderGraphLitGUI.UpdateMaterial(material, Unity.Rendering.Universal.ShaderUtils.MaterialUpdateType.CreatedNewMaterial); + } + + public override void GetFields(ref TargetFieldContext context) + { + base.GetFields(ref context); + + var descs = context.blocks.Select(x => x.descriptor); + + // Lit + context.AddField(UniversalFields.NormalDropOffOS, normalDropOffSpace == NormalDropOffSpace.Object); + context.AddField(UniversalFields.NormalDropOffTS, normalDropOffSpace == NormalDropOffSpace.Tangent); + context.AddField(UniversalFields.NormalDropOffWS, normalDropOffSpace == NormalDropOffSpace.World); + context.AddField(UniversalFields.Normal, descs.Contains(BlockFields.SurfaceDescription.NormalOS) || + descs.Contains(BlockFields.SurfaceDescription.NormalTS) || + descs.Contains(BlockFields.SurfaceDescription.NormalWS)); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + context.AddBlock(BlockFields.SurfaceDescription.Smoothness); + context.AddBlock(BlockFields.SurfaceDescription.NormalOS, normalDropOffSpace == NormalDropOffSpace.Object); + context.AddBlock(BlockFields.SurfaceDescription.NormalTS, normalDropOffSpace == NormalDropOffSpace.Tangent); + context.AddBlock(BlockFields.SurfaceDescription.NormalWS, normalDropOffSpace == NormalDropOffSpace.World); + context.AddBlock(BlockFields.SurfaceDescription.Emission); + context.AddBlock(BlockFields.SurfaceDescription.Specular); + } + + public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) + { + // if using material control, add the material property to control workflow mode + /*if (target.allowMaterialOverride) + { + collector.AddFloatProperty(Property.SpecularWorkflowMode, (float)workflowMode); + collector.AddFloatProperty(Property.CastShadows, target.castShadows ? 1.0f : 0.0f); + collector.AddFloatProperty(Property.ReceiveShadows, target.receiveShadows ? 1.0f : 0.0f); + + // setup properties using the defaults + collector.AddFloatProperty(Property.SurfaceType, (float)target.surfaceType); + collector.AddFloatProperty(Property.BlendMode, (float)target.alphaMode); + collector.AddFloatProperty(Property.AlphaClip, target.alphaClip ? 1.0f : 0.0f); + collector.AddFloatProperty(Property.SrcBlend, 1.0f); // always set by material inspector, ok to have incorrect values here + collector.AddFloatProperty(Property.DstBlend, 0.0f); // always set by material inspector, ok to have incorrect values here + collector.AddToggleProperty(Property.ZWrite, (target.surfaceType == SurfaceType.Opaque)); + collector.AddFloatProperty(Property.ZWriteControl, (float)target.zWriteControl); + collector.AddFloatProperty(Property.ZTest, (float)target.zTestMode); // ztest mode is designed to directly pass as ztest + collector.AddFloatProperty(Property.CullMode, (float)target.renderFace); // render face enum is designed to directly pass as a cull mode + + bool enableAlphaToMask = (target.alphaClip && (target.surfaceType == SurfaceType.Opaque)); + collector.AddFloatProperty(Property.AlphaToMask, enableAlphaToMask ? 1.0f : 0.0f); + }*/ + } + + public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) + { + context.AddProperty("Fragment Normal Space", new UnityEngine.UIElements.EnumField(NormalDropOffSpace.Tangent) { value = normalDropOffSpace }, (evt) => + { + if (Equals(normalDropOffSpace, evt.newValue)) + return; + + registerUndo("Change Fragment Normal Space"); + normalDropOffSpace = (NormalDropOffSpace)evt.newValue; + onChange(); + }); + + if (target.blendMode != BlendMode.Off) + { + if (target.blendMode == BlendMode.Alpha || target.blendMode == BlendMode.Additive) + context.AddProperty("Preserve Specular Lighting", new Toggle() { value = blendModePreserveSpecular }, (evt) => + { + if (Equals(blendModePreserveSpecular, evt.newValue)) + return; + + registerUndo("Change Preserve Specular"); + blendModePreserveSpecular = evt.newValue; + onChange(); + }); + } + } + + protected override int ComputeMaterialNeedsUpdateHash() + { + int hash = base.ComputeMaterialNeedsUpdateHash(); + hash = hash * 23 /*+ target.allowMaterialOverride.GetHashCode()*/; + return hash; + } + + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + if(!(masterNode is SGESimpleLitMasterNode1 sgeSimpleLitMasterNode)) + return false; + + m_NormalDropOffSpace = sgeSimpleLitMasterNode.m_NormalDropOffSpace; + + // Handle mapping of Normal block specifically + BlockFieldDescriptor normalBlock; + switch(m_NormalDropOffSpace) + { + case NormalDropOffSpace.Object: + normalBlock = BlockFields.SurfaceDescription.NormalOS; + break; + case NormalDropOffSpace.World: + normalBlock = BlockFields.SurfaceDescription.NormalWS; + break; + default: + normalBlock = BlockFields.SurfaceDescription.NormalTS; + break; + } + + // Set blockmap + blockMap = new Dictionary() + { + { BlockFields.VertexDescription.Position, 8 }, + { BlockFields.VertexDescription.Normal, 9 }, + { BlockFields.VertexDescription.Tangent, 10 }, + { BlockFields.SurfaceDescription.BaseColor, 0 }, + { normalBlock, 4 }, + { BlockFields.SurfaceDescription.Emission, 5 }, + { BlockFields.SurfaceDescription.Smoothness, 2 }, + { BlockFields.SurfaceDescription.Specular, 1 }, + { BlockFields.SurfaceDescription.Alpha, 6 }, + { BlockFields.SurfaceDescription.AlphaClipThreshold, 7 }, + }; + + return true; + } + + internal override void OnAfterParentTargetDeserialized() + { + Assert.IsNotNull(target); + + if (this.sgVersion < latestVersion) + { + // Upgrade old incorrect Premultiplied blend into + // equivalent Alpha + Preserve Specular blend mode. + if (this.sgVersion < 1) + { + if (target.blendMode == BlendMode.Premultiply) + { + target.blendMode = BlendMode.Alpha; + blendModePreserveSpecular = true; + } + else + blendModePreserveSpecular = false; + } + ChangeVersion(latestVersion); + } + } + + +#region SubShader + static class SubShaders + { + // SM 4.5, compute with dots instancing + public static SubShaderDescriptor LitSubShader(SGEUniversalTarget target, string renderType, string renderQueue, string disableBatchingTag, bool blendModePreserveSpecular) + { + SubShaderDescriptor result = new SubShaderDescriptor() + { + pipelineTag = UniversalTarget.kPipelineTag, + customTags = UniversalTarget.kLitMaterialTypeTag, + renderType = renderType, + renderQueue = renderQueue, + disableBatchingTag = disableBatchingTag, + generatesPreview = true, + passes = new PassCollection() + }; + + result.passes.Add(LitPasses.Forward(target, blendModePreserveSpecular, CorePragmas.Forward, LitKeywords.Forward)); + + result.passes.Add(LitPasses.GBuffer(target, blendModePreserveSpecular)); + + // cull the shadowcaster pass if we know it will never be used + if (target.castShadows) + result.passes.Add(PassVariant(CorePasses.ShadowCaster(target), CorePragmas.Instanced)); + + if (target.zWrite == ZWrite.On) + result.passes.Add(PassVariant(CorePasses.DepthOnly(target), CorePragmas.Instanced)); + + result.passes.Add(PassVariant(LitPasses.DepthNormal(target), CorePragmas.Instanced)); + result.passes.Add(PassVariant(LitPasses.Meta(target), CorePragmas.Default)); + + // Currently neither of these passes (selection/picking) can be last for the game view for + // UI shaders to render correctly. Verify [1352225] before changing this order. + result.passes.Add(PassVariant(CorePasses.SceneSelection(target), CorePragmas.Default)); + result.passes.Add(PassVariant(CorePasses.ScenePicking(target), CorePragmas.Default)); + result.passes.Add(PassVariant(LitPasses._2D(target), CorePragmas.Default)); + + return result; + } + } +#endregion + +#region Passes + static class LitPasses + { + static void AddReceiveShadowsControlToPass(ref PassDescriptor pass, bool receiveShadows) + { + if (!receiveShadows) + pass.defines.Add(LitKeywords.ReceiveShadowsOff, 1); + } + + static void AddSimpleLitDefinesToPass(ref PassDescriptor pass) + { + pass.defines.Add(SimpleLitDefines.SimpleLit); + } + + public static PassDescriptor Forward( + SGEUniversalTarget target, + bool blendModePreserveSpecular, + PragmaCollection pragmas, + KeywordCollection keywords) + { + var result = new PassDescriptor() + { + // Definition + displayName = "SGE SimpleLit Forward", + referenceName = "SHADERPASS_FORWARD", + lightMode = "UniversalForward", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentLit, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = LitRequiredFields.Forward, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.UberSwitchedRenderState(target, blendModePreserveSpecular), + pragmas = pragmas ?? CorePragmas.Forward, // NOTE: SM 2.0 only GL + defines = new DefineCollection { CoreDefines.UseFragmentFog }, + keywords = new KeywordCollection { keywords }, + includes = new IncludeCollection { LitIncludes.Forward }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddSimpleLitDefinesToPass(ref result); + CorePasses.AddTargetSurfaceControlsToPass(ref result, target, blendModePreserveSpecular); + CorePasses.AddAlphaToMaskControlToPass(ref result, target); + AddReceiveShadowsControlToPass(ref result, target.receiveShadows); + CorePasses.AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + public static PassDescriptor ForwardOnly( + SGEUniversalTarget target, + bool blendModePreserveSpecular, + BlockFieldDescriptor[] vertexBlocks, + BlockFieldDescriptor[] pixelBlocks, + PragmaCollection pragmas, + KeywordCollection keywords) + { + var result = new PassDescriptor + { + // Definition + displayName = "SGE SimpleLit Forward Only", + referenceName = "SHADERPASS_FORWARDONLY", + lightMode = "UniversalForwardOnly", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = vertexBlocks, + validPixelBlocks = pixelBlocks, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = LitRequiredFields.Forward, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.UberSwitchedRenderState(target, blendModePreserveSpecular), + pragmas = pragmas, + defines = new DefineCollection { CoreDefines.UseFragmentFog }, + keywords = new KeywordCollection { keywords }, + includes = new IncludeCollection { LitIncludes.Forward }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddSimpleLitDefinesToPass(ref result); + CorePasses.AddTargetSurfaceControlsToPass(ref result, target, blendModePreserveSpecular); + CorePasses.AddAlphaToMaskControlToPass(ref result, target); + AddReceiveShadowsControlToPass(ref result, target.receiveShadows); + CorePasses.AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + // Deferred only in SM4.5 + public static PassDescriptor GBuffer(SGEUniversalTarget target, bool blendModePreserveSpecular) + { + var result = new PassDescriptor + { + // Definition + displayName = "SGE SimpleLit GBuffer", + referenceName = "SHADERPASS_GBUFFER", + lightMode = "UniversalGBuffer", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentLit, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = LitRequiredFields.GBuffer, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.UberSwitchedRenderState(target, blendModePreserveSpecular), + pragmas = CorePragmas.GBuffer, + defines = new DefineCollection { CoreDefines.UseFragmentFog }, + keywords = new KeywordCollection { LitKeywords.GBuffer }, + includes = new IncludeCollection { LitIncludes.GBuffer }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddSimpleLitDefinesToPass(ref result); + CorePasses.AddTargetSurfaceControlsToPass(ref result, target, blendModePreserveSpecular); + AddReceiveShadowsControlToPass(ref result, target.receiveShadows); + CorePasses.AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + public static PassDescriptor Meta(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "SGE SimpleLit Meta", + referenceName = "SHADERPASS_META", + lightMode = "Meta", + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = LitBlockMasks.FragmentMeta, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = LitRequiredFields.Meta, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.Meta, + pragmas = CorePragmas.Default, + defines = new DefineCollection() { CoreDefines.UseFragmentFog }, + keywords = new KeywordCollection() { CoreKeywordDescriptors.EditorVisualization }, + includes = LitIncludes.Meta, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddSimpleLitDefinesToPass(ref result); + CorePasses.AddAlphaClipControlToPass(ref result, target); + + return result; + } + + public static PassDescriptor _2D(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + referenceName = "SHADERPASS_2D", + lightMode = "Universal2D", + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentColorAlpha, + + // Fields + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.UberSwitchedRenderState(target), + pragmas = CorePragmas.Instanced, + defines = new DefineCollection(), + keywords = new KeywordCollection(), + includes = LitIncludes._2D, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddSimpleLitDefinesToPass(ref result); + CorePasses.AddAlphaClipControlToPass(ref result, target); + + return result; + } + + public static PassDescriptor DepthNormal(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "DepthNormals", + referenceName = "SHADERPASS_DEPTHNORMALS", + lightMode = "DepthNormals", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentDepthNormals, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.DepthNormals, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.DepthNormalsOnly(target), + pragmas = CorePragmas.Instanced, + defines = new DefineCollection(), + keywords = new KeywordCollection(), + includes = new IncludeCollection { CoreIncludes.DepthNormalsOnly }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + CorePasses.AddAlphaClipControlToPass(ref result, target); + CorePasses.AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + + public static PassDescriptor DepthNormalOnly(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "DepthNormalsOnly", + referenceName = "SHADERPASS_DEPTHNORMALSONLY", + lightMode = "DepthNormalsOnly", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentDepthNormals, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.DepthNormals, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.DepthNormalsOnly(target), + pragmas = CorePragmas.Instanced, + defines = new DefineCollection(), + keywords = new KeywordCollection(), + includes = new IncludeCollection { CoreIncludes.DepthNormalsOnly }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + CorePasses.AddAlphaClipControlToPass(ref result, target); + CorePasses.AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + } +#endregion + +#region PortMasks + static class LitBlockMasks + { + public static readonly BlockFieldDescriptor[] FragmentLit = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.NormalOS, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Specular, + BlockFields.SurfaceDescription.Smoothness, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + }; + + public static readonly BlockFieldDescriptor[] FragmentMeta = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.Emission, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + }; + } +#endregion + +#region RequiredFields + static class LitRequiredFields + { + public static readonly FieldCollection Forward = new FieldCollection() + { + StructFields.Attributes.uv1, // needed for meta vertex position + StructFields.Attributes.uv2, + StructFields.Varyings.positionWS, + StructFields.Varyings.normalWS, + StructFields.Varyings.tangentWS, // needed for vertex lighting + UniversalStructFields.Varyings.staticLightmapUV, + UniversalStructFields.Varyings.dynamicLightmapUV, + UniversalStructFields.Varyings.sh, + UniversalStructFields.Varyings.fogFactorAndVertexLight, // fog and vertex lighting, vert input is dependency + UniversalStructFields.Varyings.shadowCoord, // shadow coord, vert input is dependency + }; + + public static readonly FieldCollection GBuffer = new FieldCollection() + { + StructFields.Attributes.uv1, // needed for meta vertex position + StructFields.Attributes.uv2, + StructFields.Varyings.positionWS, + StructFields.Varyings.normalWS, + StructFields.Varyings.tangentWS, // needed for vertex lighting + UniversalStructFields.Varyings.staticLightmapUV, + UniversalStructFields.Varyings.dynamicLightmapUV, + UniversalStructFields.Varyings.sh, + UniversalStructFields.Varyings.fogFactorAndVertexLight, // fog and vertex lighting, vert input is dependency + UniversalStructFields.Varyings.shadowCoord, // shadow coord, vert input is dependency + }; + + public static readonly FieldCollection Meta = new FieldCollection() + { + StructFields.Attributes.positionOS, + StructFields.Attributes.normalOS, + StructFields.Attributes.uv0, // + StructFields.Attributes.uv1, // needed for meta vertex position + StructFields.Attributes.uv2, // needed for meta UVs + StructFields.Attributes.instanceID, // needed for rendering instanced terrain + StructFields.Varyings.positionCS, + StructFields.Varyings.texCoord0, // needed for meta UVs + StructFields.Varyings.texCoord1, // VizUV + StructFields.Varyings.texCoord2, // LightCoord + }; + } +#endregion + +#region Defines +static class SimpleLitDefines +{ + public static readonly KeywordDescriptor SpecularColor = new KeywordDescriptor() + { + displayName = "Specular Color", + referenceName = "_SPECULAR_COLOR 1", + type = KeywordType.Boolean, + definition = KeywordDefinition.ShaderFeature, + scope = KeywordScope.Local, + stages = KeywordShaderStage.Fragment + }; + + public static readonly DefineCollection SimpleLit = new DefineCollection() + { + {SpecularColor, 1}, + }; +} +#endregion + +#region Keywords + static class LitKeywords + { + public static readonly KeywordDescriptor ReceiveShadowsOff = new KeywordDescriptor() + { + displayName = "Receive Shadows Off", + referenceName = ShaderKeywordStrings._RECEIVE_SHADOWS_OFF, + type = KeywordType.Boolean, + definition = KeywordDefinition.ShaderFeature, + scope = KeywordScope.Local, + }; + + public static readonly KeywordCollection Forward = new KeywordCollection + { + { CoreKeywordDescriptors.ScreenSpaceAmbientOcclusion }, + { CoreKeywordDescriptors.StaticLightmap }, + { CoreKeywordDescriptors.DynamicLightmap }, + { CoreKeywordDescriptors.DirectionalLightmapCombined }, + { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.AdditionalLights }, + { CoreKeywordDescriptors.AdditionalLightShadows }, + { CoreKeywordDescriptors.ReflectionProbeBlending }, + { CoreKeywordDescriptors.ReflectionProbeBoxProjection }, + { CoreKeywordDescriptors.ShadowsSoft }, + { CoreKeywordDescriptors.LightmapShadowMixing }, + { CoreKeywordDescriptors.ShadowsShadowmask }, + { CoreKeywordDescriptors.DBuffer }, + { CoreKeywordDescriptors.LightLayers }, + { CoreKeywordDescriptors.DebugDisplay }, + { CoreKeywordDescriptors.LightCookies }, + { CoreKeywordDescriptors.ForwardPlus }, + }; + + public static readonly KeywordCollection GBuffer = new KeywordCollection + { + { CoreKeywordDescriptors.StaticLightmap }, + { CoreKeywordDescriptors.DynamicLightmap }, + { CoreKeywordDescriptors.DirectionalLightmapCombined }, + { CoreKeywordDescriptors.MainLightShadows }, + { CoreKeywordDescriptors.ReflectionProbeBlending }, + { CoreKeywordDescriptors.ReflectionProbeBoxProjection }, + { CoreKeywordDescriptors.ShadowsSoft }, + { CoreKeywordDescriptors.LightmapShadowMixing }, + { CoreKeywordDescriptors.ShadowsShadowmask }, + { CoreKeywordDescriptors.MixedLightingSubtractive }, + { CoreKeywordDescriptors.DBuffer }, + { CoreKeywordDescriptors.GBufferNormalsOct }, + { CoreKeywordDescriptors.RenderPassEnabled }, + { CoreKeywordDescriptors.DebugDisplay }, + }; + } +#endregion + +#region Includes + static class LitIncludes + { + const string kShadows = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl"; + const string kMetaInput = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/MetaInput.hlsl"; + const string kForwardPass = "Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitForwardPass.hlsl"; + const string kGBuffer = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/UnityGBuffer.hlsl"; + const string kPBRGBufferPass = "Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/Shaders/SimpleLitGBufferPass.hlsl"; + const string kLightingMetaPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl"; + const string k2DPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/PBR2DPass.hlsl"; + + public static readonly IncludeCollection Forward = new IncludeCollection + { + // Pre-graph + { CoreIncludes.DOTSPregraph }, + { CoreIncludes.WriteRenderLayersPregraph }, + { CoreIncludes.ProbeVolumePregraph }, + { CoreIncludes.CorePregraph }, + { kShadows, IncludeLocation.Pregraph }, + { CoreIncludes.ShaderGraphPregraph }, + { CoreIncludes.DBufferPregraph }, + + // Post-graph + { CoreIncludes.CorePostgraph }, + { kForwardPass, IncludeLocation.Postgraph }, + }; + + public static readonly IncludeCollection GBuffer = new IncludeCollection + { + // Pre-graph + { CoreIncludes.DOTSPregraph }, + { CoreIncludes.WriteRenderLayersPregraph }, + { CoreIncludes.ProbeVolumePregraph }, + { CoreIncludes.CorePregraph }, + { kShadows, IncludeLocation.Pregraph }, + { CoreIncludes.ShaderGraphPregraph }, + { CoreIncludes.DBufferPregraph }, + + // Post-graph + { CoreIncludes.CorePostgraph }, + { kGBuffer, IncludeLocation.Postgraph }, + { kPBRGBufferPass, IncludeLocation.Postgraph }, + }; + + public static readonly IncludeCollection Meta = new IncludeCollection + { + // Pre-graph + { CoreIncludes.CorePregraph }, + { CoreIncludes.ShaderGraphPregraph }, + { kMetaInput, IncludeLocation.Pregraph }, + + // Post-graph + { CoreIncludes.CorePostgraph }, + { kLightingMetaPass, IncludeLocation.Postgraph }, + }; + + public static readonly IncludeCollection _2D = new IncludeCollection + { + // Pre-graph + { CoreIncludes.CorePregraph }, + { CoreIncludes.ShaderGraphPregraph }, + + // Post-graph + { CoreIncludes.CorePostgraph }, + { k2DPass, IncludeLocation.Postgraph }, + }; + } +#endregion + } +} diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSimpleLitSubTarget.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSimpleLitSubTarget.cs.meta new file mode 100644 index 0000000..b148c52 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSimpleLitSubTarget.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: b2ef7193bf665d442a86af14307c3fbf +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSubTarget.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSubTarget.cs new file mode 100644 index 0000000..dcceade --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSubTarget.cs @@ -0,0 +1,144 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using UnityEngine; +using UnityEditor.ShaderGraph; +using static Unity.Rendering.Universal.ShaderUtils; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor; +using UnityEditor.Rendering.Universal.ShaderGraph; +using UnityEditor.Rendering.Universal; +#if HAS_VFX_GRAPH +using UnityEditor.VFX; +#endif + +namespace ShaderGraphEssentials +{ + abstract class SGEUniversalSubTarget : SubTarget, IHasMetadata +#if HAS_VFX_GRAPH + , IRequireVFXContext +#endif + { + static readonly GUID kSourceCodeGuid = new GUID("41634f6f5f60b204ab48334329540b95"); // SGEUniversalSubTarget.cs + + public override void Setup(ref TargetSetupContext context) + { + context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency); + } + + protected abstract SGEShaderUtils.SGEShaderID shaderID { get; } + +#if HAS_VFX_GRAPH + // VFX Properties + VFXContext m_ContextVFX = null; + VFXTaskCompiledData m_TaskDataVFX; + protected bool TargetsVFX() => m_ContextVFX != null; + + public void ConfigureContextData(VFXContext context, VFXTaskCompiledData data) + { + m_ContextVFX = context; + m_TaskDataVFX = data; + } + +#endif + + protected SubShaderDescriptor PostProcessSubShader(SubShaderDescriptor subShaderDescriptor) + { +#if HAS_VFX_GRAPH + if (TargetsVFX()) + return VFXSubTarget.PostProcessSubShader(subShaderDescriptor, m_ContextVFX, m_TaskDataVFX); +#endif + return subShaderDescriptor; + } + + public override void GetFields(ref TargetFieldContext context) + { +#if HAS_VFX_GRAPH + if (TargetsVFX()) + VFXSubTarget.GetFields(ref context, m_ContextVFX); +#endif + } + + + public virtual string identifier => GetType().Name; + public virtual ScriptableObject GetMetadataObject(GraphDataReadOnly graphData) + { + var urpMetadata = ScriptableObject.CreateInstance(); + urpMetadata.shaderID = ShaderID.Unknown;//shaderID; // TODO: verify where this is used + urpMetadata.castShadows = target.castShadows; + return urpMetadata; + } + + private int lastMaterialNeedsUpdateHash = 0; + protected virtual int ComputeMaterialNeedsUpdateHash() => 0; + + public override object saveContext + { + get + { + int hash = ComputeMaterialNeedsUpdateHash(); + bool needsUpdate = hash != lastMaterialNeedsUpdateHash; + if (needsUpdate) + lastMaterialNeedsUpdateHash = hash; + + return new UniversalShaderGraphSaveContext { updateMaterials = needsUpdate }; + } + } + } + + internal static class SGESubShaderUtils + { + internal static void AddFloatProperty(this PropertyCollector collector, string referenceName, float defaultValue, HLSLDeclaration declarationType = HLSLDeclaration.DoNotDeclare) + { + collector.AddShaderProperty(new Vector1ShaderProperty + { + floatType = FloatType.Default, + hidden = true, + overrideHLSLDeclaration = true, + hlslDeclarationOverride = declarationType, + value = defaultValue, + displayName = referenceName, + overrideReferenceName = referenceName, + }); + } + + internal static void AddToggleProperty(this PropertyCollector collector, string referenceName, bool defaultValue, HLSLDeclaration declarationType = HLSLDeclaration.DoNotDeclare) + { + collector.AddShaderProperty(new BooleanShaderProperty + { + value = defaultValue, + hidden = true, + overrideHLSLDeclaration = true, + hlslDeclarationOverride = declarationType, + displayName = referenceName, + overrideReferenceName = referenceName, + }); + } + + // Overloads to do inline PassDescriptor modifications + // NOTE: param order should match PassDescriptor field order for consistency + #region PassVariant + internal static PassDescriptor PassVariant(in PassDescriptor source, PragmaCollection pragmas) + { + var result = source; + result.pragmas = pragmas; + return result; + } + + #endregion + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSubTarget.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSubTarget.cs.meta new file mode 100644 index 0000000..6d106d1 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalSubTarget.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 41634f6f5f60b204ab48334329540b95 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalTarget.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalTarget.cs new file mode 100644 index 0000000..abf3722 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalTarget.cs @@ -0,0 +1,1849 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using System.Collections.Generic; +using System.Linq; +using ShaderGraphEssentials.Legacy; +using UnityEditor; +using UnityEditor.Rendering.Universal; +using UnityEditor.Rendering.Universal.ShaderGraph; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.ShaderGraph.Serialization; +using UnityEditor.UIElements; +using UnityEngine; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; +using UnityEngine.UIElements; +using CullMode = UnityEngine.Rendering.CullMode; +using RenderQueue = UnityEditor.ShaderGraph.RenderQueue; +#if HAS_VFX_GRAPH +using UnityEditor.VFX; +#endif + +namespace ShaderGraphEssentials +{ + enum BlendMode + { + Off = 0, + Alpha = 1, + Premultiply = 2, + Additive = 3, + Multiply = 4 + } + + sealed class SGEUniversalTarget : Target, IHasMetadata, ILegacyTarget +#if HAS_VFX_GRAPH + , IMaySupportVFX, IRequireVFXContext +#endif + { + public override int latestVersion => 1; + + // Constants + static readonly GUID kSourceCodeGuid = new GUID("f9a02d7a49622a44bb0e1e7f11ade6bd"); // SGEUniversalTarget.cs + public const string kPipelineTag = "UniversalPipeline"; + + // SubTarget + List m_SubTargets; + List m_SubTargetNames; + int activeSubTargetIndex => m_SubTargets.IndexOf(m_ActiveSubTarget); + + // View + PopupField m_SubTargetField; + TextField m_CustomGUIField; +#if HAS_VFX_GRAPH + Toggle m_SupportVFXToggle; +#endif + + [SerializeField] + JsonData m_ActiveSubTarget; + + [SerializeField] + private RenderType m_RenderType = RenderType.Opaque; + + [SerializeField] + private RenderQueue m_RenderQueue = RenderQueue.Geometry; + + [SerializeField] + private BlendMode m_BlendMode = BlendMode.Off; + + [SerializeField] + private bool m_AlphaClip = false; + + [SerializeField] + bool m_CastShadows = true; + + [SerializeField] + bool m_ReceiveShadows = true; + + [SerializeField] + bool m_SupportsLODCrossFade = false; + + [SerializeField] + private CullMode m_CullMode = CullMode.Back; + + [SerializeField] + private ZWrite m_ZWrite = ZWrite.On; + + [SerializeField] + private ZTest m_ZTest = ZTest.Less; + + [SerializeField] + string m_CustomEditorGUI; + + [SerializeField] + bool m_SupportVFX; + + internal override bool ignoreCustomInterpolators => false; + internal override int padCustomInterpolatorLimit => 4; + + public SGEUniversalTarget() + { + displayName = "SGE Universal"; + m_SubTargets = TargetUtils.GetSubTargets(this); + m_SubTargetNames = m_SubTargets.Select(x => x.displayName).ToList(); + TargetUtils.ProcessSubTargetList(ref m_ActiveSubTarget, ref m_SubTargets); + } + + public string disableBatching + { + get + { + if (supportsLodCrossFade) + return $"{UnityEditor.ShaderGraph.DisableBatching.LODFading}"; + else + return $"{UnityEditor.ShaderGraph.DisableBatching.False}"; + } + } + + + public SubTarget activeSubTarget + { + get => m_ActiveSubTarget; + set => m_ActiveSubTarget = value; + } + + public RenderType renderType + { + get => m_RenderType; + set => m_RenderType = value; + } + + public RenderQueue renderQueue + { + get => m_RenderQueue; + set => m_RenderQueue = value; + } + + public BlendMode blendMode + { + get => m_BlendMode; + set => m_BlendMode = value; + } + + public bool alphaClip + { + get => m_AlphaClip; + set => m_AlphaClip = value; + } + + public bool castShadows + { + get => m_CastShadows; + set => m_CastShadows = value; + } + + public bool receiveShadows + { + get => m_ReceiveShadows; + set => m_ReceiveShadows = value; + } + + public bool supportsLodCrossFade + { + get => m_SupportsLODCrossFade; + set => m_SupportsLODCrossFade = value; + } + + public CullMode cullMode + { + get => m_CullMode; + set => m_CullMode = value; + } + + public ZWrite zWrite + { + get => m_ZWrite; + set => m_ZWrite = value; + } + + public ZTest zTest + { + get => m_ZTest; + set => m_ZTest = value; + } + + public string customEditorGUI + { + get => m_CustomEditorGUI; + set => m_CustomEditorGUI = value; + } + + public override bool IsActive() + { + bool isUniversalRenderPipeline = GraphicsSettings.currentRenderPipeline is UniversalRenderPipelineAsset; + return isUniversalRenderPipeline && activeSubTarget.IsActive(); + } + + public override bool IsNodeAllowedByTarget(Type nodeType) + { + SRPFilterAttribute srpFilter = NodeClassCache.GetAttributeOnNodeType(nodeType); + bool worksWithThisSrp = srpFilter == null || srpFilter.srpTypes.Contains(typeof(UniversalRenderPipeline)); + + SubTargetFilterAttribute subTargetFilter = NodeClassCache.GetAttributeOnNodeType(nodeType); + bool worksWithThisSubTarget = subTargetFilter == null || subTargetFilter.subTargetTypes.Contains(activeSubTarget.GetType()); + + return worksWithThisSrp && worksWithThisSubTarget && base.IsNodeAllowedByTarget(nodeType); + } + + public override void Setup(ref TargetSetupContext context) + { + // Setup the Target + context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency); + + // Override EditorGUI + if(!string.IsNullOrEmpty(m_CustomEditorGUI)) + { + context.SetDefaultShaderGUI(m_CustomEditorGUI); + } + + // Setup the active SubTarget + TargetUtils.ProcessSubTargetList(ref m_ActiveSubTarget, ref m_SubTargets); + m_ActiveSubTarget.value.target = this; + m_ActiveSubTarget.value.Setup(ref context); + } + + public override void OnAfterMultiDeserialize(string json) + { + TargetUtils.ProcessSubTargetList(ref m_ActiveSubTarget, ref m_SubTargets); + m_ActiveSubTarget.value.target = this; + + // OnAfterMultiDeserialize order is not guaranteed to be hierarchical (target->subtarget). + // Update active subTarget (only, since the target is shared and non-active subTargets could override active settings) + // after Target has been deserialized and target <-> subtarget references are intact. + m_ActiveSubTarget.value.OnAfterParentTargetDeserialized(); + } + + public override void GetFields(ref TargetFieldContext context) + { + var descs = context.blocks.Select(x => x.descriptor); + // Core fields + context.AddField(Fields.GraphVertex, descs.Contains(BlockFields.VertexDescription.Position) || + descs.Contains(BlockFields.VertexDescription.Normal) || + descs.Contains(BlockFields.VertexDescription.Tangent)); + context.AddField(Fields.GraphPixel); + + context.AddField(SGEFields.BlendModeOff, blendMode == BlendMode.Off); + context.AddField(SGEFields.BlendModeAdditive, blendMode == BlendMode.Additive); + context.AddField(SGEFields.BlendModeAlpha, blendMode == BlendMode.Alpha); + context.AddField(SGEFields.BlendModeMultiply, blendMode == BlendMode.Multiply); + context.AddField(SGEFields.BlendModePremultiply, blendMode == BlendMode.Premultiply); + + context.AddField(SGEFields.AlphaClip, alphaClip); + + context.AddField(SGEFields.CullModeOff, cullMode == CullMode.Off); + context.AddField(SGEFields.CullModeFront, cullMode == CullMode.Front); + context.AddField(SGEFields.CullModeBack, cullMode == CullMode.Back); + + context.AddField(SGEFields.ZWrite, zWrite == ZWrite.On); + + context.AddField(SGEFields.ZTestLess, zTest == ZTest.Less); + context.AddField(SGEFields.ZTestGreater, zTest == ZTest.Greater); + context.AddField(SGEFields.ZTestLEqual, zTest == ZTest.LEqual); + context.AddField(SGEFields.ZTestGEqual, zTest == ZTest.GEqual); + context.AddField(SGEFields.ZTestEqual, zTest == ZTest.Equal); + context.AddField(SGEFields.ZTestNotEqual, zTest == ZTest.NotEqual); + context.AddField(SGEFields.ZTestAlways, zTest == ZTest.Always); + + bool opaque = blendMode == BlendMode.Off; + context.AddField(UniversalFields.SurfaceOpaque, opaque); + context.AddField(UniversalFields.SurfaceTransparent, !opaque); + + // SubTarget fields + m_ActiveSubTarget.value.GetFields(ref context); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + // Core blocks + context.AddBlock(BlockFields.VertexDescription.Position); + context.AddBlock(BlockFields.VertexDescription.Normal); + context.AddBlock(BlockFields.VertexDescription.Tangent); + context.AddBlock(BlockFields.SurfaceDescription.BaseColor); + context.AddBlock(BlockFields.SurfaceDescription.Alpha, alphaClip || blendMode != BlendMode.Off); + context.AddBlock(BlockFields.SurfaceDescription.AlphaClipThreshold, alphaClip); + + // SubTarget blocks + m_ActiveSubTarget.value.GetActiveBlocks(ref context); + } + + public override void ProcessPreviewMaterial(Material material) + { + m_ActiveSubTarget.value.ProcessPreviewMaterial(material); + } + + public override object saveContext => m_ActiveSubTarget.value?.saveContext; + + public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) + { + base.CollectShaderProperties(collector, generationMode); + activeSubTarget.CollectShaderProperties(collector, generationMode); + + collector.AddShaderProperty(LightmappingShaderProperties.kLightmapsArray); + collector.AddShaderProperty(LightmappingShaderProperties.kLightmapsIndirectionArray); + collector.AddShaderProperty(LightmappingShaderProperties.kShadowMasksArray); + + // SubTarget blocks + m_ActiveSubTarget.value.CollectShaderProperties(collector, generationMode); + } + + public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) + { + // Core properties + m_SubTargetField = new PopupField(m_SubTargetNames, activeSubTargetIndex); + context.AddProperty("Material", m_SubTargetField, (evt) => + { + if (Equals(activeSubTargetIndex, m_SubTargetField.index)) + return; + + registerUndo("Change Material"); + m_ActiveSubTarget = m_SubTargets[m_SubTargetField.index]; + onChange(); + }); + + context.AddProperty("Render Type", new EnumField(RenderType.Opaque) { value = renderType }, (evt) => + { + if (Equals(renderType, evt.newValue)) + return; + + registerUndo("Change Render Type"); + renderType = (RenderType) evt.newValue; + onChange(); + }); + + context.AddProperty("Render Queue", new EnumField(RenderQueue.Background) { value = renderQueue }, (evt) => + { + if (Equals(renderQueue, evt.newValue)) + return; + + registerUndo("Change Render Queue"); + renderQueue = (RenderQueue) evt.newValue; + onChange(); + }); + + context.AddProperty("Blend", new EnumField(BlendMode.Off) { value = blendMode }, (evt) => + { + if (Equals(blendMode, evt.newValue)) + return; + + registerUndo("Change Blend"); + blendMode = (BlendMode) evt.newValue; + onChange(); + }); + + context.AddProperty("Alpha Clip", new Toggle() { value = alphaClip }, (evt) => + { + if (Equals(alphaClip, evt.newValue)) + return; + + registerUndo("Change Alpha Clip"); + alphaClip = evt.newValue; + onChange(); + }); + + context.AddProperty("Cast Shadows", new Toggle() { value = castShadows }, (evt) => + { + if (Equals(castShadows, evt.newValue)) + return; + + registerUndo("Change Cast Shadows"); + castShadows = evt.newValue; + onChange(); + }); + + context.AddProperty("Receive Shadows", new Toggle() { value = receiveShadows }, (evt) => + { + if (Equals(receiveShadows, evt.newValue)) + return; + + registerUndo("Change Receive Shadows"); + receiveShadows = evt.newValue; + onChange(); + }); + + context.AddProperty("Supports LOD Cross Fade", new Toggle() { value = supportsLodCrossFade }, (evt) => + { + if (Equals(supportsLodCrossFade, evt.newValue)) + return; + registerUndo("Change Supports LOD Cross Fade"); + supportsLodCrossFade = evt.newValue; + onChange(); + }); + + context.AddProperty("CullMode", new EnumField(CullMode.Front) { value = cullMode}, (evt) => + { + if (Equals(cullMode, evt.newValue)) + return; + + registerUndo("Change ZWrite"); + cullMode = (CullMode) evt.newValue; + onChange(); + }); + + context.AddProperty("ZWrite", new EnumField(ZWrite.On) { value = zWrite}, (evt) => + { + if (Equals(zWrite, evt.newValue)) + return; + + registerUndo("Change ZWrite"); + zWrite = (ZWrite) evt.newValue; + onChange(); + }); + + context.AddProperty("ZTest", new EnumField(ZTest.Less) { value = zTest}, (evt) => + { + if (Equals(zTest, evt.newValue)) + return; + + registerUndo("Change ZTest"); + zTest = (ZTest) evt.newValue; + onChange(); + }); + + // Custom Editor GUI + // Requires FocusOutEvent + m_CustomGUIField = new TextField("") { value = customEditorGUI }; + m_CustomGUIField.RegisterCallback(s => + { + if (Equals(customEditorGUI, m_CustomGUIField.value)) + return; + + registerUndo("Change Custom Editor GUI"); + customEditorGUI = m_CustomGUIField.value; + onChange(); + }); + context.AddProperty("Custom Editor GUI", m_CustomGUIField, (evt) => {}); + + // SubTarget properties + m_ActiveSubTarget.value.GetPropertiesGUI(ref context, onChange, registerUndo); + +#if HAS_VFX_GRAPH + // VFX Support + if (!(m_ActiveSubTarget.value is UniversalSubTarget)) + context.AddHelpBox(MessageType.Info, $"The {m_ActiveSubTarget.value.displayName} target does not support VFX Graph."); + else + { + m_SupportVFXToggle = new Toggle("") { value = m_SupportVFX }; + context.AddProperty("Support VFX Graph", m_SupportVFXToggle, (evt) => + { + m_SupportVFX = m_SupportVFXToggle.value; + }); + } +#endif + } + + public bool TrySetActiveSubTarget(Type subTargetType) + { + if(!subTargetType.IsSubclassOf(typeof(SubTarget))) + return false; + + foreach(var subTarget in m_SubTargets) + { + if(subTarget.GetType().Equals(subTargetType)) + { + m_ActiveSubTarget = subTarget; + return true; + } + } + + return false; + } + + private static CullMode UpgradeCullMode(ShaderGraphEssentials.Legacy.CullMode oldCullMode) + { + switch (oldCullMode) + { + case Legacy.CullMode.Back: + return CullMode.Back; + case Legacy.CullMode.Front: + return CullMode.Front; + case Legacy.CullMode.Off: + return CullMode.Off; + default: + throw new ArgumentOutOfRangeException(nameof(oldCullMode), oldCullMode, null); + } + } + + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + void UpgradeAlphaClip(int clipId) + { + var clipThresholdId = clipId; + var node = masterNode as AbstractMaterialNode; + var clipThresholdSlot = node.FindSlot(clipThresholdId); + if(clipThresholdSlot == null) + return; + + clipThresholdSlot.owner = node; + if(clipThresholdSlot.isConnected || clipThresholdSlot.value > 0.0f) + { + m_AlphaClip = true; + } + } + + // Upgrade Target + switch(masterNode) + { + case SGEUnlitMasterNode1 unlitMasterNode: + m_RenderType = unlitMasterNode.m_renderType; + m_RenderQueue = unlitMasterNode.m_renderQueue; + m_BlendMode = (BlendMode) unlitMasterNode.m_blendMode; + m_CullMode = UpgradeCullMode(unlitMasterNode.m_cullMode); + m_ZWrite = unlitMasterNode.m_zwrite; + m_ZTest = unlitMasterNode.m_ztest; + m_CustomEditorGUI = unlitMasterNode.m_customEditor; + UpgradeAlphaClip(8); + break; + case SGESimpleLitMasterNode1 simpleLitMasterNode: + m_RenderType = simpleLitMasterNode.m_renderType; + m_RenderQueue = simpleLitMasterNode.m_renderQueue; + m_BlendMode = (BlendMode) simpleLitMasterNode.m_blendMode; + m_CullMode = UpgradeCullMode(simpleLitMasterNode.m_cullMode); + m_ZWrite = simpleLitMasterNode.m_zwrite; + m_ZTest = simpleLitMasterNode.m_ztest; + m_CustomEditorGUI = simpleLitMasterNode.m_customEditor; + UpgradeAlphaClip(7); + break; + case SGECustomLitMasterNode1 customLitMasterNode: + m_RenderType = customLitMasterNode.m_renderType; + m_RenderQueue = customLitMasterNode.m_renderQueue; + m_BlendMode = (BlendMode) customLitMasterNode.m_blendMode; + m_CullMode = UpgradeCullMode(customLitMasterNode.m_cullMode); + m_ZWrite = customLitMasterNode.m_zwrite; + m_ZTest = customLitMasterNode.m_ztest; + m_CustomEditorGUI = customLitMasterNode.m_customEditor; + UpgradeAlphaClip(7); + break; + } + + // Upgrade SubTarget + foreach(var subTarget in m_SubTargets) + { + if(!(subTarget is ILegacyTarget legacySubTarget)) + continue; + + if(legacySubTarget.TryUpgradeFromMasterNode(masterNode, out blockMap)) + { + m_ActiveSubTarget = subTarget; + return true; + } + } + + blockMap = null; + return false; + } + + public override bool WorksWithSRP(RenderPipelineAsset scriptableRenderPipeline) + { + return scriptableRenderPipeline?.GetType() == typeof(UniversalRenderPipelineAsset); + } + +#if HAS_VFX_GRAPH + public void ConfigureContextData(VFXContext context, VFXTaskCompiledData data) + { + if (!(m_ActiveSubTarget.value is IRequireVFXContext vfxSubtarget)) + return; + + vfxSubtarget.ConfigureContextData(context, data); + } + +#endif + + public bool CanSupportVFX() + { + if (m_ActiveSubTarget.value == null) + return false; + + if (m_ActiveSubTarget.value is UniversalUnlitSubTarget) + return true; + + if (m_ActiveSubTarget.value is UniversalLitSubTarget) + return true; + + //It excludes: + // - UniversalDecalSubTarget + // - UniversalSpriteLitSubTarget + // - UniversalSpriteUnlitSubTarget + // - UniversalSpriteCustomLitSubTarget + return false; + } + + public bool SupportsVFX() + { +#if HAS_VFX_GRAPH + if (!CanSupportVFX()) + return false; + + return m_SupportVFX; +#else + return false; +#endif + } + + [Serializable] + class SGEUniversalTargetLegacySerialization + { + } + + public override void OnAfterDeserialize(string json) + { + base.OnAfterDeserialize(json); + + if (this.sgVersion < latestVersion) + { + if (this.sgVersion == 0) + { + // deserialize the old settings to upgrade + var oldSettings = JsonUtility.FromJson(json); + } + ChangeVersion(latestVersion); + } + } + + #region Metadata + string IHasMetadata.identifier + { + get + { + // defer to subtarget + if (m_ActiveSubTarget.value is IHasMetadata subTargetHasMetaData) + return subTargetHasMetaData.identifier; + return null; + } + } + + ScriptableObject IHasMetadata.GetMetadataObject(GraphDataReadOnly graph) + { + // defer to subtarget + if (m_ActiveSubTarget.value is IHasMetadata subTargetHasMetaData) + return subTargetHasMetaData.GetMetadataObject(graph); + return null; + } + + #endregion + + } + +#region Passes + static class CorePasses + { + /// + /// Automatically enables Alpha-To-Coverage in the provided opaque pass targets using alpha clipping + /// + /// The pass to modify + /// The target to query + internal static void AddAlphaToMaskControlToPass(ref PassDescriptor pass, SGEUniversalTarget target) + { + if (target.alphaClip && (target.blendMode == BlendMode.Off)) + { + pass.renderStates.Add(RenderState.AlphaToMask("On")); + } + } + + internal static void AddAlphaClipControlToPass(ref PassDescriptor pass, SGEUniversalTarget target) + { + if (target.alphaClip) + pass.defines.Add(CoreKeywordDescriptors.AlphaTestOn, 1); + } + + internal static void AddLODCrossFadeControlToPass(ref PassDescriptor pass, SGEUniversalTarget target) + { + if (target.supportsLodCrossFade) + { + pass.includes.Add(CoreIncludes.LODCrossFade); + pass.keywords.Add(CoreKeywordDescriptors.LODFadeCrossFade); + pass.defines.Add(CoreKeywordDescriptors.UseUnityCrossFade, 1); + } + } + + internal static void AddTargetSurfaceControlsToPass(ref PassDescriptor pass, SGEUniversalTarget target, bool blendModePreserveSpecular = false) + { + // setup target control via define + bool transparent = target.blendMode != BlendMode.Off; + if (transparent) + { + pass.defines.Add(CoreKeywordDescriptors.SurfaceTypeTransparent, 1); + + // alpha premultiply in shader only needed when alpha is different for diffuse & specular + if ((target.blendMode == BlendMode.Alpha || target.blendMode == BlendMode.Additive) && blendModePreserveSpecular) + pass.defines.Add(CoreKeywordDescriptors.AlphaPremultiplyOn, 1); + else if (target.blendMode == BlendMode.Multiply) + pass.defines.Add(CoreKeywordDescriptors.AlphaModulateOn, 1); + } + + AddAlphaClipControlToPass(ref pass, target); + } + + // used by lit/unlit subtargets + public static PassDescriptor DepthOnly(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "DepthOnly", + referenceName = "SHADERPASS_DEPTHONLY", + lightMode = "DepthOnly", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentAlphaOnly, + + // Fields + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.DepthOnly(target), + pragmas = CorePragmas.Instanced, + defines = new DefineCollection(), + keywords = new KeywordCollection(), + includes = new IncludeCollection { CoreIncludes.DepthOnly }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddAlphaClipControlToPass(ref result, target); + AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + // used by lit/unlit subtargets + public static PassDescriptor DepthNormal(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "DepthNormalsOnly", + referenceName = "SHADERPASS_DEPTHNORMALS", + lightMode = "DepthNormalsOnly", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentDepthNormals, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.DepthNormals, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.DepthNormalsOnly(target), + pragmas = CorePragmas.Instanced, + defines = new DefineCollection(), + keywords = new KeywordCollection(), + includes = new IncludeCollection { CoreIncludes.DepthNormalsOnly }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddAlphaClipControlToPass(ref result, target); + AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + // used by lit/unlit subtargets + public static PassDescriptor DepthNormalOnly(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "DepthNormalsOnly", + referenceName = "SHADERPASS_DEPTHNORMALSONLY", + lightMode = "DepthNormalsOnly", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentDepthNormals, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.DepthNormals, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.DepthNormalsOnly(target), + pragmas = CorePragmas.Instanced, + defines = new DefineCollection(), + keywords = new KeywordCollection { CoreKeywordDescriptors.GBufferNormalsOct }, + includes = new IncludeCollection { CoreIncludes.DepthNormalsOnly }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddAlphaClipControlToPass(ref result, target); + AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + + // used by lit/unlit targets + public static PassDescriptor ShadowCaster(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "ShadowCaster", + referenceName = "SHADERPASS_SHADOWCASTER", + lightMode = "ShadowCaster", + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentAlphaOnly, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = CoreRequiredFields.ShadowCaster, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.ShadowCaster(target), + pragmas = CorePragmas.Instanced, + defines = new DefineCollection(), + keywords = new KeywordCollection { CoreKeywords.ShadowCaster }, + includes = new IncludeCollection { CoreIncludes.ShadowCaster }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddAlphaClipControlToPass(ref result, target); + AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + public static PassDescriptor SceneSelection(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "SceneSelectionPass", + referenceName = "SHADERPASS_DEPTHONLY", + lightMode = "SceneSelectionPass", + useInPreview = false, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentAlphaOnly, + + // Fields + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.SceneSelection(target), + pragmas = CorePragmas.Instanced, + defines = new DefineCollection { CoreDefines.SceneSelection, { CoreKeywordDescriptors.AlphaClipThreshold, 1 } }, + keywords = new KeywordCollection(), + includes = CoreIncludes.SceneSelection, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddAlphaClipControlToPass(ref result, target); + + return result; + } + + public static PassDescriptor ScenePicking(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "ScenePickingPass", + referenceName = "SHADERPASS_DEPTHONLY", + lightMode = "Picking", + useInPreview = false, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentAlphaOnly, + + // Fields + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.ScenePicking(target), + pragmas = CorePragmas.Instanced, + defines = new DefineCollection { CoreDefines.ScenePicking, { CoreKeywordDescriptors.AlphaClipThreshold, 1 } }, + keywords = new KeywordCollection(), + includes = CoreIncludes.ScenePicking, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddAlphaClipControlToPass(ref result, target); + + return result; + } + + public static PassDescriptor _2DSceneSelection(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "SceneSelectionPass", + referenceName = "SHADERPASS_DEPTHONLY", + lightMode = "SceneSelectionPass", + useInPreview = false, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentAlphaOnly, + + // Fields + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.SceneSelection(target), + pragmas = CorePragmas._2DDefault, + defines = new DefineCollection { CoreDefines.SceneSelection, { CoreKeywordDescriptors.AlphaClipThreshold, 0 } }, + keywords = new KeywordCollection(), + includes = CoreIncludes.ScenePicking, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddAlphaClipControlToPass(ref result, target); + AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + public static PassDescriptor _2DScenePicking(SGEUniversalTarget target) + { + var result = new PassDescriptor() + { + // Definition + displayName = "ScenePickingPass", + referenceName = "SHADERPASS_DEPTHONLY", + lightMode = "Picking", + useInPreview = false, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentAlphaOnly, + + // Fields + structs = CoreStructCollections.Default, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.ScenePicking(target), + pragmas = CorePragmas._2DDefault, + defines = new DefineCollection { CoreDefines.ScenePicking, { CoreKeywordDescriptors.AlphaClipThreshold, 0 } }, + keywords = new KeywordCollection(), + includes = CoreIncludes.SceneSelection, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + AddAlphaClipControlToPass(ref result, target); + AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + } +#endregion + +#region PortMasks + class CoreBlockMasks + { + public static readonly BlockFieldDescriptor[] Vertex = new BlockFieldDescriptor[] + { + BlockFields.VertexDescription.Position, + BlockFields.VertexDescription.Normal, + BlockFields.VertexDescription.Tangent, + }; + + public static readonly BlockFieldDescriptor[] FragmentAlphaOnly = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + }; + + public static readonly BlockFieldDescriptor[] FragmentColorAlpha = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.BaseColor, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + }; + + public static readonly BlockFieldDescriptor[] FragmentDepthNormals = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.NormalOS, + BlockFields.SurfaceDescription.NormalTS, + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + }; + } +#endregion + +#region StructCollections + static class CoreStructCollections + { + public static readonly StructCollection Default = new StructCollection + { + { Structs.Attributes }, + { UniversalStructs.Varyings }, + { Structs.SurfaceDescriptionInputs }, + { Structs.VertexDescriptionInputs }, + }; + } +#endregion + +#region RequiredFields + static class CoreRequiredFields + { + public static readonly FieldCollection ShadowCaster = new FieldCollection() + { + StructFields.Varyings.normalWS, + }; + public static readonly FieldCollection DepthNormals = new FieldCollection() + { + StructFields.Attributes.uv1, // needed for meta vertex position + StructFields.Varyings.normalWS, + StructFields.Varyings.tangentWS, // needed for vertex lighting + }; + } +#endregion + +#region FieldDependencies + static class CoreFieldDependencies + { + public static readonly DependencyCollection Default = new DependencyCollection() + { + { FieldDependencies.Default }, + new FieldDependency(UniversalStructFields.Varyings.stereoTargetEyeIndexAsRTArrayIdx, StructFields.Attributes.instanceID ), + new FieldDependency(UniversalStructFields.Varyings.stereoTargetEyeIndexAsBlendIdx0, StructFields.Attributes.instanceID ), + }; + } +#endregion + +#region RenderStates + static class CoreRenderStates + { + public static readonly RenderStateCollection Default = new RenderStateCollection + { + // TODO render type + // TODO render queue + { RenderState.Blend(Blend.One, Blend.Zero), new FieldCondition(SGEFields.BlendModeOff, true) }, + { RenderState.Blend(Blend.SrcAlpha, Blend.OneMinusSrcAlpha, Blend.One, Blend.OneMinusSrcAlpha), new FieldCondition(SGEFields.BlendModeAlpha, true) }, + { RenderState.Blend(Blend.One, Blend.OneMinusSrcAlpha, Blend.One, Blend.OneMinusSrcAlpha), new FieldCondition(SGEFields.BlendModePremultiply, true) }, + { RenderState.Blend(Blend.SrcAlpha, Blend.One, Blend.One, Blend.One), new FieldCondition(SGEFields.BlendModeAdditive, true) }, + { RenderState.Blend(Blend.DstColor, Blend.Zero), new FieldCondition(SGEFields.BlendModeMultiply, true) }, + + { RenderState.Cull(Cull.Off), new FieldCondition(SGEFields.CullModeOff, true) }, + { RenderState.Cull(Cull.Front), new FieldCondition(SGEFields.CullModeFront, true) }, + { RenderState.Cull(Cull.Back), new FieldCondition(SGEFields.CullModeBack, true) }, + + { RenderState.ZWrite(ZWrite.On), new FieldCondition(SGEFields.ZWrite, true) }, + { RenderState.ZWrite(ZWrite.Off), new FieldCondition(SGEFields.ZWrite, false) }, + + { RenderState.ZTest(ZTest.Less), new FieldCondition(SGEFields.ZTestLess, true) }, + { RenderState.ZTest(ZTest.Greater), new FieldCondition(SGEFields.ZTestGreater, true) }, + { RenderState.ZTest(ZTest.LEqual), new FieldCondition(SGEFields.ZTestLEqual, true) }, + { RenderState.ZTest(ZTest.GEqual), new FieldCondition(SGEFields.ZTestGEqual, true) }, + { RenderState.ZTest(ZTest.Equal), new FieldCondition(SGEFields.ZTestEqual, true) }, + { RenderState.ZTest(ZTest.NotEqual), new FieldCondition(SGEFields.ZTestNotEqual, true) }, + { RenderState.ZTest(ZTest.Always), new FieldCondition(SGEFields.ZTestAlways, true) }, + }; + + // used by lit/unlit subtargets + public static RenderStateCollection UberSwitchedRenderState(SGEUniversalTarget target, bool blendModePreserveSpecular = false) + { + var result = new RenderStateCollection(); + + result.Add(RenderState.ZTest(target.zTest)); + result.Add(RenderState.ZWrite(target.zWrite)); + + result.Add(RenderState.Cull(target.cullMode.ToString())); + + // Lift alpha multiply from ROP to shader in preserve spec for different diffuse and specular blends. + Blend blendSrcRGB = blendModePreserveSpecular ? Blend.One : Blend.SrcAlpha; + + switch (target.blendMode) + { + case BlendMode.Alpha: + result.Add(RenderState.Blend(blendSrcRGB, Blend.OneMinusSrcAlpha, Blend.One, Blend.OneMinusSrcAlpha)); + break; + case BlendMode.Premultiply: + result.Add(RenderState.Blend(Blend.One, Blend.OneMinusSrcAlpha, Blend.One, Blend.OneMinusSrcAlpha)); + break; + case BlendMode.Additive: + result.Add(RenderState.Blend(blendSrcRGB, Blend.One, Blend.One, Blend.One)); + break; + case BlendMode.Multiply: + result.Add(RenderState.Blend(Blend.DstColor, Blend.Zero, Blend.Zero, Blend.One)); // Multiply RGB only, keep A + break; + } + + return result; + } + + public static readonly RenderStateCollection Meta = new RenderStateCollection + { + { RenderState.Cull(Cull.Off) }, + }; + + public static RenderStateDescriptor UberSwitchedCullRenderState(SGEUniversalTarget target) + { + return RenderState.Cull(target.cullMode.ToString()); + } + + // used by lit/unlit targets + public static RenderStateCollection ShadowCaster(SGEUniversalTarget target) + { + var result = new RenderStateCollection + { + { RenderState.ZTest(ZTest.LEqual) }, + { RenderState.ZWrite(ZWrite.On) }, + { UberSwitchedCullRenderState(target) }, + { RenderState.ColorMask("ColorMask 0") }, + }; + return result; + } + + // used by lit/unlit targets + public static RenderStateCollection DepthOnly(SGEUniversalTarget target) + { + var result = new RenderStateCollection + { + { RenderState.ZTest(ZTest.LEqual) }, + { RenderState.ZWrite(ZWrite.On) }, + { UberSwitchedCullRenderState(target) }, + { RenderState.ColorMask("ColorMask 0") }, + }; + + return result; + } + + // used by lit target ONLY + public static RenderStateCollection DepthNormalsOnly(SGEUniversalTarget target) + { + var result = new RenderStateCollection + { + { RenderState.ZTest(ZTest.LEqual) }, + { RenderState.ZWrite(ZWrite.On) }, + { UberSwitchedCullRenderState(target) } + }; + + return result; + } + + // Used by all targets + public static RenderStateCollection SceneSelection(SGEUniversalTarget target) + { + var result = new RenderStateCollection + { + { RenderState.Cull(Cull.Off) }, + }; + + return result; + } + + public static RenderStateCollection ScenePicking(SGEUniversalTarget target) + { + var result = new RenderStateCollection + { + { UberSwitchedCullRenderState(target) } + }; + + return result; + } + } +#endregion + +#region Pragmas +static class CorePragmas + { + public static readonly PragmaCollection Default = new PragmaCollection + { + { Pragma.Target(ShaderModel.Target20) }, + { Pragma.Vertex("vert") }, + { Pragma.Fragment("frag") }, + }; + + public static readonly PragmaCollection Instanced = new PragmaCollection + { + { Pragma.Target(ShaderModel.Target20) }, + { Pragma.MultiCompileInstancing }, + { Pragma.Vertex("vert") }, + { Pragma.Fragment("frag") }, + }; + + public static readonly PragmaCollection Forward = new PragmaCollection + { + { Pragma.Target(ShaderModel.Target20) }, + { Pragma.MultiCompileInstancing }, + { Pragma.MultiCompileFog }, + { Pragma.InstancingOptions(InstancingOptions.RenderingLayer) }, + { Pragma.Vertex("vert") }, + { Pragma.Fragment("frag") }, + }; + + public static readonly PragmaCollection _2DDefault = new PragmaCollection + { + { Pragma.Target(ShaderModel.Target20) }, + { Pragma.ExcludeRenderers(new[]{ Platform.D3D9 }) }, + { Pragma.Vertex("vert") }, + { Pragma.Fragment("frag") }, + }; + + public static readonly PragmaCollection GBuffer = new PragmaCollection + { + { Pragma.Target(ShaderModel.Target45) }, + { Pragma.ExcludeRenderers(new[] { Platform.GLES3, Platform.GLCore }) }, + { Pragma.MultiCompileInstancing }, + { Pragma.MultiCompileFog }, + { Pragma.InstancingOptions(InstancingOptions.RenderingLayer) }, + { Pragma.Vertex("vert") }, + { Pragma.Fragment("frag") }, + }; + } +#endregion + +#region Defines +static class CoreDefines +{ + public static readonly DefineCollection UseLegacySpriteBlocks = new DefineCollection + { + { CoreKeywordDescriptors.UseLegacySpriteBlocks, 1, new FieldCondition(CoreFields.UseLegacySpriteBlocks, true) }, + }; + + public static readonly DefineCollection UseFragmentFog = new DefineCollection() + { + {CoreKeywordDescriptors.UseFragmentFog, 1}, + }; + + public static readonly DefineCollection SceneSelection = new DefineCollection + { + { CoreKeywordDescriptors.SceneSelectionPass, 1 }, + }; + + public static readonly DefineCollection ScenePicking = new DefineCollection + { + { CoreKeywordDescriptors.ScenePickingPass, 1 }, + }; +} +#endregion + +#region Includes + static class CoreIncludes + { + const string kColor = "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"; + const string kTexture = "Packages/com.unity.render-pipelines.core/ShaderLibrary/Texture.hlsl"; + const string kCore = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"; + const string kInput = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Input.hlsl"; + const string kLighting = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl"; + const string kGraphFunctions = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/ShaderGraphFunctions.hlsl"; + const string kVaryings = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl"; + const string kShaderPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/ShaderPass.hlsl"; + const string kDepthOnlyPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/DepthOnlyPass.hlsl"; + internal const string kDepthNormalsOnlyPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/DepthNormalsOnlyPass.hlsl"; + const string kShadowCasterPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/ShadowCasterPass.hlsl"; + const string kTextureStack = "Packages/com.unity.render-pipelines.core/ShaderLibrary/TextureStack.hlsl"; + const string kDBuffer = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DBuffer.hlsl"; + const string kSelectionPickingPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SelectionPickingPass.hlsl"; + const string kLODCrossFade = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/LODCrossFade.hlsl"; + + // Files that are included with #include_with_pragmas + const string kDOTS = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/DOTS.hlsl"; + const string kRenderingLayers = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/RenderingLayers.hlsl"; + const string kProbeVolumes = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/ProbeVolumeVariants.hlsl"; + + public static readonly IncludeCollection CorePregraph = new IncludeCollection + { + { kColor, IncludeLocation.Pregraph }, + { kTexture, IncludeLocation.Pregraph }, + { kCore, IncludeLocation.Pregraph }, + { kLighting, IncludeLocation.Pregraph }, + { kInput, IncludeLocation.Pregraph }, + { kTextureStack, IncludeLocation.Pregraph }, // TODO: put this on a conditional + }; + + public static readonly IncludeCollection DOTSPregraph = new IncludeCollection + { + { kDOTS, IncludeLocation.Pregraph, true }, + }; + + public static readonly IncludeCollection WriteRenderLayersPregraph = new IncludeCollection + { + { kRenderingLayers, IncludeLocation.Pregraph, true }, + }; + + public static readonly IncludeCollection ProbeVolumePregraph = new IncludeCollection + { + { kProbeVolumes, IncludeLocation.Pregraph, true }, + }; + + public static readonly IncludeCollection ShaderGraphPregraph = new IncludeCollection + { + { kGraphFunctions, IncludeLocation.Pregraph }, + }; + + public static readonly IncludeCollection CorePostgraph = new IncludeCollection + { + { kShaderPass, IncludeLocation.Pregraph }, + { kVaryings, IncludeLocation.Postgraph }, + }; + + public static readonly IncludeCollection DepthOnly = new IncludeCollection + { + // Pre-graph + { DOTSPregraph }, + { CorePregraph }, + { ShaderGraphPregraph }, + + // Post-graph + { CorePostgraph }, + { kDepthOnlyPass, IncludeLocation.Postgraph }, + }; + + public static readonly IncludeCollection DepthNormalsOnly = new IncludeCollection + { + // Pre-graph + { DOTSPregraph }, + { WriteRenderLayersPregraph }, + { CorePregraph }, + { ShaderGraphPregraph }, + + // Post-graph + { CorePostgraph }, + { kDepthNormalsOnlyPass, IncludeLocation.Postgraph }, + }; + + public static readonly IncludeCollection ShadowCaster = new IncludeCollection + { + // Pre-graph + { DOTSPregraph }, + { CorePregraph }, + { ShaderGraphPregraph }, + + // Post-graph + { CorePostgraph }, + { kShadowCasterPass, IncludeLocation.Postgraph }, + }; + + public static readonly IncludeCollection DBufferPregraph = new IncludeCollection + { + { kDBuffer, IncludeLocation.Pregraph }, + }; + + public static readonly IncludeCollection SceneSelection = new IncludeCollection + { + // Pre-graph + { CorePregraph }, + { ShaderGraphPregraph }, + + // Post-graph + { CorePostgraph }, + { kSelectionPickingPass, IncludeLocation.Postgraph }, + }; + + public static readonly IncludeCollection ScenePicking = new IncludeCollection + { + // Pre-graph + { CorePregraph }, + { ShaderGraphPregraph }, + + // Post-graph + { CorePostgraph }, + { kSelectionPickingPass, IncludeLocation.Postgraph }, + }; + + public static readonly IncludeCollection LODCrossFade = new IncludeCollection + { + { kLODCrossFade, IncludeLocation.Pregraph } + }; + } +#endregion + +#region KeywordDescriptors +static class CoreKeywordDescriptors + { + public static readonly KeywordDescriptor StaticLightmap = new KeywordDescriptor() + { + displayName = "Static Lightmap", + referenceName = "LIGHTMAP_ON", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor DynamicLightmap = new KeywordDescriptor() + { + displayName = "Dynamic Lightmap", + referenceName = "DYNAMICLIGHTMAP_ON", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor DirectionalLightmapCombined = new KeywordDescriptor() + { + displayName = "Directional Lightmap Combined", + referenceName = "DIRLIGHTMAP_COMBINED", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor SampleGI = new KeywordDescriptor() + { + displayName = "Sample GI", + referenceName = "_SAMPLE_GI", + type = KeywordType.Boolean, + definition = KeywordDefinition.ShaderFeature, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor AlphaTestOn = new KeywordDescriptor() + { + displayName = ShaderKeywordStrings._ALPHATEST_ON, + referenceName = ShaderKeywordStrings._ALPHATEST_ON, + type = KeywordType.Boolean, + definition = KeywordDefinition.ShaderFeature, + scope = KeywordScope.Local, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor SurfaceTypeTransparent = new KeywordDescriptor() + { + displayName = ShaderKeywordStrings._SURFACE_TYPE_TRANSPARENT, + referenceName = ShaderKeywordStrings._SURFACE_TYPE_TRANSPARENT, + type = KeywordType.Boolean, + definition = KeywordDefinition.ShaderFeature, + scope = KeywordScope.Global, // needs to match HDRP + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor AlphaPremultiplyOn = new KeywordDescriptor() + { + displayName = ShaderKeywordStrings._ALPHAPREMULTIPLY_ON, + referenceName = ShaderKeywordStrings._ALPHAPREMULTIPLY_ON, + type = KeywordType.Boolean, + definition = KeywordDefinition.ShaderFeature, + scope = KeywordScope.Local, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor AlphaModulateOn = new KeywordDescriptor() + { + displayName = ShaderKeywordStrings._ALPHAMODULATE_ON, + referenceName = ShaderKeywordStrings._ALPHAMODULATE_ON, + type = KeywordType.Boolean, + definition = KeywordDefinition.ShaderFeature, + scope = KeywordScope.Local, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor MainLightShadows = new KeywordDescriptor() + { + displayName = "Main Light Shadows", + referenceName = "", + type = KeywordType.Enum, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + entries = new KeywordEntry[] + { + new KeywordEntry() { displayName = "Off", referenceName = "" }, + new KeywordEntry() { displayName = "No Cascade", referenceName = "MAIN_LIGHT_SHADOWS" }, + new KeywordEntry() { displayName = "Cascade", referenceName = "MAIN_LIGHT_SHADOWS_CASCADE" }, + new KeywordEntry() { displayName = "Screen", referenceName = "MAIN_LIGHT_SHADOWS_SCREEN" }, + } + }; + + public static readonly KeywordDescriptor AdditionalLights = new KeywordDescriptor() + { + displayName = "Additional Lights", + referenceName = "", + type = KeywordType.Enum, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + entries = new KeywordEntry[] + { + new KeywordEntry() { displayName = "Off", referenceName = "" }, + new KeywordEntry() { displayName = "Vertex", referenceName = "ADDITIONAL_LIGHTS_VERTEX" }, + new KeywordEntry() { displayName = "Fragment", referenceName = "ADDITIONAL_LIGHTS" }, + }, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor AdditionalLightShadows = new KeywordDescriptor() + { + displayName = "Additional Light Shadows", + referenceName = "_ADDITIONAL_LIGHT_SHADOWS", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor ReflectionProbeBlending = new KeywordDescriptor() + { + displayName = "Reflection Probe Blending", + referenceName = "_REFLECTION_PROBE_BLENDING", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor ReflectionProbeBoxProjection = new KeywordDescriptor() + { + displayName = "Reflection Probe Box Projection", + referenceName = "_REFLECTION_PROBE_BOX_PROJECTION", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor ShadowsSoft = new KeywordDescriptor() + { + displayName = "Shadows Soft", + referenceName = "_SHADOWS_SOFT", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor MixedLightingSubtractive = new KeywordDescriptor() + { + displayName = "Mixed Lighting Subtractive", + referenceName = "_MIXED_LIGHTING_SUBTRACTIVE", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor LightmapShadowMixing = new KeywordDescriptor() + { + displayName = "Lightmap Shadow Mixing", + referenceName = "LIGHTMAP_SHADOW_MIXING", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor ShadowsShadowmask = new KeywordDescriptor() + { + displayName = "Shadows Shadowmask", + referenceName = "SHADOWS_SHADOWMASK", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor LightLayers = new KeywordDescriptor() + { + displayName = "Light Layers", + referenceName = "_LIGHT_LAYERS", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + + + public static readonly KeywordDescriptor SmoothnessChannel = new KeywordDescriptor() + { + displayName = "Smoothness Channel", + referenceName = "_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A", + type = KeywordType.Boolean, + definition = KeywordDefinition.ShaderFeature, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor RenderPassEnabled = new KeywordDescriptor() + { + displayName = "Render Pass Enabled", + referenceName = "_RENDER_PASS_ENABLED", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor ShapeLightType0 = new KeywordDescriptor() + { + displayName = "Shape Light Type 0", + referenceName = "USE_SHAPE_LIGHT_TYPE_0", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor ShapeLightType1 = new KeywordDescriptor() + { + displayName = "Shape Light Type 1", + referenceName = "USE_SHAPE_LIGHT_TYPE_1", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor ShapeLightType2 = new KeywordDescriptor() + { + displayName = "Shape Light Type 2", + referenceName = "USE_SHAPE_LIGHT_TYPE_2", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor ShapeLightType3 = new KeywordDescriptor() + { + displayName = "Shape Light Type 3", + referenceName = "USE_SHAPE_LIGHT_TYPE_3", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor UseLegacySpriteBlocks = new KeywordDescriptor() + { + displayName = "UseLegacySpriteBlocks", + referenceName = "USELEGACYSPRITEBLOCKS", + type = KeywordType.Boolean, + }; + + public static readonly KeywordDescriptor UseFragmentFog = new KeywordDescriptor() + { + displayName = "UseFragmentFog", + referenceName = "_FOG_FRAGMENT", + type = KeywordType.Boolean, + }; + + public static readonly KeywordDescriptor GBufferNormalsOct = new KeywordDescriptor() + { + displayName = "GBuffer normal octahedron encoding", + referenceName = "_GBUFFER_NORMALS_OCT", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor DBuffer = new KeywordDescriptor() + { + displayName = "Decals", + referenceName = "", + type = KeywordType.Enum, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + entries = new KeywordEntry[] + { + new KeywordEntry() { displayName = "Off", referenceName = "" }, + new KeywordEntry() { displayName = "DBuffer Mrt1", referenceName = "DBUFFER_MRT1" }, + new KeywordEntry() { displayName = "DBuffer Mrt2", referenceName = "DBUFFER_MRT2" }, + new KeywordEntry() { displayName = "DBuffer Mrt3", referenceName = "DBUFFER_MRT3" }, + }, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor DebugDisplay = new KeywordDescriptor() + { + displayName = "Debug Display", + referenceName = "DEBUG_DISPLAY", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor FoveatedRendering = new KeywordDescriptor() + { + displayName = "Foveated Rendering Non Uniform Raster", + referenceName = "_FOVEATED_RENDERING_NON_UNIFORM_RASTER", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + stages = KeywordShaderStage.Fragment, + }; + + + public static readonly KeywordDescriptor SceneSelectionPass = new KeywordDescriptor() + { + displayName = "Scene Selection Pass", + referenceName = "SCENESELECTIONPASS", + type = KeywordType.Boolean, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor ScenePickingPass = new KeywordDescriptor() + { + displayName = "Scene Picking Pass", + referenceName = "SCENEPICKINGPASS", + type = KeywordType.Boolean, + }; + + public static readonly KeywordDescriptor AlphaClipThreshold = new KeywordDescriptor() + { + displayName = "AlphaClipThreshold", + referenceName = "ALPHA_CLIP_THRESHOLD", + type = KeywordType.Boolean, + definition = KeywordDefinition.Predefined, + }; + + public static readonly KeywordDescriptor LightCookies = new KeywordDescriptor() + { + displayName = "Light Cookies", + referenceName = "_LIGHT_COOKIES", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor ForwardPlus = new KeywordDescriptor() + { + displayName = "Forward+", + referenceName = "_FORWARD_PLUS", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor EditorVisualization = new KeywordDescriptor() + { + displayName = "Editor Visualization", + referenceName = "EDITOR_VISUALIZATION", + type = KeywordType.Boolean, + definition = KeywordDefinition.ShaderFeature, + scope = KeywordScope.Global, + }; + + public static readonly KeywordDescriptor UseUnityCrossFade = new KeywordDescriptor() + { + displayName = ShaderKeywordStrings.USE_UNITY_CROSSFADE, + referenceName = ShaderKeywordStrings.USE_UNITY_CROSSFADE, + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor LODFadeCrossFade = new KeywordDescriptor() + { + displayName = ShaderKeywordStrings.LOD_FADE_CROSSFADE, + referenceName = ShaderKeywordStrings.LOD_FADE_CROSSFADE, + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + stages = KeywordShaderStage.Fragment, + }; + + public static readonly KeywordDescriptor ScreenSpaceAmbientOcclusion = new KeywordDescriptor() + { + displayName = "Screen Space Ambient Occlusion", + referenceName = "_SCREEN_SPACE_OCCLUSION", + type = KeywordType.Boolean, + definition = KeywordDefinition.MultiCompile, + scope = KeywordScope.Global, + stages = KeywordShaderStage.Fragment, + }; + } +#endregion + + +#region CustomInterpolators +static class CoreCustomInterpDescriptors +{ + public static readonly CustomInterpSubGen.Collection Common = new CustomInterpSubGen.Collection + { + // Custom interpolators are not explicitly defined in the SurfaceDescriptionInputs template. + // This entry point will let us generate a block of pass-through assignments for each field. + CustomInterpSubGen.Descriptor.MakeBlock(CustomInterpSubGen.Splice.k_spliceCopyToSDI, "output", "input"), + + // sgci_PassThroughFunc is called from BuildVaryings in Varyings.hlsl to copy custom interpolators from vertex descriptions. + // this entry point allows for the function to be defined before it is used. + CustomInterpSubGen.Descriptor.MakeFunc(CustomInterpSubGen.Splice.k_splicePreSurface, "CustomInterpolatorPassThroughFunc", "Varyings", "VertexDescription", "CUSTOMINTERPOLATOR_VARYPASSTHROUGH_FUNC", "FEATURES_GRAPH_VERTEX") + }; +} +#endregion +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalTarget.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalTarget.cs.meta new file mode 100644 index 0000000..49656f9 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalTarget.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: f9a02d7a49622a44bb0e1e7f11ade6bd +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalUnlitSubTarget.cs b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalUnlitSubTarget.cs new file mode 100644 index 0000000..3de192e --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalUnlitSubTarget.cs @@ -0,0 +1,314 @@ +// +// ShaderGraphEssentials for Unity +// (c) 2019 PH Graphics +// Source code may be used and modified for personal or commercial projects. +// Source code may NOT be redistributed or sold. +// +// *** A NOTE ABOUT PIRACY *** +// +// If you got this asset from a pirate site, please consider buying it from the Unity asset store. This asset is only legally available from the Unity Asset Store. +// +// I'm a single indie dev supporting my family by spending hundreds and thousands of hours on this and other assets. It's very offensive, rude and just plain evil to steal when I (and many others) put so much hard work into the software. +// +// Thank you. +// +// *** END NOTE ABOUT PIRACY *** +// + +using System; +using System.Collections.Generic; +using System.Linq; +using ShaderGraphEssentials.Legacy; +using UnityEditor; +using UnityEditor.Rendering.Universal.ShaderGraph; +using UnityEditor.ShaderGraph; +using UnityEditor.ShaderGraph.Internal; +using UnityEditor.ShaderGraph.Legacy; +using UnityEditor.ShaderGraph.Serialization; +using UnityEditor.UIElements; +using UnityEngine; +using UnityEngine.Assertions; +using UnityEngine.Rendering; +using UnityEngine.Rendering.Universal; +using UnityEngine.UIElements; +using static ShaderGraphEssentials.SGESubShaderUtils; +using static ShaderGraphEssentials.SGEShaderUtils; + +namespace ShaderGraphEssentials +{ + sealed class SGEUniversalUnlitSubTarget : SGEUniversalSubTarget, ILegacyTarget + { + static readonly GUID kSourceCodeGuid = new GUID("d3ebbd9754eb42746a066ace2a731da6"); // SGEUniversalUnlitSubTarget.cs + + public override int latestVersion => 1; + + public SGEUniversalUnlitSubTarget() + { + displayName = "SGE Unlit"; + } + + protected override SGEShaderID shaderID => SGEShaderID.SGE_Unlit; + + public override bool IsActive() => true; + + public override void Setup(ref TargetSetupContext context) + { + context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency); + + base.Setup(ref context); + + // Process SubShaders + context.AddSubShader(PostProcessSubShader(SubShaders.Unlit(target, target.renderType.ToString(), target.renderQueue.ToString(), target.disableBatching.ToString()))); + } + + public override void ProcessPreviewMaterial(Material material) + { + } + + public override void GetFields(ref TargetFieldContext context) + { + base.GetFields(ref context); + } + + public override void GetActiveBlocks(ref TargetActiveBlockContext context) + { + } + + public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode) + { + } + + public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo) + { + } + + public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap) + { + blockMap = null; + if(!(masterNode is SGEUnlitMasterNode1 sgeUnlitMasterNode)) + return false; + + // Set blockmap + blockMap = new Dictionary() + { + { BlockFields.VertexDescription.Position, 9 }, + { BlockFields.VertexDescription.Normal, 10 }, + { BlockFields.VertexDescription.Tangent, 11 }, + { BlockFields.SurfaceDescription.BaseColor, 0 }, + { BlockFields.SurfaceDescription.Alpha, 7 }, + { BlockFields.SurfaceDescription.AlphaClipThreshold, 8 }, + }; + + return true; + } + + internal override void OnAfterParentTargetDeserialized() + { + Assert.IsNotNull(target); + + if (this.sgVersion < latestVersion) + { + // Upgrade old incorrect Premultiplied blend (with alpha multiply in shader) into + // equivalent Alpha blend mode for backwards compatibility. + if (this.sgVersion < 1) + { + if (target.blendMode == BlendMode.Premultiply) + { + target.blendMode = BlendMode.Alpha; + } + } + ChangeVersion(latestVersion); + } + } + + +#region SubShader + static class SubShaders + { + public static SubShaderDescriptor Unlit(SGEUniversalTarget target, string renderType, string renderQueue, string disableBatchingTag) + { + var result = new SubShaderDescriptor() + { + pipelineTag = UniversalTarget.kPipelineTag, + customTags = UniversalTarget.kUnlitMaterialTypeTag, + renderType = renderType, + renderQueue = renderQueue, + disableBatchingTag = disableBatchingTag, + generatesPreview = true, + passes = new PassCollection() + }; + + result.passes.Add(UnlitPasses.Forward(target, UnlitKeywords.Forward)); + + if (target.zWrite == ZWrite.On) + result.passes.Add(PassVariant(CorePasses.DepthOnly(target), CorePragmas.Instanced)); + + result.passes.Add(PassVariant(UnlitPasses.DepthNormalOnly(target), CorePragmas.Instanced)); + + if (target.castShadows) + result.passes.Add(PassVariant(CorePasses.ShadowCaster(target), CorePragmas.Instanced)); + + // Currently neither of these passes (selection/picking) can be last for the game view for + // UI shaders to render correctly. Verify [1352225] before changing this order. + result.passes.Add(PassVariant(CorePasses.SceneSelection(target), CorePragmas.Default)); + result.passes.Add(PassVariant(CorePasses.ScenePicking(target), CorePragmas.Default)); + + return result; + } + } +#endregion + +#region Pass + static class UnlitPasses + { + public static PassDescriptor Forward(SGEUniversalTarget target, KeywordCollection keywords) + { + var result = new PassDescriptor + { + // Definition + displayName = "SGE Universal Forward", + referenceName = "SHADERPASS_UNLIT", + useInPreview = true, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = CoreBlockMasks.FragmentColorAlpha, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = UnlitRequiredFields.Unlit, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.UberSwitchedRenderState(target), + pragmas = CorePragmas.Forward, + defines = new DefineCollection { CoreDefines.UseFragmentFog }, + keywords = new KeywordCollection { keywords }, + includes = new IncludeCollection { UnlitIncludes.Unlit }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + CorePasses.AddTargetSurfaceControlsToPass(ref result, target); + CorePasses.AddAlphaToMaskControlToPass(ref result, target); + CorePasses.AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + public static PassDescriptor DepthNormalOnly(SGEUniversalTarget target) + { + var result = new PassDescriptor + { + // Definition + displayName = "SGE DepthNormalsOnly", + referenceName = "SHADERPASS_DEPTHNORMALSONLY", + lightMode = "DepthNormalsOnly", + useInPreview = false, + + // Template + passTemplatePath = UniversalTarget.kUberTemplatePath, + sharedTemplateDirectories = UniversalTarget.kSharedTemplateDirectories, + + // Port Mask + validVertexBlocks = CoreBlockMasks.Vertex, + validPixelBlocks = UnlitBlockMasks.FragmentDepthNormals, + + // Fields + structs = CoreStructCollections.Default, + requiredFields = UnlitRequiredFields.DepthNormalsOnly, + fieldDependencies = CoreFieldDependencies.Default, + + // Conditional State + renderStates = CoreRenderStates.DepthNormalsOnly(target), + pragmas = CorePragmas.Forward, + defines = new DefineCollection(), + keywords = new KeywordCollection { CoreKeywordDescriptors.GBufferNormalsOct }, + includes = new IncludeCollection { CoreIncludes.DepthNormalsOnly }, + + // Custom Interpolator Support + customInterpolators = CoreCustomInterpDescriptors.Common + }; + + CorePasses.AddTargetSurfaceControlsToPass(ref result, target); + CorePasses.AddLODCrossFadeControlToPass(ref result, target); + + return result; + } + + #region PortMasks + static class UnlitBlockMasks + { + public static readonly BlockFieldDescriptor[] FragmentDepthNormals = new BlockFieldDescriptor[] + { + BlockFields.SurfaceDescription.NormalWS, + BlockFields.SurfaceDescription.Alpha, + BlockFields.SurfaceDescription.AlphaClipThreshold, + }; + } + #endregion + + + #region RequiredFields + static class UnlitRequiredFields + { + public static readonly FieldCollection Unlit = new FieldCollection() + { + StructFields.Varyings.positionWS, + StructFields.Varyings.normalWS, + }; + + public static readonly FieldCollection DepthNormalsOnly = new FieldCollection() + { + StructFields.Varyings.normalWS, + }; + } + #endregion + } +#endregion + +#region Keywords + static class UnlitKeywords + { + public static readonly KeywordCollection Forward = new KeywordCollection() + { + // This contain lightmaps because without a proper custom lighting solution in Shadergraph, + // people start with the unlit then add lightmapping nodes to it. + // If we removed lightmaps from the unlit target this would ruin a lot of peoples days. + CoreKeywordDescriptors.StaticLightmap, + CoreKeywordDescriptors.DirectionalLightmapCombined, + CoreKeywordDescriptors.SampleGI, + CoreKeywordDescriptors.DBuffer, + CoreKeywordDescriptors.DebugDisplay, + CoreKeywordDescriptors.ScreenSpaceAmbientOcclusion, + }; + } +#endregion + +#region Includes + static class UnlitIncludes + { + const string kUnlitPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl"; + + public static IncludeCollection Unlit = new IncludeCollection + { + // Pre-graph + { CoreIncludes.DOTSPregraph }, + { CoreIncludes.WriteRenderLayersPregraph }, + { CoreIncludes.CorePregraph }, + { CoreIncludes.ShaderGraphPregraph }, + { CoreIncludes.DBufferPregraph }, + + // Post-graph + { CoreIncludes.CorePostgraph }, + { kUnlitPass, IncludeLocation.Postgraph }, + }; + } +#endregion + } +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalUnlitSubTarget.cs.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalUnlitSubTarget.cs.meta new file mode 100644 index 0000000..fa9ca29 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/Plugin_URP/URPAssemblySpecific/Targets/SGEUniversalUnlitSubTarget.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d3ebbd9754eb42746a066ace2a731da6 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/ShaderGraphEssentials.asmref b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/ShaderGraphEssentials.asmref new file mode 100644 index 0000000..6f5b7c2 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/ShaderGraphEssentials.asmref @@ -0,0 +1,3 @@ +{ + "reference": "GUID:be0903cd8e1546f498710afdc59db5eb" +} \ No newline at end of file diff --git a/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/ShaderGraphEssentials.asmref.meta b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/ShaderGraphEssentials.asmref.meta new file mode 100644 index 0000000..5f729c1 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Plugin/Editor/ShaderGraphEssentials.asmref.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 59f1b706f0093e547ab591230fcb6a6f +AssemblyDefinitionReferenceImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/Settings.asset b/Assets/Plugins/ShaderGraphEssentials/Settings.asset new file mode 100644 index 0000000..a26afff --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Settings.asset @@ -0,0 +1,15 @@ +%YAML 1.1 +%TAG !u! tag:unity3d.com,2011: +--- !u!114 &11400000 +MonoBehaviour: + m_ObjectHideFlags: 0 + m_CorrespondingSourceObject: {fileID: 0} + m_PrefabInstance: {fileID: 0} + m_PrefabAsset: {fileID: 0} + m_GameObject: {fileID: 0} + m_Enabled: 1 + m_EditorHideFlags: 0 + m_Script: {fileID: 11500000, guid: f261da61669a6ab4bb6571eae406da7e, type: 3} + m_Name: Settings + m_EditorClassIdentifier: + OpenGettingStartedWindow: 0 diff --git a/Assets/Plugins/ShaderGraphEssentials/Settings.asset.meta b/Assets/Plugins/ShaderGraphEssentials/Settings.asset.meta new file mode 100644 index 0000000..779a5d4 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/Settings.asset.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 676368a571971ac46b79c7bb3a6f03e2 +NativeFormatImporter: + externalObjects: {} + mainObjectFileID: 11400000 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Plugins/ShaderGraphEssentials/ShaderGraphEssentials_Documentation.pdf b/Assets/Plugins/ShaderGraphEssentials/ShaderGraphEssentials_Documentation.pdf new file mode 100644 index 0000000..2aa7ee3 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/ShaderGraphEssentials_Documentation.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:92e20049f560a2f6c5cef16e931d490a48fdcfbacf82fd83f8c8f2faaeaff13c +size 927071 diff --git a/Assets/Plugins/ShaderGraphEssentials/ShaderGraphEssentials_Documentation.pdf.meta b/Assets/Plugins/ShaderGraphEssentials/ShaderGraphEssentials_Documentation.pdf.meta new file mode 100644 index 0000000..16f00a8 --- /dev/null +++ b/Assets/Plugins/ShaderGraphEssentials/ShaderGraphEssentials_Documentation.pdf.meta @@ -0,0 +1,14 @@ +fileFormatVersion: 2 +guid: 9bb8989881f14924bb299f9057d93859 +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: +AssetOrigin: + serializedVersion: 1 + productId: 141671 + packageName: ShaderGraph Essentials + packageVersion: 1.1.17 + assetPath: Assets/Plugins/ShaderGraphEssentials/ShaderGraphEssentials_Documentation.pdf + uploadId: 607369