diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.cs index a6621e271af..95f07ff29ff 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.cs @@ -306,13 +306,13 @@ public BakingBatch(Vector3Int cellCount, ProbeReferenceVolume refVolume) maxBrickCount = cellCount * ProbeReferenceVolume.CellSize(refVolume.GetMaxSubdivision()); inverseScale = ProbeBrickPool.kBrickCellCount / refVolume.MinBrickSize(); offset = refVolume.ProbeOffset(); - + // Initialize NativeHashMaps with reasonable initial capacity // Using a larger capacity to reduce allocations during baking positionToIndex = new NativeHashMap(100000, Allocator.Persistent); uniqueBrickSubdiv = new NativeHashMap(100000, Allocator.Persistent); } - + public void Dispose() { if (positionToIndex.IsCreated) @@ -1098,7 +1098,7 @@ static void BakeDelegate(ref float progress, ref bool done) { FixSeams( s_BakeData.positionRemap, - s_BakeData.originalPositions, + s_BakeData.sortedPositions, s_BakeData.lightingJob.irradiance, s_BakeData.lightingJob.validity, s_BakeData.lightingJob.occlusion, @@ -1323,7 +1323,7 @@ internal static void FixSeams( NativeArray skyOcclusion, NativeArray renderingLayerMasks) { - // Seams are caused are caused by probes on the boundary between two subdivision levels + // Seams are caused by probes on the boundary between two subdivision levels // The idea is to find first them and do a kind of dilation to smooth the values on the boundary // the dilation process consits in doing a trilinear sample of the higher subdivision brick and override the lower subdiv with that // We have to mark the probes on the boundary as valid otherwise leak reduction at runtime will interfere with this method @@ -1443,7 +1443,8 @@ Vector3Int GetCellPositionFromVoxel(Vector3Int voxelToLookup, int cellSizeInBric { uint renderingLayerMask = renderingLayerMasks[positionRemap[index]]; bool commonRenderingLayer = (renderingLayerMask & probeRenderingLayerMask) != 0; - if (!commonRenderingLayer) continue; // We do not use this probe contribution if it does not share at least a common rendering layer + if (!commonRenderingLayer) + continue; // We do not use this probe contribution if it does not share at least a common rendering layer } // Do the lerp in compressed format to match result on GPU @@ -1512,7 +1513,7 @@ static void ApplyPostBakeOperations() var chunkSizeInProbes = ProbeBrickPool.GetChunkSizeInProbeCount(); var hasVirtualOffsets = m_BakingSet.settings.virtualOffsetSettings.useVirtualOffset; var hasRenderingLayers = m_BakingSet.useRenderingLayers; - + if (!ValidateBakingCellsSize(bakingCellsArray, chunkSizeInProbes, hasVirtualOffsets, hasRenderingLayers)) return; // Early exit if validation fails diff --git a/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphViewer.PlayerConnection.cs b/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphViewer.PlayerConnection.cs index 1c608b40cf8..800f7294110 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphViewer.PlayerConnection.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphViewer.PlayerConnection.cs @@ -24,8 +24,6 @@ public PlayerConnection(IConnectionState connectionState, UnityEngine.Events.Uni EditorConnection.instance.Initialize(); EditorConnection.instance.RegisterConnection(m_OnPlayerConnected); EditorConnection.instance.RegisterDisconnection(m_OnPlayerDisconnected); - - EditorApplication.quitting += OnEditorQuitting; } public void Dispose() @@ -35,15 +33,8 @@ public void Dispose() EditorConnection.instance.UnregisterConnection(m_OnPlayerConnected); EditorConnection.instance.UnregisterDisconnection(m_OnPlayerDisconnected); - // NOTE: There is a bug where editor crashes if we call DisconnectAll during shutdown flow. In this case - // it's fine to skip the disconnect as the player will get notified of it anyway. - if (!m_EditorQuitting) - EditorConnection.instance.DisconnectAll(); - m_ConnectionState.Dispose(); m_ConnectionState = null; - - EditorApplication.quitting -= OnEditorQuitting; } } @@ -51,11 +42,6 @@ public void OnConnectionDropdownIMGUI() { PlayerConnectionGUILayout.ConnectionTargetSelectionDropdown(m_ConnectionState, EditorStyles.toolbarDropDown, 250); } - - void OnEditorQuitting() - { - m_EditorQuitting = true; - } } } } diff --git a/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphViewer.cs b/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphViewer.cs index 5a86ad27577..966131197a4 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphViewer.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphViewer.cs @@ -1131,7 +1131,7 @@ void SetSelectedExecutionIndex(int executionIndex) if (m_SelectedExecutionIndex != executionIndex) { m_SelectedExecutionIndex = executionIndex; - UpdateCurrentDebugData(); + UpdateCurrentDebugData(true); } // Using a custom toolbar menu instead of default Dropdown in order to get access to allowDuplicateNames, @@ -2032,7 +2032,7 @@ void UpdateStatusLabel() string connectionStatus = m_IsDeviceConnected ? "Online" : "Offline"; - bool isEditor = m_ConnectedDeviceName == "Editor"; + bool isEditor = m_ConnectedDeviceName == k_EditorName; string sourceLabel = isEditor ? "Source: Editor" : $"Source: {m_ConnectedDeviceName} ({connectionStatus})"; bool hasCapture = HasValidDebugData && m_LastDataCaptureTime != DateTime.MinValue; @@ -2052,7 +2052,8 @@ void UpdateCurrentDebugData(bool force = false) { m_CurrentDebugData = RenderGraphDebugSession.GetDebugData(m_SelectedRenderGraph, selectedExecutionItem.id); - if (HasValidDebugData) + // Update timestamp when we get valid data, or when forcing an update + if (HasValidDebugData || force) m_LastDataCaptureTime = DateTime.Now; } else @@ -2066,6 +2067,8 @@ void UpdateCurrentDebugData(bool force = false) currentGraphDropdown.style.display = DisplayStyle.None; if (currentExecutionToolbarMenu != null) currentExecutionToolbarMenu.style.display = DisplayStyle.None; + + m_LastDataCaptureTime = DateTime.MinValue; } UpdateStatusLabel(); @@ -2170,6 +2173,7 @@ void OnPlayerConnected(int playerID) void OnPlayerDisconnected(int playerID) { m_IsDeviceConnected = false; + m_ConnectedDeviceName = k_EditorName; if (!m_Paused) { diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Debug/RenderGraphDebugSession.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Debug/RenderGraphDebugSession.cs index 8e3192bf2b3..ddca2c9eff5 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Debug/RenderGraphDebugSession.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Debug/RenderGraphDebugSession.cs @@ -158,9 +158,27 @@ public static void EndSession() } } - public static List GetRegisteredGraphs() => s_CurrentDebugSession.debugDataContainer.GetRenderGraphs(); + public static List s_EmptyRegisteredGraphs = new(); + public static List GetRegisteredGraphs() + { + if (s_CurrentDebugSession == null || s_CurrentDebugSession.debugDataContainer == null) + { + return s_EmptyRegisteredGraphs; + } + + return s_CurrentDebugSession.debugDataContainer.GetRenderGraphs(); + } - public static List GetExecutions(string graphName) => s_CurrentDebugSession.debugDataContainer.GetExecutions(graphName); + public static List s_EmptyExecutions = new(); + public static List GetExecutions(string graphName) + { + if (s_CurrentDebugSession == null || s_CurrentDebugSession.debugDataContainer == null) + { + return s_EmptyExecutions; + } + + return s_CurrentDebugSession.debugDataContainer.GetExecutions(graphName); + } public static DebugData GetDebugData(string renderGraph, EntityId executionId) { diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl index ccb2ab7e75d..385c8b994ea 100644 --- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl +++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl @@ -79,7 +79,7 @@ real ConvertLuminanceToEv(real luminance) // Non physically based hack to limit light influence to attenuationRadius. // Square the result to smoothen the function. -real DistanceWindowing(real distSquare, real rangeAttenuationScale, real rangeAttenuationBias) +real DistanceWindowing(float distSquare, real rangeAttenuationScale, real rangeAttenuationBias) { // If (range attenuation is enabled) // rangeAttenuationScale = 1 / r^2 diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Shadow/ShadowSamplingTent.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Shadow/ShadowSamplingTent.hlsl index 53ad393b7f1..a7cd8fdb664 100644 --- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Shadow/ShadowSamplingTent.hlsl +++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Shadow/ShadowSamplingTent.hlsl @@ -106,7 +106,7 @@ void SampleShadow_GetTexelWeights_Tent_7x7(real offset, out real4 texelsWeightsA } // 3x3 Tent filter (45 degree sloped triangles in U and V) -void SampleShadow_ComputeSamples_Tent_3x3(real4 shadowMapTexture_TexelSize, real2 coord, out real fetchesWeights[4], out real2 fetchesUV[4]) +void SampleShadow_ComputeSamples_Tent_3x3(real4 shadowMapTexture_TexelSize, float2 coord, out real fetchesWeights[4], out real2 fetchesUV[4]) { // tent base is 3x3 base thus covering from 9 to 12 texels, thus we need 4 bilinear PCF fetches real2 tentCenterInTexelSpace = coord.xy * shadowMapTexture_TexelSize.zw; @@ -186,7 +186,7 @@ void SampleShadow_ComputeSamples_Tent_3x3(real4 shadowMapTexture_TexelSize, real (fetchesWeights)[8] = fetchesWeightsU.z * fetchesWeightsV.z; \ } -void SampleShadow_ComputeSamples_Tent_5x5(real4 shadowMapTexture_TexelSize, real2 coord, out real fetchesWeights[9], out real2 fetchesUV[9]) +void SampleShadow_ComputeSamples_Tent_5x5(real4 shadowMapTexture_TexelSize, float2 coord, out real fetchesWeights[9], out real2 fetchesUV[9]) { SampleShadow_ComputeSamples_Tent_Filter_5x5(real, shadowMapTexture_TexelSize, coord, fetchesWeights, fetchesUV); } @@ -254,7 +254,7 @@ void SampleShadow_ComputeSamples_Tent_5x5(real4 shadowMapTexture_TexelSize, real -void SampleShadow_ComputeSamples_Tent_7x7(real4 shadowMapTexture_TexelSize, real2 coord, out real fetchesWeights[16], out real2 fetchesUV[16]) +void SampleShadow_ComputeSamples_Tent_7x7(real4 shadowMapTexture_TexelSize, float2 coord, out real fetchesWeights[16], out real2 fetchesUV[16]) { SampleShadow_ComputeSamples_Tent_Filter_7x7(real, shadowMapTexture_TexelSize, coord, fetchesWeights, fetchesUV); } diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/fog-volume-master-stack-reference.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/fog-volume-master-stack-reference.md index b2b0243f3f8..fe1d79b9f6b 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/fog-volume-master-stack-reference.md +++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/fog-volume-master-stack-reference.md @@ -68,4 +68,4 @@ These settings appear when you select the Fog’s material in the Asset window. | **Fog Volume options** | | | | | **Single Scattering Albedo** | Control the color of each fog particle. The fog’s density doesn’t affect this color. | | | **Fog Distance** | Control how far you can see through the fog in meters. This controls how far the light passes through fog to affect how opaque it appears. A value of 0 makes the fog appear opaque. | -| | **Blend mode** | Determine how this fog shader blends with existing fog in the scene. This property overwrites the Blend mode you set in the Surface Options:
• **Overwrite:** Replaces existing fog in the volume area with this fog shader.Presented **content strategy** initiatives to leads in key team meetings.•**Additive:** Adds the color and density of this fog shader to other fog in the scene. This is the default value.
**Multiply:** Multiplies the color and density of this fog shader with other fog in the scene. You can use this to create effects relative to a specific fog density.
• **Min:** Determines the minimum density value of this fog shader and the scene fog inside its bounding box. For example, a value of 0 appears to remove fog in a certain area.
• **Max:** Determines the maximum density value of this fog shader and the scene fog inside its bounding box. | +| | **Blend mode** | Determine how this fog shader blends with existing fog in the scene. This property overwrites the Blend mode you set in the Surface Options:
• **Overwrite:** Replaces existing fog in the volume area with this fog shader.
•**Additive:** Adds the color and density of this fog shader to other fog in the scene. This is the default value.
**Multiply:** Multiplies the color and density of this fog shader with other fog in the scene. You can use this to create effects relative to a specific fog density.
• **Min:** Determines the minimum density value of this fog shader and the scene fog inside its bounding box. For example, a value of 0 appears to remove fog in a certain area.
• **Max:** Determines the maximum density value of this fog shader and the scene fog inside its bounding box. | diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPBuildData.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPBuildData.cs index 17ec4f6a056..efd8bfbdcec 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPBuildData.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPBuildData.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; @@ -17,7 +16,6 @@ internal class HDRPBuildData : IDisposable public List renderPipelineAssets { get; private set; } = new List(); public bool playerNeedRaytracing { get; private set; } public bool stripDebugVariants { get; private set; } = true; - public bool dynamicLightmapsUsed { get; private set; } public bool waterDecalMaskAndCurrent { get; private set; } public Dictionary rayTracingComputeShaderCache { get; private set; } = new(); public Dictionary computeShaderCache { get; private set; } = new(); @@ -71,35 +69,6 @@ public HDRPBuildData(BuildTarget buildTarget, bool isDevelopmentBuild) m_Instance = this; } - public void SetDynamicLightmapsUsedInBuildScenes() - { - dynamicLightmapsUsed = DynamicLightmapsUsedInBuildScenes(); - } - - static bool DynamicLightmapsUsedInBuildScenes() - { - var originalSetup = EditorSceneManager.GetSceneManagerSetup(); - - bool dynamicLightmapsUsed = false; - foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes) - { - if (!scene.enabled) continue; - - EditorSceneManager.OpenScene(scene.path, OpenSceneMode.Single); - - if (Lightmapping.HasDynamicGILightmapTextures()) - { - dynamicLightmapsUsed = true; - break; - } - } - - if (originalSetup.Length > 0) - EditorSceneManager.RestoreSceneManagerSetup(originalSetup); - - return dynamicLightmapsUsed; - } - public void Dispose() { renderPipelineAssets?.Clear(); @@ -107,7 +76,6 @@ public void Dispose() computeShaderCache?.Clear(); playerNeedRaytracing = false; stripDebugVariants = true; - dynamicLightmapsUsed = false; waterDecalMaskAndCurrent = false; buildingPlayerForHDRenderPipeline = false; runtimeShaders = null; diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessBuild.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessBuild.cs index b75c370ff69..5a9a93713c7 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessBuild.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessBuild.cs @@ -33,9 +33,6 @@ public void OnPreprocessBuild(BuildReport report) bool isDevelopmentBuild = (report.summary.options & BuildOptions.Development) != 0; m_BuildData = new HDRPBuildData(EditorUserBuildSettings.activeBuildTarget, isDevelopmentBuild); - // Since the HDRPBuildData instance is used in a lot of places, doing this check here ensures that it is done before the build starts. - m_BuildData.SetDynamicLightmapsUsedInBuildScenes(); - if (m_BuildData.buildingPlayerForHDRenderPipeline) { // Now that we know that we are on HDRP we need to make sure everything is correct, otherwise we break the build. diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessShaders.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessShaders.cs index bc6a6b9754f..c5ff8626778 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessShaders.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/BuildProcessors/HDRPPreprocessShaders.cs @@ -1,4 +1,3 @@ -using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; @@ -71,10 +70,8 @@ protected override bool DoShadersStripper(HDRenderPipelineAsset hdrpAsset, Shade // Remove editor only pass bool isSceneSelectionPass = snippet.passName == "SceneSelectionPass"; bool isScenePickingPass = snippet.passName == "ScenePickingPass"; - - bool isEnlightenSupported = SupportedRenderingFeatures.active.enlighten && ((int)SupportedRenderingFeatures.active.lightmapBakeTypes | (int)LightmapBakeType.Realtime) != 0; - bool metaPassUnused = (snippet.passName == "META") && (!isEnlightenSupported || !HDRPBuildData.instance.dynamicLightmapsUsed); - + bool metaPassUnused = (snippet.passName == "META") && (SupportedRenderingFeatures.active.enlighten == false || + ((int)SupportedRenderingFeatures.active.lightmapBakeTypes | (int)LightmapBakeType.Realtime) == 0); bool editorVisualization = inputData.shaderKeywordSet.IsEnabled(m_EditorVisualization); if (isSceneSelectionPass || isScenePickingPass || metaPassUnused || editorVisualization) return true; diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightEvaluation.hlsl b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightEvaluation.hlsl index b4c5c59a837..4c3b9e0b342 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightEvaluation.hlsl +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightEvaluation.hlsl @@ -464,12 +464,12 @@ float4 EvaluateCookie_Punctual(LightLoopContext lightLoopContext, LightData ligh return cookie; } -real PunctualLightAttenuationWithDistanceModification(real4 distances, real rangeAttenuationScale, real rangeAttenuationBias, +real PunctualLightAttenuationWithDistanceModification(float4 distances, real rangeAttenuationScale, real rangeAttenuationBias, real lightAngleScale, real lightAngleOffset) { - real distSq = distances.y; - real distRcp = distances.z; //distance contains light size modification. See ModifyDistancesForFillLighting - real distProj = distances.w; + float distSq = distances.y; + float distRcp = distances.z; //distance contains light size modification. See ModifyDistancesForFillLighting + float distProj = distances.w; real cosFwd = distProj * rcp(distances.x); //we recompute inv distance here real attenuation = min(distRcp, 1.0 / PUNCTUAL_LIGHT_THRESHOLD); diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute index 0a1d500b406..03040d1409e 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute @@ -61,9 +61,9 @@ RWStructuredBuffer g_logBaseBuffer : register( u3 ); // don't #define MAX_NR_COARSE_ENTRIES LIGHT_CLUSTER_MAX_COARSE_ENTRIES -#define MAX_NR_VISIBLE_LIGHTS 826 // correspond to m_MaxLightsOnScreen in LightLoop.cs +#define MAX_NR_VISIBLE_LIGHTS 4096 // correspond to m_MaxLightsOnScreen in LightLoop.cs -groupshared unsigned int ldsTilePassList[MAX_NR_VISIBLE_LIGHTS]; +groupshared unsigned int ldsTilePassList[MAX_NR_VISIBLE_LIGHTS/32]; groupshared unsigned int coarseList[MAX_NR_COARSE_ENTRIES]; groupshared unsigned int clusterIdxs[MAX_NR_COARSE_ENTRIES/2]; groupshared float4 lightPlanes[4*6]; // Each plane is defined by a float4. 6 planes per light, 4 lights (24 planes) @@ -248,10 +248,9 @@ void LIGHTLISTGEN(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_GroupID) const bool lightSortRequired = g_iNrVisibLights > MAX_NR_COARSE_ENTRIES; // Uniform runtime branch if (lightSortRequired) { - UNITY_LOOP - for(i=t; i> 5], 1u << (ul & (32 - 1))); // ldsTilePassList[ul/32] |= 1u << (ul % 32); else if(uIndex g_vBigTileLightList : register( t4 ); // don't sup RWStructuredBuffer g_vLightList : register( u0 ); // don't support RWBuffer yet in unity #define CATEGORY_LIST_SIZE LIGHTCATEGORY_COUNT -#define MAX_NR_VISIBLE_LIGHTS 826 // correspond to m_MaxLightsOnScreen in LightLoop.cs +#define MAX_NR_VISIBLE_LIGHTS 4096 // correspond to m_MaxLightsOnScreen in LightLoop.cs -groupshared unsigned int ldsTilePassList[MAX_NR_VISIBLE_LIGHTS]; +groupshared unsigned int ldsTilePassList[MAX_NR_VISIBLE_LIGHTS/32]; groupshared unsigned int coarseList[LIGHT_LIST_MAX_COARSE_ENTRIES]; groupshared unsigned int prunedList[LIGHT_LIST_MAX_COARSE_ENTRIES]; // temporarily support room for all 64 while in LDS @@ -160,10 +160,9 @@ void TileLightListGen(uint3 dispatchThreadId : SV_DispatchThreadID, uint threadI const bool lightSortRequired = g_iNrVisibLights > LIGHT_LIST_MAX_COARSE_ENTRIES; // Uniform runtime branch if (lightSortRequired) { - UNITY_LOOP - for(i=t; i> 5], 1u << (ul & (32 - 1))); // ldsTilePassList[ul/32] |= 1u << (ul % 32); else if(uIndex()); @@ -128,6 +131,7 @@ public void NullDiffusionProfileSettingsAreRemovedWhenAddingANewDiffusionProfile } [Test] + [UnityPlatform(exclude = new RuntimePlatform[] { RuntimePlatform.WindowsEditor })] // Unstable: https://jira.unity3d.com/browse/UUM-132689 public void RegisterReferencedDiffusionProfiles() { GraphicsSettings.GetRenderPipelineSettings().autoRegister = true; diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs index cb8e2eba1ba..1820f5fb93d 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using UnityEditor.Build; using UnityEditor.Build.Reporting; -using UnityEditor.SceneManagement; using UnityEngine; using UnityEngine.Rendering.Universal; using UnityEngine.Rendering; @@ -134,7 +133,6 @@ class ShaderBuildPreprocessor : IPreprocessBuildWithReport, IPostprocessBuildWit public static bool s_Strip2DPasses; public static bool s_UseSoftShadowQualityLevelKeywords; public static bool s_StripXRVariants; - public static bool s_UsesDynamicLightmaps; public static List supportedFeaturesList { @@ -435,27 +433,6 @@ private static void GetEveryShaderFeatureAndUpdateURPAssets(List // The path for gathering shader features for normal shader stripping private static void HandleEnabledShaderStripping() { - var originalSetup = EditorSceneManager.GetSceneManagerSetup(); - - bool dynamicLightmapsUsed = false; - foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes) - { - if (!scene.enabled) continue; - - EditorSceneManager.OpenScene(scene.path, OpenSceneMode.Single); - - if (Lightmapping.HasDynamicGILightmapTextures()) - { - dynamicLightmapsUsed = true; - break; - } - } - - if (originalSetup.Length > 0) - EditorSceneManager.RestoreSceneManagerSetup(originalSetup); - - s_UsesDynamicLightmaps = dynamicLightmapsUsed; - s_Strip2DPasses = true; using (ListPool.Get(out List urpAssets)) { diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs index ff90a2ac701..0c69260274c 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs @@ -31,7 +31,6 @@ internal interface IShaderScriptableStrippingData public bool stripUnusedVariants { get; set; } public bool stripUnusedPostProcessingVariants { get; set; } public bool stripUnusedXRVariants { get; set; } - public bool usesDynamicLightmaps { get; set; } public Shader shader { get; set; } public ShaderType shaderType { get; set; } @@ -71,7 +70,6 @@ internal struct StrippingData : IShaderScriptableStrippingData public bool stripUnusedVariants { get; set; } public bool stripUnusedPostProcessingVariants { get; set; } public bool stripUnusedXRVariants { get; set; } - public bool usesDynamicLightmaps { get; set; } public Shader shader { get; set; } public ShaderType shaderType { get => passData.shaderType; set{} } @@ -1064,17 +1062,15 @@ internal bool StripUnusedPass_2D(ref IShaderScriptableStrippingData strippingDat internal bool StripUnusedPass_Meta(ref IShaderScriptableStrippingData strippingData) { - bool isEnlightenSupported = SupportedRenderingFeatures.active.enlighten && ((int)SupportedRenderingFeatures.active.lightmapBakeTypes | (int)LightmapBakeType.Realtime) != 0; - - // Meta pass is needed in the player for Enlighten Precomputed Realtime GI albedo and emission, as well as Surface Cache Global Illumination. + // Meta pass is needed in the player for Enlighten Precomputed Realtime GI albedo and emission. if (strippingData.passType == PassType.Meta) { - if ((!isEnlightenSupported || !strippingData.usesDynamicLightmaps) - + if (SupportedRenderingFeatures.active.enlighten == false + || ((int)SupportedRenderingFeatures.active.lightmapBakeTypes | (int)LightmapBakeType.Realtime) == 0 #if SURFACE_CACHE - && !strippingData.IsShaderFeatureEnabled(ShaderFeatures.SurfaceCache) + || !strippingData.IsShaderFeatureEnabled(ShaderFeatures.SurfaceCache) #endif - ) + ) return true; } return false; @@ -1240,7 +1236,6 @@ public bool CanRemoveVariant([DisallowNull] Shader shader, ShaderSnippetData pas stripUnusedVariants = ShaderBuildPreprocessor.s_StripUnusedVariants, stripUnusedPostProcessingVariants = ShaderBuildPreprocessor.s_StripUnusedPostProcessingVariants, stripUnusedXRVariants = ShaderBuildPreprocessor.s_StripXRVariants, - usesDynamicLightmaps = ShaderBuildPreprocessor.s_UsesDynamicLightmaps, IsHDRDisplaySupportEnabled = PlayerSettings.allowHDRDisplaySupport, IsRenderCompatibilityMode = #if URP_COMPATIBILITY_MODE diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs index fdd8ec33ee8..6431a1b4758 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs @@ -743,7 +743,7 @@ bool SetupForEmptyRendering(bool stripShadowsOffVariants, bool shadowsEnabled, U bool lightHasSoftShadows = shadows != LightShadows.Soft; bool supportsSoftShadows = shadowData.supportsSoftShadows; float softShadows = ShadowUtils.SoftShadowQualityToShaderProperty(light, (supportsSoftShadows && lightHasSoftShadows)); - s_EmptyAdditionalLightIndexToShadowParams[lightIndexToUse] = new Vector4(light.shadowStrength, softShadows, lightType, lightIndexToUse); + s_EmptyAdditionalLightIndexToShadowParams[lightIndexToUse] = new Vector4(light.shadowStrength, softShadows, lightType, c_DefaultShadowParams.w); } else { diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs index 82f6beaed0e..a96d7119a67 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs @@ -615,7 +615,7 @@ internal override void OnRecordRenderGraph(RenderGraph renderGraph, ScriptableRe bool requirePrepass = requirePrepassForTextures || useDepthPriming; // Only use a depth format when we do a prepass directly the cameraDepthTexture. If we do depth priming (ie, prepass to the activeCameraDepth), we don't do a prepass to the texture. Instead, we do a copy from the primed attachment. - bool prepassToCameraDepthTexture = requirePrepassForTextures && !usesDeferredLighting; + bool prepassToCameraDepthTexture = requirePrepassForTextures && !usesDeferredLighting && !useDepthPriming; bool depthTextureIsDepthFormat = prepassToCameraDepthTexture; bool requireCopyFromDepth = requireDepthTexture && !prepassToCameraDepthTexture; diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderScriptableStripperTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderScriptableStripperTests.cs index 8c102078f17..1daee4775bf 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderScriptableStripperTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderScriptableStripperTests.cs @@ -29,7 +29,6 @@ internal struct TestStrippingData : IShaderScriptableStrippingData public bool stripUnusedVariants { get; set; } public bool stripUnusedPostProcessingVariants { get; set; } public bool stripUnusedXRVariants { get; set; } - public bool usesDynamicLightmaps { get; set; } public bool IsHDRDisplaySupportEnabled { get; set; } public bool IsRenderCompatibilityMode { get; set; } @@ -227,7 +226,6 @@ public void TestStripUnusedPass(string shaderName) helper.IsFalse(helper.stripper.StripUnusedPass(ref helper.data)); TestStripUnusedPass_2D(shader); - TestStripUnusedPass_Meta(shader); TestStripUnusedPass_XR(shader); TestStripUnusedPass_ShadowCaster(shader); TestStripUnusedPass_Decals(shader); @@ -250,76 +248,6 @@ public void TestStripUnusedPass_2D(Shader shader) helper.IsTrue(helper.stripper.StripUnusedPass(ref helper.data)); } - public void TestStripUnusedPass_Meta(Shader shader) - { - TestHelper helper; - - bool enlightenPrev = SupportedRenderingFeatures.active.enlighten; - LightmapBakeType lightmapBakeTypesPrev = SupportedRenderingFeatures.active.lightmapBakeTypes; - - SupportedRenderingFeatures.active.enlighten = false; - SupportedRenderingFeatures.active.lightmapBakeTypes = LightmapBakeType.Mixed | LightmapBakeType.Baked; - - helper = new TestHelper(shader, ShaderFeatures.None); - helper.data.usesDynamicLightmaps = false; - helper.data.passType = PassType.Meta; - helper.IsTrue(helper.stripper.StripUnusedPass_Meta(ref helper.data)); - helper.IsTrue(helper.stripper.StripUnusedPass(ref helper.data)); - - SupportedRenderingFeatures.active.enlighten = true; - SupportedRenderingFeatures.active.lightmapBakeTypes = LightmapBakeType.Mixed | LightmapBakeType.Baked; - helper = new TestHelper(shader, ShaderFeatures.None); - helper.data.usesDynamicLightmaps = false; - helper.data.passType = PassType.Meta; - helper.IsTrue(helper.stripper.StripUnusedPass_Meta(ref helper.data)); - helper.IsTrue(helper.stripper.StripUnusedPass(ref helper.data)); - - SupportedRenderingFeatures.active.enlighten = false; - SupportedRenderingFeatures.active.lightmapBakeTypes = LightmapBakeType.Realtime | LightmapBakeType.Mixed | LightmapBakeType.Baked; - helper = new TestHelper(shader, ShaderFeatures.None); - helper.data.usesDynamicLightmaps = false; - helper.data.passType = PassType.Meta; - helper.IsTrue(helper.stripper.StripUnusedPass_Meta(ref helper.data)); - helper.IsTrue(helper.stripper.StripUnusedPass(ref helper.data)); - - SupportedRenderingFeatures.active.enlighten = false; - SupportedRenderingFeatures.active.lightmapBakeTypes = LightmapBakeType.Mixed | LightmapBakeType.Baked; - helper = new TestHelper(shader, ShaderFeatures.None); - helper.data.usesDynamicLightmaps = true; - helper.data.passType = PassType.Meta; - helper.IsTrue(helper.stripper.StripUnusedPass_Meta(ref helper.data)); - helper.IsTrue(helper.stripper.StripUnusedPass(ref helper.data)); - - SupportedRenderingFeatures.active.enlighten = true; - SupportedRenderingFeatures.active.lightmapBakeTypes = LightmapBakeType.Realtime | LightmapBakeType.Mixed | LightmapBakeType.Baked; - helper = new TestHelper(shader, ShaderFeatures.None); - helper.data.usesDynamicLightmaps = true; - helper.data.passType = PassType.Meta; - helper.IsFalse(helper.stripper.StripUnusedPass_Meta(ref helper.data)); - helper.IsFalse(helper.stripper.StripUnusedPass(ref helper.data)); - -#if SURFACE_CACHE - SupportedRenderingFeatures.active.enlighten = false; - SupportedRenderingFeatures.active.lightmapBakeTypes = LightmapBakeType.Mixed | LightmapBakeType.Baked; - helper = new TestHelper(shader, ShaderFeatures.SurfaceCache); - helper.data.usesDynamicLightmaps = false; - helper.data.passType = PassType.Meta; - helper.IsFalse(helper.stripper.StripUnusedPass_Meta(ref helper.data)); - helper.IsFalse(helper.stripper.StripUnusedPass(ref helper.data)); - - SupportedRenderingFeatures.active.enlighten = true; - SupportedRenderingFeatures.active.lightmapBakeTypes = LightmapBakeType.Realtime | LightmapBakeType.Mixed | LightmapBakeType.Baked; - helper = new TestHelper(shader, ShaderFeatures.SurfaceCache); - helper.data.usesDynamicLightmaps = true; - helper.data.passType = PassType.Meta; - helper.IsFalse(helper.stripper.StripUnusedPass_Meta(ref helper.data)); - helper.IsFalse(helper.stripper.StripUnusedPass(ref helper.data)); -#endif - - // Restore previous SupportedRenderingFeatures values - SupportedRenderingFeatures.active.enlighten = enlightenPrev; - SupportedRenderingFeatures.active.lightmapBakeTypes = lightmapBakeTypesPrev; - } public void TestStripUnusedPass_XR(Shader shader) { diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderStripToolTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderStripToolTests.cs index 38376cf5ae7..bdc56e6804f 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderStripToolTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/ShaderStripToolTests.cs @@ -30,7 +30,6 @@ internal struct TestStrippingData : IShaderScriptableStrippingData public bool stripUnusedVariants { get; set; } public bool stripUnusedPostProcessingVariants { get; set; } public bool stripUnusedXRVariants { get; set; } - public bool usesDynamicLightmaps { get; set; } public Shader shader { get; set; } public ShaderType shaderType { get; set; } diff --git a/Packages/com.unity.shadergraph/Documentation~/Graph-Target.md b/Packages/com.unity.shadergraph/Documentation~/Graph-Target.md index 652b6b20eb4..05e4feb18b6 100644 --- a/Packages/com.unity.shadergraph/Documentation~/Graph-Target.md +++ b/Packages/com.unity.shadergraph/Documentation~/Graph-Target.md @@ -10,7 +10,7 @@ Target Settings are specific to each Target, and can vary between assets dependi Typically, each Target you select generates a valid subshader from the graph. For example, a Shader Graph asset with both URP and HDRP Targets will generate two subshaders. When you use a graph that targets multiple render pipelines, you must reimport the Shader Graph asset if you change the active render pipeline. This updates the Material Inspector for any Materials that use your graph. -Shader Graph supports three targets: the [Universal Render Pipeline](https://docs.unity3d.com/Manual/urp/urp-introduction.html), the [High Definition Render Pipeline](https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@12.0/manual/index.html), and the [Built-In Render Pipeline](https://docs.unity3d.com/2020.3/Documentation/Manual/render-pipelines). +Shader Graph supports three targets: the [Universal Render Pipeline](https://docs.unity3d.com/Manual/urp/urp-introduction.html), the [High Definition Render Pipeline](https://docs.unity3d.com/Packages/com.unity.render-pipelines.high-definition@latest/index.html?subfolder=/manual/), and the [Built-In Render Pipeline](https://docs.unity3d.com/Documentation/Manual/built-in-render-pipeline.html). Not all blocks are compatible with all targets. If a block in your graph becomes inactive when you choose a target, that block is not compatible with that target. diff --git a/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Components.md b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Components.md index 0e299ba5875..65bda775d74 100644 --- a/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Components.md +++ b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Components.md @@ -1,129 +1,86 @@ -# Component Subgraphs +# Component sub graph reference -## Components +Explore the Component sub graphs used as building blocks for the [Lighting Model sub graphs](Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md) included in the Custom Lighting sample. -### Apply Decals -This node brings in data from projected decals in the scene. If the Decal component has not been added to the renderer, this node does nothing and does not add cost to the shader. +These sub graphs are available in the [**Create Node** menu](Create-Node-Menu.md) under the **Lighting** > **Components** section. -### Fog -This node adds fog to the object using the Fog parameters in the Environment tab of the Lighting window. It should only be used with the Unlit material type since the other material types automatically add fog. If you use this with anything but the Unlit Master Stack, you end up with double fog. +## General -### Half Angle -This node computes the half angle, which is a vector that is half way between the View Direction vector and the Light Direction vector. It is often used to calculate specular highlights. - -### MainLight -The MainLight node brings in the Direction, Color, and Shadow Attenuation of the main light source in the scene. - -### SmoothnessToSpecPower -For lighting models that use specular power as an input (such as Blinn and Phong), this node converts a smoothness value into a specular power value. +| **Sub graph** | **Description** | +| :--- | :--- | +| **Apply Decals** | Brings in data from projected decals in the scene. If the Decal component has not been added to the renderer, this node does nothing and does not add cost to the shader. | +| **Fog** | Adds fog to the object using the Fog parameters in the Environment tab of the Lighting window. It should only be used with the Unlit material type since the other material types automatically add fog. If you use this with anything but the Unlit Master Stack, you end up with double fog. | +| **Half Angle** | Computes the half angle, which is a vector that is halfway between the View Direction vector and the Light Direction vector. It is often used to calculate specular highlights. | +| **MainLight** | Brings in the Direction, Color, and Shadow Attenuation of the main light source in the scene. | +| **SmoothnessToSpecPower** | Converts a smoothness value into a specular power value, for lighting models that use specular power as an input (such as Blinn and Phong). | ## Additional Lights -The additional lights subgraphs compute the lighting contributions of the additional light sources in the scene. As this lighting data computation requires a `For` loop, these calculations must be done in code in the Custom Function node inside each subgraph. - -### AdditionalLightsBasic -The AdditionalLightsBasic subgraph computes very simple lighting for the additional light sources. Basically just diffuse light with no specular. - -### AdditionalLightsColorize -In addition to outputting the Diffuse, Specular, and Color components like other AdditionalLights nodes, this version also outputs the light attenuation separately so that it can be used outside the subgraph to calculate what areas should be colorized and what areas should be black and white. -### AdditionalLightsHalfLambert -This subgraph node computes the lighting for the additional lights in the scene using the Half Lambert formula which wraps the lighting gradient all the way around to the side of the model opposite the light source. Frequently, stylized lighting models use this type of lighting instead of standard Lambert diffuse. +The Additional Lights sub graphs compute the lighting contributions of the additional light sources in the scene. As this lighting data computation requires a `For` loop, these calculations must be done in code in the Custom Function node inside each sub graph. -### AdditionalLightsSimple -This subgraph node computes lighting using the Blinn formula for specular highlights. This makes the specular highlights cheaper to compute. Blinn specular is generally considered to be less realistic than the default specular that the Universal Render Pipeline uses. - -### AdditionalLightsURP -This subgraph node computes the additional lighting using the same formula used by the Universal Render Pipeline by default. It provides the same type of lighting that you would get when using the standard Lit Master Stack. +| **Sub graph** | **Description** | +| :--- | :--- | +| **AdditionalLightsBasic** | Computes very simple lighting for the additional light sources. It only includes diffuse light with no specular reflection. | +| **AdditionalLightsColorize** | Outputs the Diffuse, Specular, and Color components, and also outputs the light attenuation separately to allow to use it outside the sub graph to calculate what areas should be colorized and what areas should be black and white. | +| **AdditionalLightsHalfLambert** | Computes the lighting for the additional lights in the scene using the Half Lambert formula which wraps the lighting gradient all the way around to the side of the model opposite the light source. | +| **AdditionalLightsSimple** | Computes lighting using the Blinn formula for specular highlights. This makes the specular highlights cheaper to compute. Blinn specular is generally considered to be less realistic than the default specular that the Universal Render Pipeline uses. | +| **AdditionalLightsURP** | Computes the additional lighting using the same formula used by the Universal Render Pipeline by default. It provides the same type of lighting that you would get when using the standard Lit Master Stack. | ## Ambient -### AmbientBasic -The AmbientBasic node computes a very simple ambient term using only the BakedGI node. It does not create reflections as many of the other ambient subgraphs do. - -### AmbientStylized -The AmbientStylized node computes ambient using the Sky, Equator, and Ground colors that are defined in the Lighting window on the Environment tab. It also adds some ambient lighting for the sky using the normal up direction and a Fresnel term. - -### AmbientURP -The AmbientURP node computes ambient light using the same formula as the standard URP lighting mode. - -### SampleReflectionProbes -The SampleReflectionProbes node gets a color sample from the closest reflection probes and blends them together based on the position being rendered. -### ScreenSpaceAmbientOcclusion -The ScreenSpaceAmbientOcclusion node samples the ambient occlusion that is calculated by the Screen Space Ambient Occlusion component on the Renderer Data asset. If the SSAO component is not active on the Renderer, this node simply returns 1. Typically, this value is multiplied by the ambient value so that ambient is darker in occluded areas, but you can use this data as you see fit in your own custom lighting model. +| **Sub graph** | **Description** | +| :--- | :--- | +| **AmbientBasic** | Computes a very simple ambient lighting using only the BakedGI node. It doesn't create any reflections. | +| **AmbientStylized** | Computes ambient lighting using the Sky, Equator, and Ground colors that are defined in the Lighting window on the Environment tab. It also adds some ambient lighting for the sky using the normal up direction and a Fresnel term. | +| **AmbientURP** | Computes ambient light using the same formula as the standard URP lighting mode. | +| **SampleReflectionProbes** | Gets a color sample from the closest reflection probes and blends them together based on the position being rendered. | +| **ScreenSpaceAmbientOcclusion** | Samples the ambient occlusion that is calculated by the Screen Space Ambient Occlusion component on the Renderer Data asset. If the SSAO component is not active on the Renderer, this node simply returns 1. Typically, this value is multiplied by the ambient value so that ambient is darker in occluded areas, but you can use this data as you see fit in your own custom lighting model. | ## Core Models -### LightBasic -The Lit Basic lighting model does very simple lighting and leaves out most lighting features in order to render as fast as possible. It calculates simple diffuse lighting and a simple form of ambient lighting. It does not support fog, reflections, specular, light cookies, or any other lighting features. But it does render fast and is ideal for low-end mobile devices and XR headsets. -### LightColorize -The Colorize lighting model is an example of the type of custom behavior you can create when you can control the lighting model. The main directional light renders the scene in grayscale with no color. Color is introduced with point lights so you can control where the scene has color based on where you place the point lights in the scene. - -### LightSimple -The Lit Simple lighting model is the same as the URP lighting model, except it uses the Blinn formula for the specular highlights. This makes it slightly cheaper to render than standard URP while looking fairly similar. If you still need all of the lighting features (specular, fog, screen space ambient occlusion, reflections, etc), but you want to make the lighting cheaper, this may be a good choice. - -### LightToon -The Lit Toon lighting model uses a Posterize operation to break the smooth lighting gradient into distinct bands of shading. It simulates the look of cartoons where lighting is rendered with distinct colors of paint rather than smooth gradients. - -### LightURP -The Lit URP lighting model closely matches the lighting that the Universal Render Pipeline does by default. If you want to start with the URP lighting and then alter it, this is the node to use. +| **Sub graph** | **Description** | +| :--- | :--- | +| **LightBasic** | Computes very simple lighting and leaves out most lighting features in order to render as fast as possible. It calculates simple diffuse lighting and a simple form of ambient lighting. It does not support fog, reflections, specular, light cookies, or any other lighting features. But it does render fast and is ideal for low-end mobile devices and XR headsets. | +| **LightColorize** | Example of the type of custom behavior you can create when you can control the lighting model. The main directional light renders the scene in grayscale with no color. Color is introduced with point lights so you can control where the scene has color based on where you place the point lights in the scene. | +| **LightSimple** | Same as the URP lighting model, except it uses the Blinn formula for the specular highlights. This makes it slightly cheaper to render than standard URP while looking fairly similar. If you still need all of the lighting features (specular, fog, screen space ambient occlusion, reflections, etc), but you want to make the lighting cheaper, this may be a good choice. | +| **LightToon** | Uses a Posterize operation to break the smooth lighting gradient into distinct bands of shading. It simulates the look of cartoons where lighting is rendered with distinct colors of paint rather than smooth gradients. | +| **LightURP** | Closely matches the lighting that the Universal Render Pipeline does by default. If you want to start with the URP lighting and then alter it, this is the node to use. | ## Debug -### DebugLighting -When added to your lighting model (as seen in the existing examples), this subgraph provides support for the following debug lighting modes (available from the Rendering Debugger window): -* Shadow Cascades -* Lighting Without Normal Maps -* Lighting With Normal Maps -* Reflections -* Reflection With Smoothness -* Global Illumination - -### DebugMaterials -When added to your lighting model (as seen in the existing examples), this subgraph provides support for the following debug material modes (available from the Rendering Debugger window): -* Albedo -* Specular -* Alpha -* Smoothness -* Ambient Occlusion -* Emission -* Normal World Space -* Normal Tangent Space -* Light Complexity -* Metallic -* Sprite Mask -* Rendering Layer Masks -## Diffuse -### DiffuseCustomGradient -Instead of a dot product calculation to generate the lighting gradient, this subgraph uses an input texture gradient. This allows you to paint the lighting as you see fit. +| **Sub graph** | **Description** | +| :--- | :--- | +| **DebugLighting** | Provides support for the following lighting debug modes (available from the [Rendering Debugger window](xref:urp-rendering-debugger-reference)):
  • Shadow Cascades
  • Lighting Without Normal Maps
  • Lighting With Normal Maps
  • Reflections
  • Reflection With Smoothness
  • Global Illumination
| +| **DebugMaterials** | Provides support for the following material debug modes (available from the [Rendering Debugger window](xref:urp-rendering-debugger-reference)):
  • Albedo
  • Specular
  • Alpha
  • Smoothness
  • Ambient Occlusion
  • Emission
  • Normal World Space
  • Normal Tangent Space
  • Light Complexity
  • Metallic
  • Sprite Mask
  • Rendering Layer Masks
| -### DiffuseHalfLambert -The Half Lambert formula that this node uses creates a lighting gradient that goes from 0 to 1 from the dark side of the model to the bright side. Because the gradient wraps all the way around the model instead of just half way (as realistic lighting does), it has a softer, more stylized look. - -### DiffuseLambert -This subgraph creates standard diffuse lighting using the dot product between the surface normal and the light vector. If the two vectors are pointing in the same direction, the surface has a diffuse value of 1. If the two vectors are perpendicular, the surface has a value of 0. The dark side of the model (facing away from the light) is clamped so that the result is also 0. +## Diffuse -### DiffuseOrenNayar -This subgraph uses the Oren Nayar lighting formula which simulates the lighting response of a rough surface like clay or plaster. The math used by this formula is quite expensive when you compare it with the subtle results that it provides, so you may find it sufficient to just use DiffuseLambert instead. +| **Sub graph** | **Description** | +| :--- | :--- | +| **DiffuseCustomGradient** | Uses an input texture gradient instead of a dot product calculation to generate the lighting gradient. This allows you to paint the lighting as you see fit. | +| **DiffuseHalfLambert** | Uses a Half Lambert formula that creates a lighting gradient that goes from 0 to 1 from the dark side to the bright side of the model. Because the gradient wraps all the way around the model instead of just halfway (as realistic lighting does), it has a softer, more stylized look. | +| **DiffuseLambert** | Creates standard diffuse lighting using the dot product between the surface normal and the light vector. If the two vectors are pointing in the same direction, the surface has a diffuse value of 1. If the two vectors are perpendicular, the surface has a value of 0. The dark side of the model (facing away from the light) is clamped so that the result is also 0. | +| **DiffuseOrenNayar** | Uses the Oren Nayar lighting formula which simulates the lighting response of a rough surface like clay or plaster. The math used by this formula is quite expensive when you compare it with the subtle results that it provides, so you may find it sufficient to just use DiffuseLambert instead. | ## Reflectance -### ReflectancePBR -A subgraph that calculates reflectance using a standard physically-based model. -### ReflectanceURP -A subgraph that calculates reflectance using the same formula that URP uses. +| **Sub graph** | **Description** | +| :--- | :--- | +| **ReflectancePBR** | Calculates reflectance using a standard physically-based model. | +| **ReflectanceURP** | Calculates reflectance using the same formula that URP uses. | ## Specular -### SpecularBlinn -This subgraph calculates specular highlights using the Blinn formula. It’s cheaper than a more modern/realistic formula. - -### SpecularCookTorrance -This subgraph calculates specular highlights using the Cook Torrance formula. This method creates specular that works well for brushed metal surfaces. -### SpecularPBR -This subgraph calculates specular highlights using the GGX formula, which is popular in modern PBR lighting models. +| **Sub graph** | **Description** | +| :--- | :--- | +| **SpecularBlinn** | Calculates specular highlights using the Blinn formula. It’s cheaper than a more modern/realistic formula. | +| **SpecularCookTorrance** | Calculates specular highlights using the Cook Torrance formula. This method creates specular highlights that work well for brushed metal surfaces. | +| **SpecularPBR** | Calculates specular highlights using the GGX formula, which is popular in modern PBR lighting models. | +| **SpecularStylized** | Calculates specular highlights in a less realistic, more stylized way. This specular works better for an illustrative style. | +| **SpecularURP** | Calculates specular highlights using the same formula as the lighting that the Universal Render Pipeline uses. | -### SpecularStylized -This subgraph calculates specular highlights in a less realistic, more stylized way. This specular works better for an illustrative style. +## Additional resources -### SpecularURP -This subgraph calculates specular highlights using the same formula as the lighting that the Universal Render Pipeline uses. +* [Introduction to lighting model customization](Shader-Graph-Sample-Custom-Lighting-Introduction.md) +* [Get started with the Custom Lighting sample](Shader-Graph-Sample-Custom-Lighting-Get-Started.md) +* [Lighting Model sub graph reference](Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md) diff --git a/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Get-Started.md b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Get-Started.md new file mode 100644 index 00000000000..e12e7c57273 --- /dev/null +++ b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Get-Started.md @@ -0,0 +1,39 @@ +# Get started with the Custom Lighting sample + +Use the templates and sub graphs included in the **Custom Lighting** sample to get started with lighting model customization in Shader Graph. + +> [!NOTE] +> To use the **Custom Lighting** templates and sub graphs, you first need to [import the sample in your project](ShaderGraph-Samples.md#add-samples). + +## Start from a shader graph template + +To use one of the available Custom Lighting templates as a starting point to customize lighting in a prebuilt shader graph asset, follow these steps: + +1. [Create a shader graph asset from a template](create-shader-graph.md). + +1. In the [template browser](template-browser.md), select one of the templates from the **URP Custom Lighting** section. + +1. Select **Create**. + +1. Open the created shader graph asset in the Shader Graph window if the window doesn't open automatically. + +## Start from an empty shader graph + +To use one of the available Lighting Model sub graphs as a starting point to customize lighting in an empty shader graph asset, follow these steps: + +1. [Create a shader graph asset with a preset target](create-shader-graph.md#create-a-shader-graph-with-a-preset-target) and select **URP** > **Unlit Shader Graph**. + +1. Open the created shader graph asset in the Shader Graph window if the window doesn't open automatically. + +1. Go to the [**Create Node** menu](Create-Node-Menu.md) and add one of the sub graphs from the **Custom Lighting** > **Lighting Models** section. + +1. Connect the **Lit** output port of the added sub graph to the **Base Color** input port of the Master Stack. + +1. To allow the Unlit target to correctly support custom lighting models, set the [Graph Settings](Graph-Settings-Tab.md) as follows: + * Enable **Keep Lighting Variants**. + * Disable **Default Decal Blending** and **Default SSAO**. + +## Additional resources + +* [Create a shader graph asset](Create-Shader-Graph.md) +* [Add and connect nodes](Create-Node-Menu.md) diff --git a/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Introduction.md b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Introduction.md new file mode 100644 index 00000000000..b52c4be8d66 --- /dev/null +++ b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Introduction.md @@ -0,0 +1,41 @@ +# Introduction to lighting model customization with Shader Graph + +You can customize lighting models to do the following: + +* Improve rendering performance. You can remove or simplify one or more types of lighting calculations and sacrifice visual quality for rendering speed. + +* Make your lighting look different from Unity's default lighting. For example, to make your project look like a watercolor painting or a pen and ink drawing. + + +## Lighting model customization examples + +The assets available in the **Custom Lighting** sample allow you to [get started with lighting model customization](Shader-Graph-Sample-Custom-Lighting-Get-Started.md) in different contexts and for various purposes. + +| **Context** | **Description** | **Template** | +| :--- | :--- | :--- | +| Model for devices where performance is critical | With XR or low-end mobile devices where performance is critical, you likely need to reduce the cost of calculations in your shaders. For example, you might skip any fog, specular, reflections, light cookies, or SSAO support and only keep the basics. | [Custom Lighting Basic](Shader-Graph-Sample-Custom-Lighting-Templates.md#custom-lighting-basic) | +| Simplified URP model with performance optimization | If you need to optimize performance in URP, you might want to use a Blinn model, which is similar to the main lighting in URP but slightly cheaper for specular highlights. The Blinn model slightly affects the redering quality but renders faster in most cases. | [Custom Lighting Simple](Shader-Graph-Sample-Custom-Lighting-Templates.md#custom-lighting-simple) | +| Posterization model for cartoon appearance | You can alter the lighting in a shader graph to achieve stylized effects such as posterization, to give the visuals of your project the appearance of a cartoon. | [Custom Lighting Toon](Shader-Graph-Sample-Custom-Lighting-Templates.md#custom-lighting-toon) | +| Lit URP model customization | You might want to explore the process of lighting customization directly from a shader based on the Lit URP model. | [Custom Lighting URP](Shader-Graph-Sample-Custom-Lighting-Templates.md#custom-lighting-urp) | +| Other types of lighting customization | You can use any of the [Lighting Model](Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md) sub graphs available in the **Custom Lighting** sample to create any type of lighting that you need within your own shader graphs. These sub graphs use a recommended pattern that illustrates how Unity expects custom lighting models to be defined. | N/A | + + +## Limitations + +Before you start to customize lighting models with Shader Graph, be aware of the following limitations: + +### Shader Graph doesn't support deferred rendering + +Customizable lighting is only intended to be used when you set the render type to Forward or Forward+ in the Render Asset. + +When you set the render type to Deferred or Deferred+, it's not possible to control the lighting directly in an object’s shader, because the lighting occurs in a pass that is not directly connected to the object's shader. + +If you need to customize lighting in a deferred rendering context, you have to [write shaders in code](xref:um-shader-writing) instead of using Shader Graph. + +### Handling multiple light sources in Shader Graph requires HLSL coding + +To support multiple light sources in Shader Graph, you have to write a small amount of code. + +For the main directional light, you can create custom lighting in Shader Graph without coding. However, the part of the graph that does multiple light calculations requires the use of a [Custom Function node](Custom-Function-Node.md), because Shader Graph doesn’t support `For` loops. + +The sample includes multiple examples of Additional Lights nodes, but if you want to create your own, you need to know a little bit of HLSL coding. diff --git a/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md index e3cfd396a28..7f92aa7db4f 100644 --- a/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md +++ b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md @@ -1,21 +1,46 @@ -# Lighting Models +# Lighting Model sub graph reference -Use any of these subgraphs with the Unlit material type to create lighting that is defined in the Shader Graph. To know how to use these subgraphs, refer to the [main page](Shader-Graph-Sample-Custom-Lighting.md#examples). +Explore the Lighting Model sub graphs used in the [URP Custom Lighting templates](Shader-Graph-Sample-Custom-Lighting-Templates.md) included in the Custom Lighting sample. -All of the following subgraphs include the ApplyDecals subgraph to blend decal data, and the Debug Lighting and Debug Materials subgraph nodes to support the debug rendering modes (available in the Rendering Debugger window). They also include a subgraph from the Core Lighting Models category to define the behavior of the lighting itself as described below. +These sub graphs are available in the [**Create Node** menu](Create-Node-Menu.md) under the **Lighting** > **Light Models** section. -## Lit Basic -The Lit Basic lighting model does very simple lighting and leaves out most lighting features to render as fast as possible. It calculates simple diffuse lighting and a simple form of ambient lighting. It does not support fog, reflections, specular, light cookies, or any other lighting features. But it does render fast and is ideal for low-end mobile devices and XR headsets. +> [!NOTE] +> To use any of these sub graphs, you must include it in a shader graph set up with the **Universal** (URP) target and the **Unlit** material type. -## Lit Colorize -The Colorize lighting model is an example of custom behavior type you can create when you can control the lighting model. The main directional light renders the scene in grayscale with no color. Color is introduced with point lights, which allows you to control where the scene has color based on where you place the point lights in the scene. +## Common sub graph structure -## Lit Simple -The Lit Simple lighting model is the same as the URP lighting model, except it uses the Blinn formula for the specular highlights. This makes it slightly cheaper to render than standard URP while looking fairly similar. If you still need all of the lighting features (specular, fog, screen space ambient occlusion, reflections, etc), but you want to make the lighting cheaper, this may be a good choice. +Each Lighting Model sub graph includes the following: +* The [ApplyDecals](Shader-Graph-Sample-Custom-Lighting-Components.md#general) sub graph, to blend decal data with the original material properties. +* The [Debug Lighting and Debug Materials](Shader-Graph-Sample-Custom-Lighting-Components.md#debug) sub graphs, to support the debug rendering modes (available in the Rendering Debugger window). +* A sub graph from the [Core Models](Shader-Graph-Sample-Custom-Lighting-Components.md#core-models) category, to define the lighting behavior according to the model. -## Lit Toon -The Lit Toon lighting model uses a Posterize operation to break the smooth lighting gradient into distinct bands of shading. It simulates the look of cartoons where lighting is rendered with distinct colors of paint rather than smooth gradients. +> [!NOTE] +> The ApplyDecals, DebugLighting, and DebugMaterials sub graph nodes aren’t strictly required. They enable the decals and debug rendering modes, which are core engine features. When you don't use these features, the corresponding sub graph nodes don't affect your project's performance. -## Lit URP -The Lit URP lighting model closely matches the lighting that the Universal Render Pipeline does by default. If you want to start with the URP lighting and then alter it, this is the node to use. +## Available Lighting Model sub graphs +### Lit Basic + +This lighting model does very simple lighting and leaves out most lighting features to render as fast as possible. It calculates simple diffuse lighting and a simple form of ambient lighting. It does not support fog, reflections, specular, light cookies, or any other lighting features. But it does render fast and is ideal for low-end mobile devices and XR headsets. + +### Lit Colorize + +This lighting model is an example of custom behavior type you can create when you can control the lighting model. The main directional light renders the scene in grayscale with no color. Color is introduced with point lights, which allows you to control where the scene has color based on where you place the point lights in the scene. + +### Lit Simple + +This lighting model is the same as the URP lighting model, except it uses the Blinn formula for the specular highlights. This makes it slightly cheaper to render than standard URP while looking fairly similar. If you still need all of the lighting features (specular, fog, screen space ambient occlusion, reflections, etc), but you want to make the lighting cheaper, this may be a good choice. + +### Lit Toon + +This lighting model uses a Posterize operation to break the smooth lighting gradient into distinct bands of shading. It simulates the look of cartoons where lighting is rendered with distinct colors of paint rather than smooth gradients. + +### Lit URP + +This lighting model closely matches the lighting that the Universal Render Pipeline does by default. If you want to start with the URP lighting and then alter it, this is the node to use. + +## Additional resources + +* [Introduction to lighting model customization](Shader-Graph-Sample-Custom-Lighting-Introduction.md) +* [Get started with the Custom Lighting sample](Shader-Graph-Sample-Custom-Lighting-Get-Started.md) +* [URP Custom Lighting template reference](Shader-Graph-Sample-Custom-Lighting-Templates.md) diff --git a/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Templates.md b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Templates.md new file mode 100644 index 00000000000..a4803fe1b05 --- /dev/null +++ b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting-Templates.md @@ -0,0 +1,29 @@ +# URP Custom Lighting template reference + +Explore the prebuilt URP Custom Lighting shader graph templates included in the Custom Lighting sample. + +> [!NOTE] +> These templates are available in the [template browser](template-browser.md) under the **URP Custom Lighting** section. Don't edit the corresponding assets in the **Assets** > **Samples** > **Shader Graph** folder of your project. + +Each Custom Lighting template includes a specific [Lighting Model sub graph](Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md). + +## Custom Lighting Basic + +This template uses a basic lighting model that calculates diffuse lighting for multiple light sources. To reduce the cost of calculations, this shader does not support fog, specular, reflections, light cookies, and SSAO, but you can reintegrate any of these features if needed. This model makes the lighting as cheap as possible by only including the basic requirements. This type of lighting model is ideal for XR or low-end mobile devices where performance is critical. + +## Custom Lighting Simple + +This template uses a lighting model designed to be similar to the main lighting used by URP. It uses a slightly cheaper Blinn model for specular highlights, which reduces the quality but speeds up the rendering in most cases. + +## Custom Lighting Toon + +This template uses a lighting model that posterizes the lighting to give it the appearance of a cartoon. This shows you how you can alter lighting in the graph to achieve stylized effects that give your project a unique appearance. + +## Custom Lighting URP + +This template uses the same lighting formula as the Lit URP model. You can use it as a starting point if you want to begin with URP as is and then make changes. + +## Additional resources + +* [Introduction to lighting model customization](Shader-Graph-Sample-Custom-Lighting-Introduction.md) +* [Get started with the Custom Lighting sample](Shader-Graph-Sample-Custom-Lighting-Get-Started.md) diff --git a/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting.md b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting.md index be7c2e0ed2d..10402c4e975 100644 --- a/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting.md +++ b/Packages/com.unity.shadergraph/Documentation~/Shader-Graph-Sample-Custom-Lighting.md @@ -1,57 +1,13 @@ # Custom Lighting -![The Shader Graph Custom Lighting Sample: A collection of Shader Graph subgraphs that serve as building blocks for building user interface elements.](images/CustomLightingSample.png) -The Shader Graph Custom Lighting sample shows how you can create your own custom lighting in Shader Graph and provides dozens of example templates, shaders, and subgraphs to help you get started with your own custom lighting. +![An example scene with custom lighting effects.](images/CustomLightingSample.png) - Documentation for this set of samples is broken into two pages: +Use the additional templates and sub graphs provided in the **Custom Lighting** sample to get started with lighting model customization in Shader Graph. -* [Lighting Models](Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md) -* [Components](Shader-Graph-Sample-Custom-Lighting-Components.md) - -## Limitations -Before making your own custom lighting model in Shader Graph, be aware of the following limitations: - -* Customizable lighting is only intended to be used when the render type is set to Forward or Forward+ in the Render Asset. - - When the render type is set to Deferred or Deferred+, it's not possible to control the lighting directly in an object’s shader, because the lighting occurs in a pass that is not directly connected to the object's shader. - - If you need to customize lighting in deferred rendering context, you have to write code instead of using Shader Graph. - -* To support multiple light sources, you have to write a small amount of code. - - For the main directional light, you can create custom lighting 100% in Shader Graph. However, the part of the graph that does multiple light calculations requires the use of a Custom Function node, because Shader Graph doesn’t support `For` loops. - - The sample includes multiple examples of Additional Lights nodes, but if you want to create your own, you need to know a little bit of HLSL coding. - - -## Motivations -There are two main reasons you might want to customize the lighting model in Shader Graph: - -* Improve rendering performance by leaving out one or more types of lighting calculations, sacrificing visual quality for rendering speed. - -* Make your lighting look different from the lighting that Unity already provides. For example, you might want your project to look like a watercolor painting, like it’s drawn with pen and ink, etc. - -## Examples -The sample includes the following subgraph examples in the Shader Graph node library: - -* Lighting / Light Models / Lit Basic -* Lighting / Light Models / Lit Colorize -* Lighting / Light Models / Lit Simple -* Lighting / Light Models / Lit Toon -* Lighting / Light Models / Lit URP - -To get customized lighting with any of these subgraphs: -1. Add the subgraph to an empty Shader Graph. -1. Connect the Lit output port to the Base Color input port on the Unlit Master Stack. -1. To allow the Unlit target to correctly support custom lighting models, make sure to set the Graph inspector as follows: - * Enable *Keep Lighting Variants*. - * Disable *Default Decal Blending* and *Default SSAO*. - -Notice that each of the above subgraphs use the following: -* The ApplyDecals subgraph to blend decal data with the original material properties. -* The Debug Lighting and Debug Materials subgraph nodes to support the debug rendering modes (available in the Rendering Debugger window). -* A subgraph from the Core Lighting Models category to define the behavior of the lighting itself. - -While the ApplyDecals, DebugLighting, and DebugMaterials subgraph nodes aren’t strictly required, they are included in the lighting model subgraphs to enable these core engine features: decals and debug rendering modes. When these features are not in use, the ApplyDecals, DebugLighting, and DebugMaterials subgraph nodes don't add any performance cost to the shader overall. You can use them without worrying that you’re slowing down your project. - -You can create any type of lighting that you want, but the above subgraphs show you a recommended pattern to illustrate how Unity expects custom lighting models to be defined. +| **Topic** | **Description** | +| :--- | :--- | +| [Introduction to lighting model customization with Shader Graph](Shader-Graph-Sample-Custom-Lighting-Introduction.md) | Learn about the purpose and limitations of lighting model customization in Shader Graph and get an overview of the use cases covered in the **Custom Lighting** sample. | +| [Get started with the Custom Lighting sample](Shader-Graph-Sample-Custom-Lighting-Get-Started.md) | Start your lighting customization from either a prebuilt shader graph template or a lighting model sub graph in your own shader graph. | +| [URP Custom Lighting template reference](Shader-Graph-Sample-Custom-Lighting-Templates.md) | Explore the prebuilt shader graph templates included in the sample. | +| [Lighting Model sub graph reference](Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md) | Explore the Lighting Model sub graphs included in the sample and used in the URP Custom Lighting templates. | +| [Component sub graph reference](Shader-Graph-Sample-Custom-Lighting-Components.md) | Explore the Component sub graphs used as building blocks for the Lighting Model sub graphs included in the sample. | diff --git a/Packages/com.unity.shadergraph/Documentation~/TableOfContents.md b/Packages/com.unity.shadergraph/Documentation~/TableOfContents.md index 9bc453d206a..87fdf746e71 100644 --- a/Packages/com.unity.shadergraph/Documentation~/TableOfContents.md +++ b/Packages/com.unity.shadergraph/Documentation~/TableOfContents.md @@ -353,8 +353,11 @@ * [How to make shapes that adapt to the aspect ratio of the UI element](Shader-Graph-Sample-UGUI-Shaders-How-tos-aspect-ratio.md) * [Notes on performance](Shader-Graph-Sample-UGUI-Shaders-Notes-on-performance.md) * [Custom Lighting](Shader-Graph-Sample-Custom-Lighting.md) - * [Lighting Models](Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md) - * [Components](Shader-Graph-Sample-Custom-Lighting-Components.md) + * [Introduction to lighting model customization](Shader-Graph-Sample-Custom-Lighting-Introduction.md) + * [Get started with the Custom Lighting sample](Shader-Graph-Sample-Custom-Lighting-Get-Started.md) + * [URP Custom Lighting template reference](Shader-Graph-Sample-Custom-Lighting-Templates.md) + * [Lighting Model sub graph reference](Shader-Graph-Sample-Custom-Lighting-Lighting-Models.md) + * [Component sub graph reference](Shader-Graph-Sample-Custom-Lighting-Components.md) * [Terrain Shaders](Shader-Graph-Sample-Terrain.md) * [Texture Packing Schemes](Shader-Graph-Sample-Terrain-Packing.md) * [Shaders](Shader-Graph-Sample-Terrain-Shaders.md) diff --git a/Packages/com.unity.shadergraph/Editor/Drawing/Views/MaterialNodeView.cs b/Packages/com.unity.shadergraph/Editor/Drawing/Views/MaterialNodeView.cs index c1848a12847..830d0220222 100644 --- a/Packages/com.unity.shadergraph/Editor/Drawing/Views/MaterialNodeView.cs +++ b/Packages/com.unity.shadergraph/Editor/Drawing/Views/MaterialNodeView.cs @@ -334,6 +334,9 @@ void OnSubGraphDoubleClick(MouseDownEvent evt) var path = AssetDatabase.GUIDToAssetPath(subgraphNode.subGraphGuid); ShaderGraphImporterEditor.ShowGraphEditWindow(path); + + // Stop the double click event from starting a drag action on the node + evt.StopImmediatePropagation(); } } diff --git a/Packages/com.unity.visualeffectgraph/Runtime/Utilities/SDF/MeshToSDFBaker.cs b/Packages/com.unity.visualeffectgraph/Runtime/Utilities/SDF/MeshToSDFBaker.cs index f2d153559e5..b42134eb6b5 100644 --- a/Packages/com.unity.visualeffectgraph/Runtime/Utilities/SDF/MeshToSDFBaker.cs +++ b/Packages/com.unity.visualeffectgraph/Runtime/Utilities/SDF/MeshToSDFBaker.cs @@ -39,6 +39,7 @@ private GraphicsBuffer private int m_nStepsJFA; private Kernels m_Kernels; private Mesh m_Mesh; + private bool m_OwnsMesh; private RenderTexture m_textureVoxel, m_textureVoxelBis, m_DistanceTexture; private GraphicsBuffer m_bufferVoxel; private ComputeShader m_computeShader; @@ -173,6 +174,28 @@ public Vector3 GetActualBoxSize() return m_SizeBox; } + private MeshToSDFBaker(Vector3 sizeBox, + Vector3 center, + int maxRes, + Mesh mesh, + bool ownsMesh, + int signPassesCount, + float threshold, + float sdfOffset, + CommandBuffer cmd) + { + LoadRuntimeResources(); + m_Mesh = mesh; + m_OwnsMesh = ownsMesh; + if (cmd != null) + { + m_Cmd = cmd; + m_OwnsCommandBuffer = false; + } + SetParameters(sizeBox, center, maxRes, signPassesCount, threshold, sdfOffset); + Init(); + } + /// /// Constructor of the class MeshToSDFBaker. /// @@ -191,17 +214,9 @@ public MeshToSDFBaker(Vector3 sizeBox, int signPassesCount = 1, float threshold = 0.5f, float sdfOffset = 0.0f, - CommandBuffer cmd = null) + CommandBuffer cmd = null) : + this(sizeBox, center, maxRes, mesh, false, signPassesCount, threshold, sdfOffset, cmd) { - LoadRuntimeResources(); - m_Mesh = mesh; - if (cmd != null) - { - m_Cmd = cmd; - m_OwnsCommandBuffer = false; - } - SetParameters(sizeBox, center, maxRes, signPassesCount, threshold, sdfOffset); - Init(); } /// @@ -225,8 +240,10 @@ public MeshToSDFBaker(Vector3 sizeBox, float threshold = 0.5f, float sdfOffset = 0.0f, CommandBuffer cmd = null) : - this(sizeBox, center, maxRes, InitMeshFromList(meshes, transforms), signPassesCount, threshold, sdfOffset, cmd) + this(sizeBox, center, maxRes, InitMeshFromList(meshes, transforms), true, signPassesCount, threshold, sdfOffset, cmd) { + if (!m_OwnsMesh) + throw new InvalidOperationException("InitMeshFromList expects owns mesh flag to prevent leak"); } /// @@ -240,6 +257,23 @@ public MeshToSDFBaker(Vector3 sizeBox, } } + private void Reinit(Vector3 sizeBox, + Vector3 center, + int maxRes, + Mesh mesh, + bool ownsMesh, + int signPassesCount = 1, + float threshold = 0.5f, + float sdfOffset = 0.0f) + { + ReleaseMeshIfOwned(); + m_Mesh = mesh; + m_OwnsMesh = ownsMesh; + + SetParameters(sizeBox, center, maxRes, signPassesCount, threshold, sdfOffset); + Init(); + } + /// /// Reinitialize the baker with the new mesh and provided parameters. /// @@ -258,9 +292,7 @@ public void Reinit(Vector3 sizeBox, float threshold = 0.5f, float sdfOffset = 0.0f) { - m_Mesh = mesh; - SetParameters(sizeBox, center, maxRes, signPassesCount, threshold, sdfOffset); - Init(); + Reinit(sizeBox, center, maxRes, mesh, false, signPassesCount, threshold, sdfOffset); } /// @@ -283,7 +315,9 @@ public void Reinit(Vector3 sizeBox, float threshold = 0.5f, float sdfOffset = 0.0f) { - Reinit(sizeBox, center, maxRes, InitMeshFromList(meshes, transforms), signPassesCount, threshold, sdfOffset); + Reinit(sizeBox, center, maxRes, InitMeshFromList(meshes, transforms), true, signPassesCount, threshold, sdfOffset); + if (!m_OwnsMesh) + throw new InvalidOperationException("InitMeshFromList expects owns mesh flag to prevent leak"); } private void SetParameters(Vector3 sizeBox, Vector3 center, int maxRes, int signPassesCount, float threshold, float sdfOffset) @@ -773,7 +807,6 @@ public void BakeSDF() private void InitMeshBuffers() { - if (m_Mesh.GetVertexAttributeFormat(VertexAttribute.Position) != VertexAttributeFormat.Float32) { throw new ArgumentException( @@ -958,9 +991,22 @@ private void PerformDistanceTransformWinding() m_Cmd.EndSample("BakeSDF.DistanceTransform"); } + private void ReleaseMeshIfOwned() + { + if (m_Mesh && m_OwnsMesh) + { + if (Application.isPlaying) + Object.Destroy(m_Mesh); + else + Object.DestroyImmediate(m_Mesh); + m_Mesh = null; + m_OwnsMesh = false; + } + } + private void ReleaseBuffersAndTextures() { - //Release textures. + //Release textures. ReleaseRenderTexture(ref m_textureVoxel); ReleaseRenderTexture(ref m_textureVoxelBis); ReleaseRenderTexture(ref m_DistanceTexture); @@ -979,7 +1025,7 @@ private void ReleaseBuffersAndTextures() ReleaseRenderTexture(ref m_RayMaps[i]); } - //Release buffers. + //Release buffers. ReleaseGraphicsBuffer(ref m_bufferVoxel); ReleaseGraphicsBuffer(ref m_TrianglesUV); ReleaseGraphicsBuffer(ref m_TrianglesInVoxels); @@ -1002,6 +1048,7 @@ private void ReleaseBuffersAndTextures() /// public void Dispose() { + ReleaseMeshIfOwned(); ReleaseBuffersAndTextures(); GC.SuppressFinalize(this); m_IsDisposed = true; diff --git a/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/Tests/HDRP_VisualEffectsGraph_GraphicsTests.cs b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/Tests/HDRP_VisualEffectsGraph_GraphicsTests.cs index 62866c6a42b..51cc6b0e945 100644 --- a/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/Tests/HDRP_VisualEffectsGraph_GraphicsTests.cs +++ b/Tests/SRPTests/Projects/VisualEffectGraph_HDRP/Assets/Tests/HDRP_VisualEffectsGraph_GraphicsTests.cs @@ -35,6 +35,7 @@ public class VFXGraphicsTests [IgnoreGraphicsTest("StressTestRuntime_GPUEvent", "No reference images provided")] [IgnoreGraphicsTest("Timeline_FirstFrame", "No reference images provided")] [IgnoreGraphicsTest("NamedObject_ExposedProperties", "No reference images provided")] + [IgnoreGraphicsTest("35_ShaderGraphGenerationFTP", "https://jira.unity3d.com/browse/UUM-131997", runtimePlatforms: new RuntimePlatform[] { RuntimePlatform.WindowsEditor }, graphicsDeviceTypes: new GraphicsDeviceType[] { GraphicsDeviceType.Direct3D12 })] [MockHmdSetup(99)] [AssetBundleSetup]