diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.LightTransport.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.LightTransport.cs index 02db2704c1b..884a58f0ae8 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.LightTransport.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.LightTransport.cs @@ -668,7 +668,7 @@ static void UpdateLightStatus() var sceneLights = new Dictionary>(); // Modify each baked light, take note of which scenes they belong to. - var allLights = Object.FindObjectsByType(FindObjectsSortMode.None); + var allLights = Object.FindObjectsByType(); foreach (var light in allLights) { if (light.lightmapBakeType != LightmapBakeType.Realtime) diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.Placement.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.Placement.cs index cc44edcc970..325d9f899f8 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.Placement.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeGIBaking.Placement.cs @@ -73,7 +73,9 @@ internal static List GetPerSceneDataList() internal static List GetProbeVolumeList() { + #pragma warning disable CS0618 // Type or member is obsolete var fullPvList = GameObject.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete List usedPVList; if (isBakingSceneSubset) 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 c4de5688616..3d3f66c16fd 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) @@ -746,7 +746,9 @@ static internal void Clear() if (activeSet != null) activeSet.Clear(); + #pragma warning disable CS0618 // Type or member is obsolete var probeVolumes = GameObject.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete foreach (var probeVolume in probeVolumes) probeVolume.OnLightingDataAssetCleared(); } @@ -879,7 +881,9 @@ static void CellCountInDirections(out Vector3Int minCellPositionXYZ, out Vector3 static TouchupVolumeWithBoundsList GetAdjustementVolumes() { // This is slow, but we should have very little amount of touchup volumes. +#pragma warning disable CS0618 // Type or member is obsolete var touchupVolumes = Object.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete var touchupVolumesAndBounds = new TouchupVolumeWithBoundsList(touchupVolumes.Length); foreach (var touchup in touchupVolumes) @@ -1098,7 +1102,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 +1327,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 +1447,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 +1517,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/Lighting/ProbeVolume/ProbeSubdivisionContext.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeSubdivisionContext.cs index f54e06a7637..95a39346313 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeSubdivisionContext.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeSubdivisionContext.cs @@ -42,7 +42,9 @@ static void UpdateRealtimeSubdivisionDebug() if (Time.realtimeSinceStartupAsDouble - s_LastSubdivisionTime > debugDisplay.subdivisionDelayInSeconds) { + #pragma warning disable CS0618 // Type or member is obsolete var probeVolume = GameObject.FindFirstObjectByType(); +#pragma warning restore CS0618 // Type or member is obsolete if (probeVolume == null || !probeVolume.isActiveAndEnabled) return; diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeLightingTab.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeLightingTab.cs index bb2045301a0..00ccbcd4fea 100644 --- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeLightingTab.cs +++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeLightingTab.cs @@ -1216,7 +1216,9 @@ internal class ProbeVolumeOverlay : Overlay, ITransientOverlay { if (ProbeReferenceVolume.instance.probeVolumeDebug.realtimeSubdivision) { + #pragma warning disable CS0618 // Type or member is obsolete var probeVolume = GameObject.FindFirstObjectByType(); +#pragma warning restore CS0618 // Type or member is obsolete if (probeVolume != null && probeVolume.isActiveAndEnabled) { var profile = ProbeVolumeBakingSet.GetBakingSetForScene(probeVolume.gameObject.scene); 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/Runtime/Debugging/DebugManager.cs b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugManager.cs index f519eb4d8fe..15d06a39036 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugManager.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugManager.cs @@ -227,7 +227,9 @@ void EnsurePersistentCanvas() { if (m_RootUIPersistentCanvas == null) { + #pragma warning disable CS0618 // Type or member is obsolete var uiManager = UnityObject.FindFirstObjectByType(); +#pragma warning restore CS0618 // Type or member is obsolete if (uiManager == null) { diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugUpdater.cs b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugUpdater.cs index 688181e1c68..098b8293310 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugUpdater.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugUpdater.cs @@ -80,7 +80,7 @@ internal static void HandleInternalEventSystemComponents(bool uiEnabled) void EnsureExactlyOneEventSystem() { - var eventSystems = FindObjectsByType(FindObjectsSortMode.None); + var eventSystems = FindObjectsByType(); var debugEventSystem = GetComponent(); if (eventSystems.Length > 1 && debugEventSystem != null) diff --git a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/GPUResidentDrawer.cs b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/GPUResidentDrawer.cs index 798ba16771a..b0ad70a10aa 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/GPUResidentDrawer.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/GPUResidentDrawer.cs @@ -924,12 +924,12 @@ private unsafe struct FindRenderersFromMaterialOrMeshJob : IJobParallelForBatch public void Execute(int startIndex, int count) { - int* renderersToAddForMaterialsPtr = stackalloc int[k_BatchSize]; - var renderersToAddForMaterials = new UnsafeList(renderersToAddForMaterialsPtr, k_BatchSize); + EntityId* renderersToAddForMaterialsPtr = stackalloc EntityId[k_BatchSize]; + var renderersToAddForMaterials = new UnsafeList(renderersToAddForMaterialsPtr, k_BatchSize); renderersToAddForMaterials.Length = 0; - int* renderersToAddForMeshesPtr = stackalloc int[k_BatchSize]; - var renderersToAddForMeshes = new UnsafeList(renderersToAddForMeshesPtr, k_BatchSize); + EntityId* renderersToAddForMeshesPtr = stackalloc EntityId[k_BatchSize]; + var renderersToAddForMeshes = new UnsafeList(renderersToAddForMeshesPtr, k_BatchSize); renderersToAddForMeshes.Length = 0; for (int index = 0; index < count; index++) @@ -945,9 +945,7 @@ public void Execute(int startIndex, int count) var meshID = meshIDArray[rendererIndex]; if (meshIDs.Contains(meshID)) { -#pragma warning disable 618 // todo @emilie.thaulow make renderID an EntityId renderersToAddForMeshes.AddNoResize(rendererID); -#pragma warning restore 618 // We can skip the material check if we found a mesh match since at this point // the renderer is already added and will be processed by the mesh branch continue; diff --git a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/InstanceCuller.cs b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/InstanceCuller.cs index 3974f0525da..b5a27c8446f 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/InstanceCuller.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/InstanceCuller.cs @@ -1281,7 +1281,7 @@ internal enum FilteringJobMode internal unsafe struct DrawCommandOutputFiltering : IJob { [ReadOnly] public NativeParallelHashMap batchIDs; - [ReadOnly] public int viewID; + [ReadOnly] public EntityId viewID; [ReadOnly] public GPUInstanceDataBuffer.ReadOnly instanceDataBuffer; @@ -1816,10 +1816,8 @@ private JobHandle AnimateCrossFades(CPUPerCameraInstanceData perCameraInstanceDa } //For main camera, animate crossfades, and store the result in the hashmap to be retrieved by other cameras - var viewID = cc.viewID.GetInstanceID(); -#pragma warning disable 618 // todo @emilie.thaulow make viewID an EntityId - hasAnimatedCrossfade = perCameraInstanceData.perCameraData.TryGetValue(viewID, out var tmpCameraInstanceData); -#pragma warning restore 618 + var viewID = cc.viewID; + hasAnimatedCrossfade = perCameraInstanceData.perCameraData.TryGetValue(viewID.GetEntityId(), out var tmpCameraInstanceData); if (hasAnimatedCrossfade == false) { // For picking / filtering and outlining passes. We do not have animated crossfade data. @@ -1836,9 +1834,7 @@ private JobHandle AnimateCrossFades(CPUPerCameraInstanceData perCameraInstanceDa crossFadeArray = cameraInstanceData.crossFades }.Schedule(perCameraInstanceData.instancesLength, AnimateCrossFadeJob.k_BatchSize); -#pragma warning disable 618 // todo @emilie.thaulow make viewID an EntityId - m_LODParamsToCameraID.TryAdd(lodHash, new AnimatedFadeData(){ cameraID = viewID, jobHandle = handle}); -#pragma warning restore 618 + m_LODParamsToCameraID.TryAdd(lodHash, new AnimatedFadeData(){ cameraID = viewID.GetEntityId(), jobHandle = handle}); return handle; } @@ -1868,10 +1864,8 @@ private unsafe JobHandle CreateFrustumCullingJob( InstanceCullerBurst.SetupCullingJobInput(QualitySettings.lodBias, QualitySettings.meshLodThreshold, contextPtr, &receiverPlanes, &receiverSphereCuller, &frustumPlaneCuller, &screenRelativeMetric, &meshLodConstant); } -#pragma warning disable 618 // todo @emilie.thaulow make GetInstanceID return EntityId if (occlusionCullingCommon != null) - occlusionCullingCommon.UpdateSilhouettePlanes(cc.viewID.GetInstanceID(), receiverPlanes.SilhouettePlaneSubArray()); -#pragma warning restore 618 + occlusionCullingCommon.UpdateSilhouettePlanes(cc.viewID.GetEntityId(), receiverPlanes.SilhouettePlaneSubArray()); var jobHandle = AnimateCrossFades(perCameraInstanceData, cc, out var cameraInstanceData, out var hasAnimatedCrossfade); @@ -2012,9 +2006,7 @@ public unsafe JobHandle CreateCullJobTree( int debugCounterBaseIndex = -1; if (m_DebugStats?.enabled ?? false) { -#pragma warning disable 618 // todo @emilie.thaulow make GetInstanceID return EntityId - debugCounterBaseIndex = m_SplitDebugArray.TryAddSplits(cc.viewType, cc.viewID.GetInstanceID(), cc.cullingSplits.Length); -#pragma warning restore 618 + debugCounterBaseIndex = m_SplitDebugArray.TryAddSplits(cc.viewType, cc.viewID.GetEntityId(), cc.cullingSplits.Length); } var batchCount = drawInstanceData.drawBatches.Length; @@ -2030,16 +2022,12 @@ public unsafe JobHandle CreateCullJobTree( var binVisibleInstanceOffsets = new NativeArray(maxBinCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); int indirectContextIndex = -1; -#pragma warning disable 618 //todo @emilie.thaulow make GetInstanceID return EntityId - bool useOcclusionCulling = (occlusionCullingCommon != null) && occlusionCullingCommon.HasOccluderContext(cc.viewID.GetInstanceID()); -#pragma warning restore 618 + bool useOcclusionCulling = (occlusionCullingCommon != null) && occlusionCullingCommon.HasOccluderContext(cc.viewID.GetEntityId()); if (useOcclusionCulling) { -#pragma warning disable 618 // todo @emilie.thaulow make GetInstanceID return EntityId - int viewInstanceID = cc.viewID.GetInstanceID(); - indirectContextIndex = m_IndirectStorage.TryAllocateContext(viewInstanceID); -#pragma warning restore 618 - cullingOutput.customCullingResult[0] = (IntPtr)viewInstanceID; + EntityId viewEntityId = cc.viewID.GetEntityId(); + indirectContextIndex = m_IndirectStorage.TryAllocateContext(viewEntityId); + cullingOutput.customCullingResult[0] = (IntPtr)viewEntityId.GetRawData(); } IndirectBufferLimits indirectBufferLimits = m_IndirectStorage.GetLimits(indirectContextIndex); NativeArray indirectBufferAllocInfo = m_IndirectStorage.GetAllocInfoSubArray(indirectContextIndex); @@ -2201,7 +2189,7 @@ private JobHandle CreateFilteringCullingOutputJob_EditorOnly(in BatchCullingCont var drawOutputJob = new DrawCommandOutputFiltering { - viewID = cc.viewID.GetInstanceID(), + viewID = cc.viewID.GetEntityId(), batchIDs = batchIDs, instanceDataBuffer = instanceDataBuffer, rendererVisibilityMasks = rendererVisibilityMasks, @@ -2244,7 +2232,7 @@ private JobHandle CreatePickingCullingOutputJob_EditorOnly(in BatchCullingContex var drawOutputJob = new DrawCommandOutputFiltering { - viewID = cc.viewID.GetInstanceID(), + viewID = cc.viewID.GetEntityId(), batchIDs = batchIDs, instanceDataBuffer = instanceDataBuffer, rendererVisibilityMasks = rendererVisibilityMasks, diff --git a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/InstanceCullingBatcher.cs b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/InstanceCullingBatcher.cs index 4a805041462..759b23b271a 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/InstanceCullingBatcher.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/InstanceCullingBatcher.cs @@ -229,8 +229,8 @@ internal struct FindNonRegisteredMaterialsJob : IJobParallelForBatch public unsafe void Execute(int startIndex, int count) { - int* notFoundinstanceIDsPtr = stackalloc int[k_BatchSize]; - var notFoundinstanceIDs = new UnsafeList(notFoundinstanceIDsPtr, k_BatchSize); + EntityId* notFoundinstanceIDsPtr = stackalloc EntityId[k_BatchSize]; + var notFoundinstanceIDs = new UnsafeList(notFoundinstanceIDsPtr, k_BatchSize); GPUDrivenPackedMaterialData* notFoundPackedMaterialDatasPtr = stackalloc GPUDrivenPackedMaterialData[k_BatchSize]; var notFoundPackedMaterialDatas = new UnsafeList(notFoundPackedMaterialDatasPtr, k_BatchSize); @@ -244,9 +244,7 @@ public unsafe void Execute(int startIndex, int count) if (!hashMap.ContainsKey(entityId)) { -#pragma warning disable 618 // todo @emilie.thaulow fix this notFoundinstanceIDs.AddNoResize(entityId); -#pragma warning restore 618 notFoundPackedMaterialDatas.AddNoResize(packedMaterialDatas[i]); } } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBakingSet.Editor.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBakingSet.Editor.cs index a8534637637..6a88f0f9b54 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBakingSet.Editor.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeBakingSet.Editor.cs @@ -525,7 +525,7 @@ static void InflateBound(ref Bounds bounds, ProbeVolume pv) internal void UpdateSceneBounds(Scene scene, string sceneGUID, bool onSceneSave) { - var volumes = FindObjectsByType(FindObjectsSortMode.None); + var volumes = FindObjectsByType(); float prevBrickSize = ProbeReferenceVolume.instance.MinBrickSize(); int prevMaxSubdiv = ProbeReferenceVolume.instance.GetMaxSubdivision(); Vector3 prevOffset = ProbeReferenceVolume.instance.ProbeOffset(); diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeGIContributor.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeGIContributor.cs index 83e44b9319c..5537ab50e3f 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeGIContributor.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumeGIContributor.cs @@ -196,7 +196,9 @@ void PushTerrain(Terrain terrain) } else { + #pragma warning disable CS0618 // Type or member is obsolete var renderers = Object.FindObjectsByType(FindObjectsSortMode.InstanceID); + #pragma warning restore CS0618 // Type or member is obsolete Profiling.Profiler.BeginSample($"Find Renderers ({renderers.Length})"); foreach (var renderer in renderers) { @@ -205,7 +207,9 @@ void PushTerrain(Terrain terrain) } Profiling.Profiler.EndSample(); + #pragma warning disable CS0618 // Type or member is obsolete var terrains = Object.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete Profiling.Profiler.BeginSample($"Find Terrains ({terrains.Length})"); foreach (var terrain in terrains) { diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/PathTracingContext.cs b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/PathTracingContext.cs index 84592c4d6e4..1df34022fdd 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/PathTracingContext.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/PathTracing/PathTracingContext.cs @@ -186,7 +186,7 @@ public void Update(CommandBuffer cmd, PathTracingSettings settings) if (settings.lightPickingMethod == LightPickingMethod.Regir || settings.lightPickingMethod == LightPickingMethod.LightGrid) { - var sceneRenderers = Object.FindObjectsByType(FindObjectsSortMode.None); + var sceneRenderers = Object.FindObjectsByType(); foreach (Renderer r in sceneRenderers) sceneBounds.Encapsulate(r.bounds); } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Debug/DebugMessageHandler.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Debug/DebugMessageHandler.cs index 385b631efb8..3d0f7edab1c 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Debug/DebugMessageHandler.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Debug/DebugMessageHandler.cs @@ -141,7 +141,7 @@ internal static byte[] SerializeMessage(MessageType type, IPayload payload = nul return memoryStream.ToArray(); } - internal static (MessageType, IPayload) DeserializeMessage(byte[] data) + internal unsafe static (MessageType, IPayload) DeserializeMessage(byte[] data) { using var memoryStream = new MemoryStream(data); using var reader = new BinaryReader(memoryStream); diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceBuffer.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceBuffer.cs index 97b8430077e..9d1ee0d9feb 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceBuffer.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceBuffer.cs @@ -171,9 +171,9 @@ override protected string GetResourceTypeName() return "GraphicsBuffer"; } - override protected int GetSortIndex(GraphicsBuffer res) + override protected ulong GetSortIndex(GraphicsBuffer res) { - return res.GetHashCode(); + return (ulong)res.GetHashCode(); } } } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourcePool.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourcePool.cs index 118662a9f56..509a871c4ab 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourcePool.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourcePool.cs @@ -16,7 +16,7 @@ abstract class RenderGraphResourcePool : IRenderGraphResourcePool where Ty { // Dictionary tracks resources by hash and stores resources with same hash in a List (list instead of a stack because we need to be able to remove stale allocations, potentially in the middle of the stack). // The list needs to be sorted otherwise you could get inconsistent resource usage from one frame to another. - protected Dictionary> m_ResourcePool = new Dictionary>(); + protected Dictionary> m_ResourcePool = new Dictionary>(); // This list allows us to determine if all resources were correctly released in the frame when validity checks are enabled. // This is useful to warn in case of user error or avoid leaks when a render graph execution error occurs for example. @@ -28,13 +28,13 @@ abstract class RenderGraphResourcePool : IRenderGraphResourcePool where Ty protected abstract string GetResourceName(in Type res); protected abstract long GetResourceSize(in Type res); protected abstract string GetResourceTypeName(); - protected abstract int GetSortIndex(Type res); + protected abstract ulong GetSortIndex(Type res); public void ReleaseResource(int hash, Type resource, int currentFrameIndex) { if (!m_ResourcePool.TryGetValue(hash, out var list)) { - list = new SortedList(); + list = new SortedList(); m_ResourcePool.Add(hash, list); } @@ -43,7 +43,7 @@ public void ReleaseResource(int hash, Type resource, int currentFrameIndex) public bool TryGetResource(int hashCode, out Type resource) { - if (m_ResourcePool.TryGetValue(hashCode, out SortedList list) && list.Count > 0) + if (m_ResourcePool.TryGetValue(hashCode, out SortedList list) && list.Count > 0) { var index = list.Count - 1; resource = list.Values[index].resource; @@ -176,7 +176,7 @@ public int GetNumResourcesAvailable() return totalResources; } - static List s_ToRemoveList = new List(32); + static List s_ToRemoveList = new List(32); public override void PurgeUnusedResources(int currentFrameIndex) { diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceTexture.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceTexture.cs index eb039afa38b..cd63545cf4a 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceTexture.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphResourceTexture.cs @@ -623,9 +623,9 @@ override protected string GetResourceTypeName() return "Texture"; } - override protected int GetSortIndex(RTHandle res) + override protected ulong GetSortIndex(RTHandle res) { - return res.GetInstanceID(); + return res.GetUniqueID(); } } } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Textures/PowerOfTwoTextureAtlas.cs b/Packages/com.unity.render-pipelines.core/Runtime/Textures/PowerOfTwoTextureAtlas.cs index 4175f1fb208..526068e941d 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Textures/PowerOfTwoTextureAtlas.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Textures/PowerOfTwoTextureAtlas.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using UnityEngine.Experimental.Rendering; @@ -11,7 +12,7 @@ public class PowerOfTwoTextureAtlas : Texture2DAtlas readonly int m_MipPadding; const float k_MipmapFactorApprox = 1.33f; - private Dictionary m_RequestedTextures = new Dictionary(); + private Dictionary m_RequestedTextures = new Dictionary(); /// /// Create a new texture atlas, must have power of two size. @@ -120,15 +121,44 @@ private void Blit2DTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture textu /// Source scale (.xy) and offset(.zw). /// Blit mip maps. /// Override texture instance ID. - public override void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, int overrideInstanceID = -1) + [Obsolete("BlitTexture(CommandBuffer, Vector4, Texture, Vector4, bool, int) is obsolete, use BlitTexture(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.")] + public override void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips, int overrideInstanceID) + { + int instanceID = overrideInstanceID != -1 ? overrideInstanceID : texture.GetEntityId(); + TextureIdentifier identifier = new TextureIdentifier((ulong)instanceID); + BlitTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, identifier); + } + + /// + /// Blit texture into the atlas with padding. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Source scale (.xy) and offset(.zw). + /// Override texture instance ID. + [Obsolete("BlitTexture(CommandBuffer, Vector4, Texture, Vector4, int) is obsolete, use BlitTexture(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.")] + public override void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, int overrideInstanceID) + { + BlitTexture(cmd, scaleOffset, texture, sourceScaleOffset, true, overrideInstanceID); + } + + /// + /// Blit texture into the atlas with padding. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Source scale (.xy) and offset(.zw). + /// Blit mip maps. + /// Override texture identifier. + public override void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, TextureIdentifier overrideIdentifier = default) { // We handle ourself the 2D blit because cookies needs mipPadding for trilinear filtering if (Is2D(texture)) { Blit2DTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, BlitType.Padding); -#pragma warning disable 618 // todo @emilie.thaulow replace with GetIdentifier() - MarkGPUTextureValid(overrideInstanceID != -1 ? overrideInstanceID : texture.GetEntityId(), blitMips); -#pragma warning restore 618 + MarkGPUTextureValid(overrideIdentifier != default ? overrideIdentifier : GetTextureIdentifier(texture), blitMips); } } @@ -141,15 +171,45 @@ public override void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture /// Source scale (.xy) and offset(.zw). /// Blit mip maps. /// Override texture instance ID. - public void BlitTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, int overrideInstanceID = -1) + [Obsolete("BlitTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, bool, int) is obsolete, use BlitTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.")] + public void BlitTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips, int overrideInstanceID) + { + int instanceID = overrideInstanceID != -1 ? overrideInstanceID : texture.GetEntityId(); + TextureIdentifier identifier = new TextureIdentifier((ulong)instanceID); + BlitTextureMultiply(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, identifier); + + } + + /// + /// Blit texture into the atlas with padding and blending. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Source scale (.xy) and offset(.zw). + /// Override texture instance ID. + [Obsolete("BlitTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, int) is obsolete, use BlitTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.")] + public void BlitTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, int overrideInstanceID) + { + BlitTextureMultiply(cmd, scaleOffset, texture, sourceScaleOffset, true, overrideInstanceID); + } + + /// + /// Blit texture into the atlas with padding and blending. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Source scale (.xy) and offset(.zw). + /// Blit mip maps. + /// Override texture identifier. + public void BlitTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, TextureIdentifier overrideIdentifier = default) { // We handle ourself the 2D blit because cookies needs mipPadding for trilinear filtering if (Is2D(texture)) { Blit2DTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, BlitType.PaddingMultiply); -#pragma warning disable 618 // todo @emilie.thaulow replace with GetIdentifier() - MarkGPUTextureValid(overrideInstanceID != -1 ? overrideInstanceID : texture.GetEntityId(), blitMips); -#pragma warning restore 618 + MarkGPUTextureValid(overrideIdentifier != default ? overrideIdentifier : GetTextureIdentifier(texture), blitMips); } } @@ -162,15 +222,46 @@ public void BlitTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture /// Source scale (.xy) and offset(.zw). /// Blit mip maps. /// Override texture instance ID. - public override void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, int overrideInstanceID = -1) + [Obsolete("BlitOctahedralTexture(CommandBuffer, Vector4, Texture, Vector4, bool, int) is obsolete, use BlitOctahedralTexture(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.")] + public override void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips, int overrideInstanceID) + { + int instanceID = overrideInstanceID != -1 ? overrideInstanceID : texture.GetEntityId(); + TextureIdentifier identifier = new TextureIdentifier((ulong)instanceID); + BlitOctahedralTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, identifier); + + } + + /// + /// Blit octahedral texture into the atlas with padding. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Source scale (.xy) and offset(.zw). + /// Override texture instance ID. + [Obsolete("BlitOctahedralTexture(CommandBuffer, Vector4, Texture, Vector4, int) is obsolete, use BlitOctahedralTexture(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.")] + public override void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, int overrideInstanceID) + { + BlitOctahedralTexture(cmd, scaleOffset, texture, sourceScaleOffset, true, overrideInstanceID); + + } + + /// + /// Blit octahedral texture into the atlas with padding. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Source scale (.xy) and offset(.zw). + /// Blit mip maps. + /// Override texture identifier. + public override void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, TextureIdentifier textureIdentifier = default) { // We handle ourself the 2D blit because cookies needs mipPadding for trilinear filtering if (Is2D(texture)) { Blit2DTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, BlitType.OctahedralPadding); -#pragma warning disable 618 // todo @emilie.thaulow replace with GetIdentifier() - MarkGPUTextureValid(overrideInstanceID != -1 ? overrideInstanceID : texture.GetEntityId(), blitMips); -#pragma warning restore 618 + MarkGPUTextureValid(textureIdentifier != default ? textureIdentifier : GetTextureIdentifier(texture), blitMips); } } @@ -183,15 +274,44 @@ public override void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffse /// Source scale (.xy) and offset(.zw). /// Blit mip maps. /// Override texture instance ID. - public void BlitOctahedralTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, int overrideInstanceID = -1) + [Obsolete("BlitOctahedralTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, bool, int) is obsolete, use BlitOctahedralTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.")] + public void BlitOctahedralTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips, int overrideInstanceID ) + { + int instanceID = overrideInstanceID != -1 ? overrideInstanceID : texture.GetEntityId(); + TextureIdentifier identifier = new TextureIdentifier((ulong)instanceID); + BlitOctahedralTextureMultiply(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, identifier); + } + + /// + /// Blit octahedral texture into the atlas with padding. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Source scale (.xy) and offset(.zw). + /// Override texture instance ID. + [Obsolete("BlitOctahedralTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, int) is obsolete, use BlitOctahedralTextureMultiply(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.")] + public void BlitOctahedralTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, int overrideInstanceID ) + { + BlitOctahedralTextureMultiply(cmd, scaleOffset, texture, sourceScaleOffset, true, overrideInstanceID); + } + + /// + /// Blit octahedral texture into the atlas with padding. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Source scale (.xy) and offset(.zw). + /// Blit mip maps. + /// Override texture identifier. + public void BlitOctahedralTextureMultiply(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, TextureIdentifier overrideIdentifier = default) { // We handle ourself the 2D blit because cookies needs mipPadding for trilinear filtering if (Is2D(texture)) { Blit2DTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, BlitType.OctahedralPaddingMultiply); -#pragma warning disable 618 // todo @emilie.thaulow replace with GetIdentifier() - MarkGPUTextureValid(overrideInstanceID != -1 ? overrideInstanceID : texture.GetEntityId(), blitMips); -#pragma warning restore 618 + MarkGPUTextureValid(overrideIdentifier != default ? overrideIdentifier : GetTextureIdentifier(texture), blitMips); } } @@ -221,7 +341,25 @@ Vector2 GetPowerOfTwoTextureSize(Texture texture) /// Request height in pixels. /// Override texture instance ID. /// True on success, false otherwise. - public override bool AllocateTexture(CommandBuffer cmd, ref Vector4 scaleOffset, Texture texture, int width, int height, int overrideInstanceID = -1) + [Obsolete("AllocateTexture(CommandBuffer, ref Vector4, Texture, int, int, int) is obsolete, use AllocateTexture(CommandBuffer, ref Vector4, Texture, int, int, TextureIdentifier) instead.")] + public override bool AllocateTexture(CommandBuffer cmd, ref Vector4 scaleOffset, Texture texture, int width, int height, int overrideInstanceID) + { + TextureIdentifier identifier = new TextureIdentifier((ulong)overrideInstanceID); + return AllocateTexture(cmd, ref scaleOffset, texture, width, height, identifier); + } + + // Override the behavior when we add a texture so all non-pot textures are blitted to a pot target zone + /// + /// Allocate space from the atlas for a texture and copy texture contents into the atlas. + /// + /// Target command buffer for graphics commands. + /// Allocated scale (.xy) and offset (.zw) + /// Source Texture + /// Request width in pixels. + /// Request height in pixels. + /// Override texture identifier. + /// True on success, false otherwise. + public override bool AllocateTexture(CommandBuffer cmd, ref Vector4 scaleOffset, Texture texture, int width, int height, TextureIdentifier overrideIdentifier = default) { // This atlas only supports square textures if (height != width) @@ -232,7 +370,7 @@ public override bool AllocateTexture(CommandBuffer cmd, ref Vector4 scaleOffset, TextureSizeToPowerOfTwo(texture, ref height, ref width); - return base.AllocateTexture(cmd, ref scaleOffset, texture, width, height); + return base.AllocateTexture(cmd, ref scaleOffset, texture, width, height, default(TextureIdentifier)); } /// @@ -255,7 +393,7 @@ public override bool AllocateTexture(CommandBuffer cmd, ref Vector4 scaleOffset, /// The height /// True if the space is reserved public bool ReserveSpace(Texture texture, int width, int height) - => ReserveSpace(GetTextureID(texture), width, height); + => ReserveSpace(GetTextureIdentifier(texture), width, height); /// /// Reserves the space on the texture atlas @@ -266,7 +404,7 @@ public bool ReserveSpace(Texture texture, int width, int height) /// The height /// True if the space is reserved public bool ReserveSpace(Texture textureA, Texture textureB, int width, int height) - => ReserveSpace(GetTextureID(textureA, textureB), width, height); + => ReserveSpace(GetTextureIdentifier(textureA, textureB), width, height); /// /// Reserves the space on the texture atlas @@ -275,23 +413,36 @@ public bool ReserveSpace(Texture textureA, Texture textureB, int width, int heig /// The width /// The height /// True if the space is reserved + [Obsolete("ReserveSpace with int id is obsolete, use the TextureIdentifier version instead.")] public bool ReserveSpace(int id, int width, int height) { - m_RequestedTextures[id] = new Vector2Int(width, height); + TextureIdentifier identifier = new TextureIdentifier((ulong)id); + return ReserveSpace(identifier, width, height); + } + + /// + /// Reserves the space on the texture atlas + /// + /// The id + /// The width + /// The height + /// True if the space is reserved + public bool ReserveSpace(TextureIdentifier identifier, int width, int height) + { + m_RequestedTextures[identifier] = new Vector2Int(width, height); // Cookie texture resolution changing between frame is a special case, so we handle it here. // The texture will be re-allocated and may cause holes in the atlas texture, which is fine // because when it doesn't have any more space, it will re-layout the texture correctly. - var cachedSize = GetCachedTextureSize(id); - if (!IsCached(out _, id) || cachedSize.x != width || cachedSize.y != height) + var cachedSize = GetCachedTextureSize(identifier); + if (!IsCached(out _, identifier) || cachedSize.x != width || cachedSize.y != height) { Vector4 scaleBias = Vector4.zero; - if (!AllocateTextureWithoutBlit(id, width, height, ref scaleBias)) + if (!AllocateTextureWithoutBlit(identifier, width, height, ref scaleBias)) return false; } return true; } - /// /// sort all the requested allocation from biggest to smallest and re-insert them. /// This function does not moves the textures in the atlas, it only changes their coordinates @@ -299,7 +450,7 @@ public bool ReserveSpace(int id, int width, int height) /// True if all textures have successfully been re-inserted in the atlas public bool RelayoutEntries() { - var entries = new List<(int instanceId, Vector2Int size)>(); + var entries = new List<(TextureIdentifier identifier, Vector2Int size)>(); foreach (var entry in m_RequestedTextures) entries.Add((entry.Key, entry.Value)); @@ -314,7 +465,7 @@ public bool RelayoutEntries() bool success = true; Vector4 newScaleOffset = Vector4.zero; foreach (var e in entries) - success &= AllocateTextureWithoutBlit(e.instanceId, e.size.x, e.size.y, ref newScaleOffset); + success &= AllocateTextureWithoutBlit(e.identifier, e.size.x, e.size.y, ref newScaleOffset); return success; } diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Textures/RTHandle.cs b/Packages/com.unity.render-pipelines.core/Runtime/Textures/RTHandle.cs index 1d9eb5d7db9..9da571575fc 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Textures/RTHandle.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Textures/RTHandle.cs @@ -202,20 +202,33 @@ internal void SetTexture(RenderTargetIdentifier tex) m_NameID = tex; } + /// + /// Get the identifier of the RTHandle. + /// + /// The RTHandle identifier. + public ulong GetUniqueID() + { + if (m_RT != null) + return m_RT.GetEntityId().GetRawData(); + else if (m_ExternalTexture != null) + return m_ExternalTexture.GetEntityId().GetRawData(); + else + return (ulong)m_NameID.GetHashCode(); // No instance ID so we return the hash code. + } + /// /// Get the Instance ID of the RTHandle. /// /// The RTHandle Instance ID. + [Obsolete("GetInstanceID() is obsolete, use GetUniqueID() instead.")] public int GetInstanceID() { -#pragma warning disable 618 // todo @emilie.thaulow replace with ulong if (m_RT != null) - return m_RT.GetEntityId(); + return m_RT.GetInstanceID(); else if (m_ExternalTexture != null) - return m_ExternalTexture.GetEntityId(); + return m_ExternalTexture.GetInstanceID(); else return m_NameID.GetHashCode(); // No instance ID so we return the hash code. -#pragma warning restore 618 } /// diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Textures/Texture2DAtlas.cs b/Packages/com.unity.render-pipelines.core/Runtime/Textures/Texture2DAtlas.cs index 041baa4e01c..bc3872d5fc3 100644 --- a/Packages/com.unity.render-pipelines.core/Runtime/Textures/Texture2DAtlas.cs +++ b/Packages/com.unity.render-pipelines.core/Runtime/Textures/Texture2DAtlas.cs @@ -140,6 +140,71 @@ public void Reset() /// public class Texture2DAtlas { + /// + /// A unique identifier for textures used as a Texture2DAtlas. + /// +#pragma warning disable CS0660, CS0661 + // The omission of Equals(object) is intentional, it causes boxing. + public readonly struct TextureIdentifier : IEquatable +#pragma warning restore CS0660, CS0661 + { + /// + /// An invalid or default TextureIdentifier. + /// + public static TextureIdentifier None => default; + + internal TextureIdentifier(ulong value) + { + this.value = value; + } + + /// + /// Returns true if other equals the current TextureIdentifier. + /// + /// Other TextureIdentifier to compare to. + /// True if equal. + public bool Equals(TextureIdentifier other) + { + return value == other.value; + } + + /// + /// Get hash code for the TextureIdentifier. + /// + /// Hash code. + public override int GetHashCode() + { + return value.GetHashCode(); + } + + /// + /// Equality operator. + /// + /// First operand. + /// Second operand. + /// True if equal. + public static bool operator ==(TextureIdentifier left, TextureIdentifier right) + { + return left.Equals(right); + } + + /// + /// Inequality operator. + /// + /// First operand. + /// Second operand. + /// True if not equal. + public static bool operator !=(TextureIdentifier left, TextureIdentifier right) + { + return !left.Equals(right); + } + + /// + /// Internal value of the identifier, shouldn't be directly used. + /// + internal readonly ulong value; + } + private enum BlitType { Default, @@ -183,9 +248,9 @@ private enum BlitType private protected bool m_UseMipMaps; bool m_IsAtlasTextureOwner = false; private AtlasAllocator m_AtlasAllocator = null; - private Dictionary m_AllocationCache = new Dictionary(); - private Dictionary m_IsGPUTextureUpToDate = new Dictionary(); - private Dictionary m_TextureHashes = new Dictionary(); + private Dictionary m_AllocationCache = new(); + private Dictionary m_IsGPUTextureUpToDate = new(); + private Dictionary m_TextureHashes = new(); static readonly Vector4 fullScaleOffset = new Vector4(1, 1, 0, 0); @@ -370,18 +435,18 @@ private void Blit2DTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture textu /// /// Mark texture valid on the GPU. /// - /// Texture instance ID. + /// Texture identifier. /// Texture has valid mip maps. - private protected void MarkGPUTextureValid(int instanceId, bool mipAreValid = false) + private protected void MarkGPUTextureValid(TextureIdentifier identifier, bool mipAreValid = false) { - m_IsGPUTextureUpToDate[instanceId] = (mipAreValid) ? kGPUTexValidMipAll : kGPUTexValidMip0; + m_IsGPUTextureUpToDate[identifier] = (mipAreValid) ? kGPUTexValidMipAll : kGPUTexValidMip0; } /// /// Mark texture invalid on the GPU. /// - /// Texture instance ID. - private protected void MarkGPUTextureInvalid(int instanceId) => m_IsGPUTextureUpToDate[instanceId] = kGPUTexInvalid; + /// Texture identifier. + private protected void MarkGPUTextureInvalid(TextureIdentifier identifier) => m_IsGPUTextureUpToDate[identifier] = kGPUTexInvalid; /// /// Blit 2D texture into the atlas. @@ -392,7 +457,40 @@ private protected void MarkGPUTextureValid(int instanceId, bool mipAreValid = fa /// Source scale (.xy) and offset(.zw). /// Blit mip maps. /// Override texture instance ID. - public virtual void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, int overrideInstanceID = -1) + [Obsolete("BlitTexture(CommandBuffer, Vector4, Texture, Vector4 , bool , int) is obsolete, " + + "use BlitTexture(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.")] + public virtual void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips, int overrideInstanceID) + { + var instanceID = overrideInstanceID != -1 ? overrideInstanceID : GetTextureID(texture); + TextureIdentifier identifier = new TextureIdentifier((ulong)instanceID); + BlitTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, identifier); + } + + /// + /// Blit 2D texture into the atlas. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Source scale (.xy) and offset(.zw). + /// Override texture instance ID. + [Obsolete("BlitTexture(CommandBuffer, Vector4, Texture, Vector4, int) is obsolete, " + + "use BlitTexture(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.")] + public virtual void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, int overrideInstanceID) + { + BlitTexture(cmd, scaleOffset, texture, sourceScaleOffset, true, overrideInstanceID); + } + + /// + /// Blit 2D texture into the atlas. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Source scale (.xy) and offset(.zw). + /// Blit mip maps. + /// Override texture identifier. + public virtual void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, TextureIdentifier overrideIdentifier = default) { // This atlas only support 2D texture so we only blit 2D textures if (Is2D(texture)) @@ -402,9 +500,9 @@ public virtual void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture blitType = BlitType.SingleChannel; Blit2DTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, blitType); - var instanceID = overrideInstanceID != -1 ? overrideInstanceID : GetTextureID(texture); - MarkGPUTextureValid(instanceID, blitMips); - m_TextureHashes[instanceID] = CoreUtils.GetTextureHash(texture); + var identifier = overrideIdentifier != default ? overrideIdentifier : GetTextureIdentifier(texture); + MarkGPUTextureValid(identifier, blitMips); + m_TextureHashes[identifier] = CoreUtils.GetTextureHash(texture); } } @@ -417,10 +515,45 @@ public virtual void BlitTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture /// Source scale (.xy) and offset(.zw). /// Blit mip maps. /// Override texture instance ID. - public virtual void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, int overrideInstanceID = -1) + [Obsolete("BlitOctahedralTexture(CommandBuffer, Vector4, Texture, Vector4, bool, int) is obsolete, use " + + "BlitOctahedralTexture(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.")] + public virtual void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips, int overrideInstanceID) + { + // Default implementation. No padding in Texture2DAtlas, no need to handle specially. + var instanceID = overrideInstanceID != -1 ? overrideInstanceID : GetTextureID(texture); + TextureIdentifier identifier = new TextureIdentifier((ulong)instanceID); + BlitOctahedralTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, identifier); + } + + /// + /// Blit octahedral texture into the atlas. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Source scale (.xy) and offset(.zw). + /// Override texture instance ID. + [Obsolete("BlitOctahedralTexture(CommandBuffer, Vector4, Texture, Vector4, int) is obsolete, use " + + "BlitOctahedralTexture(CommandBuffer, Vector4, Texture, Vector4, bool, TextureIdentifier) instead.")] + public virtual void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, int overrideInstanceID) + { + // Default implementation. No padding in Texture2DAtlas, no need to handle specially. + BlitOctahedralTexture(cmd, scaleOffset, texture, sourceScaleOffset, true, overrideInstanceID); + } + + /// + /// Blit octahedral texture into the atlas. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Source scale (.xy) and offset(.zw). + /// Blit mip maps. + /// Override texture identifier. + public virtual void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, Vector4 sourceScaleOffset, bool blitMips = true, TextureIdentifier overrideIdentifier = default) { // Default implementation. No padding in Texture2DAtlas, no need to handle specially. - BlitTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, overrideInstanceID); + BlitTexture(cmd, scaleOffset, texture, sourceScaleOffset, blitMips, overrideIdentifier); } /// @@ -431,7 +564,38 @@ public virtual void BlitOctahedralTexture(CommandBuffer cmd, Vector4 scaleOffset /// Source Texture /// Blit mip maps. /// Override texture instance ID. - public virtual void BlitCubeTexture2D(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, bool blitMips = true, int overrideInstanceID = -1) + [Obsolete("BlitCubeTexture2D(CommandBuffer, Vector4, Texture, bool blitMips, int ) is obsolete, " + + "use BlitCubeTexture2D(CommandBuffer, Vector4, Texture, bool, TextureIdentifier) instead.")] + public virtual void BlitCubeTexture2D(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, bool blitMips, int overrideInstanceID) + { + var instanceID = overrideInstanceID != -1 ? overrideInstanceID : GetTextureID(texture); + TextureIdentifier identifier = new TextureIdentifier((ulong)instanceID); + BlitCubeTexture2D(cmd, scaleOffset, texture, blitMips, identifier); + } + + /// + /// Blit and project Cube texture into a 2D texture in the atlas. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Override texture instance ID. + [Obsolete("BlitCubeTexture2D(CommandBuffer, Vector4, Texture, int) is obsolete, " + + "use BlitCubeTexture2D(CommandBuffer, Vector4, Texture, bool, TextureIdentifier) instead.")] + public virtual void BlitCubeTexture2D(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, int overrideInstanceID) + { + BlitCubeTexture2D(cmd, scaleOffset, texture, true, overrideInstanceID); + } + + /// + /// Blit and project Cube texture into a 2D texture in the atlas. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Blit mip maps. + /// Override texture identifier. + public virtual void BlitCubeTexture2D(CommandBuffer cmd, Vector4 scaleOffset, Texture texture, bool blitMips = true, TextureIdentifier overrideIdentifier = default) { Debug.Assert(texture.dimension == TextureDimension.Cube); @@ -445,9 +609,9 @@ public virtual void BlitCubeTexture2D(CommandBuffer cmd, Vector4 scaleOffset, Te // By default blit cube into a single octahedral 2D texture quad Blit2DTexture(cmd, scaleOffset, texture, new Vector4(1.0f, 1.0f, 0.0f, 0.0f), blitMips, blitType); - var instanceID = overrideInstanceID != -1 ? overrideInstanceID : GetTextureID(texture); - MarkGPUTextureValid(instanceID, blitMips); - m_TextureHashes[instanceID] = CoreUtils.GetTextureHash(texture); + var identifier = overrideIdentifier != default ? overrideIdentifier : GetTextureIdentifier(texture); + MarkGPUTextureValid(identifier, blitMips); + m_TextureHashes[identifier] = CoreUtils.GetTextureHash(texture); } } @@ -461,17 +625,36 @@ public virtual void BlitCubeTexture2D(CommandBuffer cmd, Vector4 scaleOffset, Te /// Request height in pixels. /// Override texture instance ID. /// True if the texture was successfully allocated and copied; false otherwise. - public virtual bool AllocateTexture(CommandBuffer cmd, ref Vector4 scaleOffset, Texture texture, int width, int height, int overrideInstanceID = -1) + [Obsolete("AllocateTexture(CommandBuffer, ref Vector4, Texture, int, int, int) is obsolete, " + + "use AllocateTexture(CommandBuffer, ref Vector4, Texture, int, int, TextureIdentifier) instead.")] + public virtual bool AllocateTexture(CommandBuffer cmd, ref Vector4 scaleOffset, Texture texture, int width, int height, int overrideInstanceID) { var instanceID = overrideInstanceID != -1 ? overrideInstanceID : GetTextureID(texture); + TextureIdentifier identifier = new TextureIdentifier((ulong)instanceID); + return AllocateTexture(cmd, ref scaleOffset, texture, width, height, identifier); + } + + /// + /// Allocate space from the atlas for a texture and copy texture contents into the atlas. + /// + /// Target command buffer for graphics commands. + /// Destination scale (.xy) and offset (.zw) + /// Source Texture + /// Request width in pixels. + /// Request height in pixels. + /// Override texture identifier. + /// True if the texture was successfully allocated and copied; false otherwise. + public virtual bool AllocateTexture(CommandBuffer cmd, ref Vector4 scaleOffset, Texture texture, int width, int height, TextureIdentifier overrideIdentifier = default) + { + var instanceID = overrideIdentifier != default ? overrideIdentifier : GetTextureIdentifier(texture); bool allocated = AllocateTextureWithoutBlit(instanceID, width, height, ref scaleOffset); if (allocated) { if (Is2D(texture)) - BlitTexture(cmd, scaleOffset, texture, fullScaleOffset); + BlitTexture(cmd, scaleOffset, texture, fullScaleOffset, true, default(TextureIdentifier)); else - BlitCubeTexture2D(cmd, scaleOffset, texture, true); + BlitCubeTexture2D(cmd, scaleOffset, texture, true, default(TextureIdentifier)); // texture is up to date MarkGPUTextureValid(instanceID, true); @@ -490,9 +673,7 @@ public virtual bool AllocateTexture(CommandBuffer cmd, ref Vector4 scaleOffset, /// Allocated scale (.xy) and offset (.zw). /// True on success, false otherwise. public bool AllocateTextureWithoutBlit(Texture texture, int width, int height, ref Vector4 scaleOffset) -#pragma warning disable 618 // todo @emilie.thaulow replace with GetIdentifier() - => AllocateTextureWithoutBlit(texture.GetEntityId(), width, height, ref scaleOffset); -#pragma warning restore 618 + => AllocateTextureWithoutBlit(GetTextureIdentifier(texture), width, height, ref scaleOffset); /// /// Allocate space from the atlas for a texture. @@ -502,16 +683,31 @@ public bool AllocateTextureWithoutBlit(Texture texture, int width, int height, r /// Request height in pixels. /// Allocated scale (.xy) and offset (.zw). /// True on success, false otherwise. + [Obsolete("AllocateTextureWithoutBlit(int, int, int, ref Vector4) is obsolete, use AllocateTextureWithoutBlit(TextureIdentifier, int, int, ref Vector4) instead.", false)] public virtual bool AllocateTextureWithoutBlit(int instanceId, int width, int height, ref Vector4 scaleOffset) + { + TextureIdentifier identifier = new TextureIdentifier((ulong)instanceId); + return AllocateTextureWithoutBlit(identifier, width, height, ref scaleOffset); + } + + /// + /// Allocate space from the atlas for a texture. + /// + /// Source texture identifier. + /// Request width in pixels. + /// Request height in pixels. + /// Allocated scale (.xy) and offset (.zw). + /// True on success, false otherwise. + public virtual bool AllocateTextureWithoutBlit(TextureIdentifier identifier, int width, int height, ref Vector4 scaleOffset) { scaleOffset = Vector4.zero; if (m_AtlasAllocator.Allocate(ref scaleOffset, width, height)) { scaleOffset.Scale(new Vector4(1.0f / m_Width, 1.0f / m_Height, 1.0f / m_Width, 1.0f / m_Height)); - m_AllocationCache[instanceId] = (scaleOffset, new Vector2Int(width, height)); - MarkGPUTextureInvalid(instanceId); // the texture data haven't been uploaded - m_TextureHashes[instanceId] = -1; + m_AllocationCache[identifier] = (scaleOffset, new Vector2Int(width, height)); + MarkGPUTextureInvalid(identifier); // the texture data haven't been uploaded + m_TextureHashes[identifier] = -1; return true; } else @@ -537,24 +733,46 @@ private protected int GetTextureHash(Texture textureA, Texture textureB) /// /// Source texture. /// Texture instance ID. + [Obsolete("int GetTextureID(Texture texture) is obsolete, use GetTextureIdentifier(Texture texture) instead.")] public int GetTextureID(Texture texture) { -#pragma warning disable 618 // todo @emilie.thaulow replace with GetIdentifier() return texture.GetEntityId(); -#pragma warning restore 618 } + /// + /// Get sub-texture ID for the atlas. + /// + /// Source texture. + /// The TextureIdentifier, which stores the EntityId of the texture. + public TextureIdentifier GetTextureIdentifier(Texture texture) + { + return new TextureIdentifier(texture.GetEntityId().GetRawData()); + } + + /// /// Get sub-texture ID for the atlas. /// /// Source texture A. /// Source texture B. /// Combined texture instance ID. + [Obsolete("GetTextureID(Texture textureA, Texture textureB) is obsolete , use GetTextureIdentifier(Texture textureA, Texture textureB) instead.")] public int GetTextureID(Texture textureA, Texture textureB) { return GetTextureID(textureA) + 23 * GetTextureID(textureB); } + /// + /// Get sub-texture ID for the atlas. + /// + /// Source texture A. + /// Source texture B. + /// Combined texture instance ID. + public TextureIdentifier GetTextureIdentifier(Texture textureA, Texture textureB) + { + return new TextureIdentifier(GetTextureIdentifier(textureA).value + 23 * GetTextureIdentifier(textureB).value); + } + /// /// Check if the atlas contains the textures. /// @@ -563,7 +781,7 @@ public int GetTextureID(Texture textureA, Texture textureB) /// Source texture B. /// True if the texture is in the atlas, false otherwise. public bool IsCached(out Vector4 scaleOffset, Texture textureA, Texture textureB) - => IsCached(out scaleOffset, GetTextureID(textureA, textureB)); + => IsCached(out scaleOffset, GetTextureIdentifier(textureA, textureB)); /// /// Check if the atlas contains the textures. @@ -572,7 +790,7 @@ public bool IsCached(out Vector4 scaleOffset, Texture textureA, Texture textureB /// Source texture /// True if the texture is in the atlas, false otherwise. public bool IsCached(out Vector4 scaleOffset, Texture texture) - => IsCached(out scaleOffset, GetTextureID(texture)); + => IsCached(out scaleOffset, GetTextureIdentifier(texture)); /// /// Check if the atlas contains the texture. @@ -580,9 +798,24 @@ public bool IsCached(out Vector4 scaleOffset, Texture texture) /// Texture scale (.xy) and offset (.zw). /// Source texture instance ID. /// True if the texture is in the atlas, false otherwise + [Obsolete("IsCached(out Vector4, int) is obsolete, use IsCached(out Vector4, TextureIdentifier) instead.")] public bool IsCached(out Vector4 scaleOffset, int id) { - bool cached = m_AllocationCache.TryGetValue(id, out var value); + TextureIdentifier identifier = new TextureIdentifier((ulong)id); + bool cached = m_AllocationCache.TryGetValue(identifier, out var value); + scaleOffset = value.scaleOffset; + return cached; + } + + /// + /// Check if the atlas contains the texture. + /// + /// Texture scale (.xy) and offset (.zw). + /// Source texture identifier. + /// True if the texture is in the atlas, false otherwise. + public bool IsCached(out Vector4 scaleOffset, TextureIdentifier identifier) + { + bool cached = m_AllocationCache.TryGetValue(identifier, out var value); scaleOffset = value.scaleOffset; return cached; } @@ -592,9 +825,22 @@ public bool IsCached(out Vector4 scaleOffset, int id) /// /// Source texture instance ID. /// Texture size. + [Obsolete("GetCachedTextureSize(int) is obsolete, use GetCachedTextureSize(TextureIdentifier) instead.")] internal Vector2Int GetCachedTextureSize(int id) { - m_AllocationCache.TryGetValue(id, out var value); + TextureIdentifier identifier = new TextureIdentifier((ulong)id); + m_AllocationCache.TryGetValue(identifier, out var value); + return value.size; + } + + /// + /// Get cached texture size. + /// + /// Source texture identifier. + /// Texture size. + internal Vector2Int GetCachedTextureSize(TextureIdentifier identifier) + { + m_AllocationCache.TryGetValue(identifier, out var value); return value.size; } @@ -607,7 +853,7 @@ internal Vector2Int GetCachedTextureSize(int id) public virtual bool NeedsUpdate(Texture texture, bool needMips = false) { RenderTexture rt = texture as RenderTexture; - int key = GetTextureID(texture); + var key = GetTextureIdentifier(texture); int textureHash = CoreUtils.GetTextureHash(texture); // Update the render texture if needed @@ -649,20 +895,34 @@ public virtual bool NeedsUpdate(Texture texture, bool needMips = false) /// The update count. /// Texture uses mips. /// True if slot needs update, false otherwise. + [Obsolete("NeedsUpdate(int, int, bool) is obsolete, use NeedsUpdate(TextureIdentifier, int, bool) instead.")] public virtual bool NeedsUpdate(int id, int updateCount, bool needMips = false) + { + TextureIdentifier identifier = new TextureIdentifier((ulong)id); + return NeedsUpdate(identifier, updateCount, needMips); + } + + /// + /// Check if a slot needs to be updated in the atlas. + /// + /// The textureIdentifier. + /// The update count. + /// Texture uses mips. + /// True if slot needs update, false otherwise. + public virtual bool NeedsUpdate(TextureIdentifier identifier, int updateCount, bool needMips = false) { int atlasUpdateCount; - if (m_IsGPUTextureUpToDate.TryGetValue(id, out atlasUpdateCount)) + if (m_IsGPUTextureUpToDate.TryGetValue(identifier, out atlasUpdateCount)) { if (updateCount != atlasUpdateCount) { - m_IsGPUTextureUpToDate[id] = updateCount; + m_IsGPUTextureUpToDate[identifier] = updateCount; return true; } } else { - m_IsGPUTextureUpToDate[id] = updateCount; + m_IsGPUTextureUpToDate[identifier] = updateCount; } return false; @@ -679,7 +939,7 @@ public virtual bool NeedsUpdate(Texture textureA, Texture textureB, bool needMip { RenderTexture rtA = textureA as RenderTexture; RenderTexture rtB = textureB as RenderTexture; - int key = GetTextureID(textureA, textureB); + var key = GetTextureIdentifier(textureA, textureB); int textureHash = GetTextureHash(textureA, textureB); // Update the render texture if needed @@ -712,7 +972,7 @@ public virtual bool NeedsUpdate(Texture textureA, Texture textureB, bool needMip // In case the texture settings/import settings have changed, we need to update it else if (m_TextureHashes.TryGetValue(key, out int hash) && hash != textureHash) { - m_TextureHashes[key] = key; + m_TextureHashes[key] = textureHash; return true; } // For regular textures, values == 0 means that their GPU data needs to be updated (either because @@ -736,7 +996,7 @@ public virtual bool AddTexture(CommandBuffer cmd, ref Vector4 scaleOffset, Textu if (IsCached(out scaleOffset, texture)) return true; - return AllocateTexture(cmd, ref scaleOffset, texture, texture.width, texture.height); + return AllocateTexture(cmd, ref scaleOffset, texture, texture.width, texture.height, default(TextureIdentifier)); } /// @@ -758,16 +1018,16 @@ public virtual bool UpdateTexture(CommandBuffer cmd, Texture oldTexture, Texture if (updateIfNeeded && NeedsUpdate(newTexture)) { if (Is2D(newTexture)) - BlitTexture(cmd, scaleOffset, newTexture, sourceScaleOffset, blitMips); + BlitTexture(cmd, scaleOffset, newTexture, sourceScaleOffset, blitMips, default(TextureIdentifier)); else - BlitCubeTexture2D(cmd, scaleOffset, newTexture, blitMips); - MarkGPUTextureValid(GetTextureID(newTexture), blitMips); // texture is up to date + BlitCubeTexture2D(cmd, scaleOffset, newTexture, blitMips, default(TextureIdentifier)); + MarkGPUTextureValid(GetTextureIdentifier(newTexture), blitMips); // texture is up to date } return true; } else // else we try to allocate the updated texture { - return AllocateTexture(cmd, ref scaleOffset, newTexture, newTexture.width, newTexture.height); + return AllocateTexture(cmd, ref scaleOffset, newTexture, newTexture.width, newTexture.height, default(TextureIdentifier)); } } @@ -783,7 +1043,7 @@ public virtual bool UpdateTexture(CommandBuffer cmd, Texture oldTexture, Texture public virtual bool UpdateTexture(CommandBuffer cmd, Texture texture, ref Vector4 scaleOffset, bool updateIfNeeded = true, bool blitMips = true) => UpdateTexture(cmd, texture, texture, ref scaleOffset, fullScaleOffset, updateIfNeeded, blitMips); - internal bool EnsureTextureSlot(out bool isUploadNeeded, ref Vector4 scaleBias, int key, int width, int height) + internal bool EnsureTextureSlot(out bool isUploadNeeded, ref Vector4 scaleBias, TextureIdentifier key, int width, int height) { isUploadNeeded = false; if (m_AllocationCache.TryGetValue(key, out var value)) 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.core/Tests/Editor/RenderGraphTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs index 7af25de6a5b..6df299a2d62 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs @@ -2287,7 +2287,7 @@ public void ResourcePool_TryGet() // Retrieve it from the pool and make sure this is the right one RTHandle resOut; texturePool.TryGetResource(0, out resOut); - Assert.IsTrue(resIn.GetInstanceID() == resOut.GetInstanceID()); + Assert.IsTrue(resIn.GetUniqueID() == resOut.GetUniqueID()); texturePool.Cleanup(); } diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/AccelStructTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/AccelStructTests.cs index 23a6676b844..64047788a35 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/AccelStructTests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/UnifiedRayTracing/AccelStructTests.cs @@ -532,7 +532,9 @@ public void AddAndRemoveInstances() private void AddTerrainToAccelerationStructure(int heightmapResolution) { Terrain.CreateTerrainGameObject(new TerrainData()); + #pragma warning disable CS0618 // Type or member is obsolete Terrain terrain = GameObject.FindFirstObjectByType(); +#pragma warning restore CS0618 // Type or member is obsolete Assert.NotNull(terrain); // Set terrain texture resolution on terrain data. diff --git a/Packages/com.unity.render-pipelines.core/Tests/Runtime/RuntimeProfilerTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Runtime/RuntimeProfilerTests.cs index ee29f1edc51..f0a215b17c0 100644 --- a/Packages/com.unity.render-pipelines.core/Tests/Runtime/RuntimeProfilerTests.cs +++ b/Packages/com.unity.render-pipelines.core/Tests/Runtime/RuntimeProfilerTests.cs @@ -28,7 +28,9 @@ public void Setup() Assert.Ignore("Frame timing tests are not supported in batch mode, skipping test."); // HACK #1 - really shouldn't have to do this here, but previous tests are leaking gameobjects +#pragma warning disable CS0618 // Type or member is obsolete var objects = GameObject.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete foreach (var o in objects) { // HACK #2 - must not destroy DebugUpdater, which happens to have an EventSystem. 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 08a985da7e7..148eb9b848f 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/Editor/Lighting/DiffusionProfileListEditor.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/DiffusionProfileListEditor.cs index b59bbe44fc5..2b0203eb4e2 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/DiffusionProfileListEditor.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/DiffusionProfileListEditor.cs @@ -57,7 +57,9 @@ void FillProfileListWithScene() // Get all mesh renderers that are within the current volume var diffusionProfiles = new List(); + #pragma warning disable CS0618 // Type or member is obsolete foreach (var meshRenderer in Object.FindObjectsByType(FindObjectsSortMode.InstanceID)) +#pragma warning restore CS0618 // Type or member is obsolete { var colliders = Physics.OverlapBox(meshRenderer.bounds.center, meshRenderer.bounds.size / 2); if (colliders.Contains(volumeCollider)) diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineMenuItems.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineMenuItems.cs index 5b6978312b0..cbceffe4fcd 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineMenuItems.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineMenuItems.cs @@ -301,7 +301,9 @@ static void MenuCreatePostProcessShader() //[MenuItem("Internal/HDRP/Add \"Additional Light-shadow Data\" (if not present)")] static void AddAdditionalLightData() { + #pragma warning disable CS0618 // Type or member is obsolete var lights = UnityObject.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete foreach (var light in lights) { @@ -317,7 +319,9 @@ static void AddAdditionalLightData() //[MenuItem("Internal/HDRP/Add \"Additional Camera Data\" (if not present)")] static void AddAdditionalCameraData() { + #pragma warning disable CS0618 // Type or member is obsolete var cameras = UnityObject.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete foreach (var camera in cameras) { @@ -509,8 +513,10 @@ static void CheckSceneContentForRayTracing(MenuCommand menuCommand) { // Flag that holds bool generalErrorFlag = false; + #pragma warning disable CS0618 // Type or member is obsolete var rendererArray = UnityEngine.GameObject.FindObjectsByType(FindObjectsSortMode.InstanceID); var lodGroupArray = UnityEngine.GameObject.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete List materialArray = new List(32); ReflectionProbe reflectionProbe = new ReflectionProbe(); diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Sky/HDLightingWindowEnvironmentSection.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Sky/HDLightingWindowEnvironmentSection.cs index 64a0878a82a..481c23f91f6 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/Sky/HDLightingWindowEnvironmentSection.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Sky/HDLightingWindowEnvironmentSection.cs @@ -103,7 +103,9 @@ static internal StaticLightingSky GetStaticLightingSkyForScene(Scene scene) //Perhaps it is an old scene. Search everywhere if (result == null) { + #pragma warning disable CS0618 // Type or member is obsolete var candidates = GameObject.FindObjectsByType(FindObjectsSortMode.InstanceID).Where(sls => sls.gameObject.scene == scene); +#pragma warning restore CS0618 // Type or member is obsolete if (candidates.Count() > 0) result = candidates.First(); } diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Sky/HDRISky/HDRISkyEditor.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Sky/HDRISky/HDRISkyEditor.cs index ddcb3fd3508..851a3731c20 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Editor/Sky/HDRISky/HDRISkyEditor.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Sky/HDRISky/HDRISkyEditor.cs @@ -167,7 +167,9 @@ public void GetUpperHemisphereLuxValue() Light GetSun() { Light sunObject = null; + #pragma warning disable CS0618 // Type or member is obsolete var lights = FindObjectsByType(FindObjectsInactive.Exclude, FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete foreach (var light in lights) { if (light.type != LightType.Directional) diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs index 347a75d8c0a..f775adba6b1 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightCookieManager.cs @@ -257,13 +257,13 @@ public Vector4 Fetch2DCookie(CommandBuffer cmd, Texture cookie, Texture ies) if (width < k_MinCookieSize || height < k_MinCookieSize) return Vector4.zero; - if (!m_CookieAtlas.IsCached(out var scaleBias, m_CookieAtlas.GetTextureID(cookie, ies)) && !m_NoMoreSpace) + if (!m_CookieAtlas.IsCached(out var scaleBias, m_CookieAtlas.GetTextureIdentifier(cookie, ies)) && !m_NoMoreSpace) Debug.LogError($"Unity cannot fetch the 2D Light cookie texture: {cookie} because it is not on the cookie atlas. To resolve this, open your HDRP Asset and increase the resolution of the cookie atlas."); if (m_CookieAtlas.NeedsUpdate(cookie, ies, false)) { - m_CookieAtlas.BlitTexture(cmd, scaleBias, ies, new Vector4(1, 1, 0, 0), blitMips: false, overrideInstanceID: m_CookieAtlas.GetTextureID(cookie, ies)); - m_CookieAtlas.BlitTextureMultiply(cmd, scaleBias, cookie, new Vector4(1, 1, 0, 0), blitMips: false, overrideInstanceID: m_CookieAtlas.GetTextureID(cookie, ies)); + m_CookieAtlas.BlitTexture(cmd, scaleBias, ies, new Vector4(1, 1, 0, 0), blitMips: false, overrideIdentifier: m_CookieAtlas.GetTextureIdentifier(cookie, ies)); + m_CookieAtlas.BlitTextureMultiply(cmd, scaleBias, cookie, new Vector4(1, 1, 0, 0), blitMips: false, overrideIdentifier: m_CookieAtlas.GetTextureIdentifier(cookie, ies)); } return scaleBias; @@ -274,7 +274,7 @@ public Vector4 Fetch2DCookie(CommandBuffer cmd, Texture cookie) if (cookie.width < k_MinCookieSize || cookie.height < k_MinCookieSize) return Vector4.zero; - if (!m_CookieAtlas.IsCached(out var scaleBias, m_CookieAtlas.GetTextureID(cookie)) && !m_NoMoreSpace) + if (!m_CookieAtlas.IsCached(out var scaleBias, m_CookieAtlas.GetTextureIdentifier(cookie)) && !m_NoMoreSpace) Debug.LogError($"Unity cannot fetch the 2D Light cookie texture: {cookie} because it is not on the cookie atlas. To resolve this, open your HDRP Asset and increase the resolution of the cookie atlas."); if (m_CookieAtlas.NeedsUpdate(cookie, false)) @@ -291,14 +291,14 @@ public Vector4 FetchAreaCookie(CommandBuffer cmd, Texture cookie) if (!m_CookieAtlas.IsCached(out var scaleBias, cookie) && !m_NoMoreSpace) Debug.LogError($"Area Light cookie texture {cookie} can't be fetched without having reserved. You can try to increase the cookie atlas resolution in the HDRP settings."); - int currentID = m_CookieAtlas.GetTextureID(cookie); + var currentID = m_CookieAtlas.GetTextureIdentifier(cookie); //RTHandle existingTexture; if (m_CookieAtlas.NeedsUpdate(cookie, true)) { // Generate the mips Texture filteredAreaLight = FilterAreaLightTexture(cmd, cookie, cookie.width, cookie.height); Vector4 sourceScaleOffset = new Vector4((cookie.width - 0.5f) / (float)atlasTexture.rt.width, (cookie.height - 0.5f) / (float)atlasTexture.rt.height, 0, 0); - m_CookieAtlas.BlitTexture(cmd, scaleBias, filteredAreaLight, sourceScaleOffset, blitMips: true, overrideInstanceID: currentID); + m_CookieAtlas.BlitTexture(cmd, scaleBias, filteredAreaLight, sourceScaleOffset, blitMips: true, overrideIdentifier: currentID); } return scaleBias; @@ -326,9 +326,9 @@ public Vector4 FetchAreaCookie(CommandBuffer cmd, Texture cookie, Texture ies) Vector4 sourceScaleOffset = new Vector4(projectionSize / (float)atlasTexture.rt.width, projectionSize / (float)atlasTexture.rt.height, 0, 0); Texture filteredProjected = FilterAreaLightTexture(cmd, cookie, projectionSize, projectionSize); - m_CookieAtlas.BlitOctahedralTexture(cmd, scaleBias, filteredProjected, sourceScaleOffset, blitMips: true, overrideInstanceID: m_CookieAtlas.GetTextureID(cookie, ies)); + m_CookieAtlas.BlitOctahedralTexture(cmd, scaleBias, filteredProjected, sourceScaleOffset, blitMips: true, textureIdentifier: m_CookieAtlas.GetTextureIdentifier(cookie, ies)); filteredProjected = FilterAreaLightTexture(cmd, ies, projectionSize, projectionSize); - m_CookieAtlas.BlitOctahedralTextureMultiply(cmd, scaleBias, filteredProjected, sourceScaleOffset, blitMips: true, overrideInstanceID: m_CookieAtlas.GetTextureID(cookie, ies)); + m_CookieAtlas.BlitOctahedralTextureMultiply(cmd, scaleBias, filteredProjected, sourceScaleOffset, blitMips: true, overrideIdentifier: m_CookieAtlas.GetTextureIdentifier(cookie, ies)); } return scaleBias; @@ -414,7 +414,7 @@ public Vector4 FetchCubeCookie(CommandBuffer cmd, Texture cookie) Vector4 sourceScaleOffset = new Vector4(projectionSize / (float)atlasTexture.rt.width, projectionSize / (float)atlasTexture.rt.height, 0, 0); Texture filteredProjected = FilterAreaLightTexture(cmd, cookie, projectionSize, projectionSize); - m_CookieAtlas.BlitOctahedralTexture(cmd, scaleBias, filteredProjected, sourceScaleOffset, blitMips: true, overrideInstanceID: m_CookieAtlas.GetTextureID(cookie)); + m_CookieAtlas.BlitOctahedralTexture(cmd, scaleBias, filteredProjected, sourceScaleOffset, blitMips: true, textureIdentifier: m_CookieAtlas.GetTextureIdentifier(cookie)); } return scaleBias; @@ -443,9 +443,9 @@ public Vector4 FetchCubeCookie(CommandBuffer cmd, Texture cookie, Texture ies) Vector4 sourceScaleOffset = new Vector4(projectionSize / (float)atlasTexture.rt.width, projectionSize / (float)atlasTexture.rt.height, 0, 0); Texture filteredProjected = FilterAreaLightTexture(cmd, cookie, projectionSize, projectionSize); - m_CookieAtlas.BlitOctahedralTexture(cmd, scaleBias, filteredProjected, sourceScaleOffset, blitMips: true, overrideInstanceID: m_CookieAtlas.GetTextureID(cookie, ies)); + m_CookieAtlas.BlitOctahedralTexture(cmd, scaleBias, filteredProjected, sourceScaleOffset, blitMips: true, textureIdentifier: m_CookieAtlas.GetTextureIdentifier(cookie, ies)); filteredProjected = FilterAreaLightTexture(cmd, ies, projectionSize, projectionSize); - m_CookieAtlas.BlitOctahedralTextureMultiply(cmd, scaleBias, filteredProjected, sourceScaleOffset, blitMips: true, overrideInstanceID: m_CookieAtlas.GetTextureID(cookie, ies)); + m_CookieAtlas.BlitOctahedralTextureMultiply(cmd, scaleBias, filteredProjected, sourceScaleOffset, blitMips: true, overrideIdentifier: m_CookieAtlas.GetTextureIdentifier(cookie, ies)); } return scaleBias; 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 2024fd569a3..768be7796dd 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(FindObjectsSortMode.None); + var hdProbes = GameObject.FindObjectsByType(); foreach (var hdProbe in hdProbes) { hdProbe.TryUpdateLuminanceSHL2ForNormalization(); diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/HDRenderPipeline.WaterSystem.Decals.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/HDRenderPipeline.WaterSystem.Decals.cs index b5ffa242eaf..f4ab6e2136a 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/HDRenderPipeline.WaterSystem.Decals.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/HDRenderPipeline.WaterSystem.Decals.cs @@ -1,5 +1,7 @@ using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; using Unity.Mathematics; +using UnityEngine.Assertions; using UnityEngine.Experimental.Rendering; namespace UnityEngine.Rendering.HighDefinition @@ -140,13 +142,17 @@ struct VisibleDecalData public readonly int resX => decal.resolution.x; public readonly int resY => decal.resolution.y; - public int MaterialId(WaterDecal.PassType passType) + public readonly unsafe Texture2DAtlas.TextureIdentifier GetFakeTextureIdentifier(WaterDecal.PassType passType) { - int hash = 17; - hash = hash * 23 + (int)passType; - hash = hash * 23 + materialId.GetHashCode(); - return hash; + ulong hash = 17; + hash = hash * 23 + (ulong)passType; + hash = hash * 23 + (ulong)materialId.GetHashCode(); + Texture2DAtlas.TextureIdentifier identifier = Texture2DAtlas.TextureIdentifier.None; + Assert.IsTrue(sizeof(Texture2DAtlas.TextureIdentifier) == sizeof(ulong)); + UnsafeUtility.MemCpy(&identifier, &hash, sizeof(Texture2DAtlas.TextureIdentifier)); + return identifier; } + } bool CullWaterDecals() @@ -251,7 +257,7 @@ bool CullWaterDecals() if (decal.updateMode == CustomRenderTextureUpdateMode.Realtime) decal.updateCount++; - bool ReserveAtlasSpace(WaterDecal.PassType passType, in VisibleDecalData cpuData) => m_DecalAtlas.ReserveSpace(cpuData.MaterialId(passType), cpuData.resX, cpuData.resY); + bool ReserveAtlasSpace(WaterDecal.PassType passType, in VisibleDecalData cpuData) => m_DecalAtlas.ReserveSpace(cpuData.GetFakeTextureIdentifier(passType), cpuData.resX, cpuData.resY); if (affectDeformation && !ReserveAtlasSpace(WaterDecal.PassType.Deformation, in cpuData)) needRelayout = true; @@ -292,7 +298,7 @@ void ProcessWaterDecals(CommandBuffer cmd) // Render decals in atlas if needed void FetchCoords(in VisibleDecalData cpuData, WaterDecal.PassType passType, string passName, ref Vector4 scaleBias) { - int id = cpuData.MaterialId(passType); + var id = cpuData.GetFakeTextureIdentifier(passType); if (!m_DecalAtlas.IsCached(out scaleBias, id)) { // Used in WaterDecal.shader to discard decal @@ -427,7 +433,7 @@ void UpdateWaterDecals(CommandBuffer cmd, WaterSurface currentWater) int numTiles = HDUtils.DivRoundUp((int)currentWater.deformationRes, 8); cmd.SetKeyword(horizontalDeformationKeyword, HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.supportWaterHorizontalDeformation); - + // First we need to clear the edge pixel and blur the deformation a bit cmd.SetComputeTextureParam(m_WaterDeformationCS, m_FilterDeformationKernel, HDShaderIDs._WaterDeformationBuffer, currentWater.deformationSGBuffer); cmd.SetComputeTextureParam(m_WaterDeformationCS, m_FilterDeformationKernel, HDShaderIDs._WaterDeformationBufferRW, currentWater.deformationBuffer); diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/HDRenderPipeline.WaterSystem.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/HDRenderPipeline.WaterSystem.cs index dc64aee5828..8dc15930c83 100644 --- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/HDRenderPipeline.WaterSystem.cs +++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/HDRenderPipeline.WaterSystem.cs @@ -180,7 +180,7 @@ void CheckWaterCurrentData() internal void Cleanup() { // Grab all the water surfaces in the scene. Including disabled ones (i.e. not in WaterSurface.instances). - var waterSurfaces = Object.FindObjectsByType(FindObjectsSortMode.None); + var waterSurfaces = Object.FindObjectsByType(); int numWaterSurfaces = waterSurfaces.Length; // Loop through them and display them diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteCustomLitSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteCustomLitSubTarget.cs index 24f5e85e858..33021f8ffca 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteCustomLitSubTarget.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteCustomLitSubTarget.cs @@ -6,7 +6,7 @@ namespace UnityEditor.Rendering.Universal.ShaderGraph { sealed class UniversalSpriteCustomLitSubTarget : UniversalSubTarget { - static readonly GUID kSourceCodeGuid = new GUID("69e608b3e7e0405bbc2f259ad9cfa196"); // UniversalUnlitSubTarget.cs + static readonly UnityEngine.GUID kSourceCodeGuid = new UnityEngine.GUID("69e608b3e7e0405bbc2f259ad9cfa196"); // UniversalUnlitSubTarget.cs public UniversalSpriteCustomLitSubTarget() { diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs index e508428815b..a0ce7ac4acb 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs @@ -8,7 +8,7 @@ namespace UnityEditor.Rendering.Universal.ShaderGraph { sealed class UniversalSpriteLitSubTarget : UniversalSubTarget, ILegacyTarget { - static readonly GUID kSourceCodeGuid = new GUID("ea1514729d7120344b27dcd67fbf34de"); // UniversalSpriteLitSubTarget.cs + static readonly UnityEngine.GUID kSourceCodeGuid = new UnityEngine.GUID("ea1514729d7120344b27dcd67fbf34de"); // UniversalSpriteLitSubTarget.cs public UniversalSpriteLitSubTarget() { diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteUnlitSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteUnlitSubTarget.cs index 1114ed046f2..1544a63d9bc 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteUnlitSubTarget.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteUnlitSubTarget.cs @@ -8,7 +8,7 @@ namespace UnityEditor.Rendering.Universal.ShaderGraph { sealed class UniversalSpriteUnlitSubTarget : UniversalSubTarget, ILegacyTarget { - static readonly GUID kSourceCodeGuid = new GUID("ed7c0aacec26e9646b45c96fb318e5a3"); // UniversalSpriteUnlitSubTarget.cs + static readonly UnityEngine.GUID kSourceCodeGuid = new UnityEngine.GUID("ed7c0aacec26e9646b45c96fb318e5a3"); // UniversalSpriteUnlitSubTarget.cs public UniversalSpriteUnlitSubTarget() { diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs index 1e94dfa46f9..e0b82806b1f 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 { @@ -433,27 +431,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/ShaderGUI/Shaders/ParticlesLitShader.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesLitShader.cs index 621643e1b43..9e8df9a249d 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesLitShader.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesLitShader.cs @@ -57,7 +57,9 @@ void CacheRenderersUsingThisMaterial(Material material) { m_RenderersUsingThisMaterial.Clear(); + #pragma warning disable CS0618 // Type or member is obsolete ParticleSystemRenderer[] renderers = UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete foreach (ParticleSystemRenderer renderer in renderers) { if (renderer.sharedMaterial == material) diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesSimpleLitShader.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesSimpleLitShader.cs index 8d3ab6717b8..fcaae57fbd2 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesSimpleLitShader.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesSimpleLitShader.cs @@ -59,7 +59,9 @@ void CacheRenderersUsingThisMaterial(Material material) { m_RenderersUsingThisMaterial.Clear(); + #pragma warning disable CS0618 // Type or member is obsolete ParticleSystemRenderer[] renderers = UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete foreach (ParticleSystemRenderer renderer in renderers) { if (renderer.sharedMaterial == material) diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesUnlitShader.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesUnlitShader.cs index 9c569e07e14..c8c0f0061f1 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesUnlitShader.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/Shaders/ParticlesUnlitShader.cs @@ -57,7 +57,9 @@ void CacheRenderersUsingThisMaterial(Material material) { m_RenderersUsingThisMaterial.Clear(); + #pragma warning disable CS0618 // Type or member is obsolete ParticleSystemRenderer[] renderers = UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete foreach (ParticleSystemRenderer renderer in renderers) { if (renderer.sharedMaterial == material) diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUISubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUISubTarget.cs index d86aad86f18..e43d46482b4 100644 --- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUISubTarget.cs +++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUISubTarget.cs @@ -7,7 +7,7 @@ namespace UnityEditor.Rendering.Universal.ShaderGraph { class UniversalUISubTarget: UISubTarget { - static readonly GUID kSourceCodeGuid = new GUID("b1197b10aa62577498d67cffe1d3bd43"); // UniversalUISubTarget.cs + static readonly UnityEngine.GUID kSourceCodeGuid = new UnityEngine.GUID("b1197b10aa62577498d67cffe1d3bd43"); // UniversalUISubTarget.cs static readonly string kUITKPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UITKPass.hlsl"; public override void Setup(ref TargetSetupContext context) diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs index 409a3e715a5..9f02ae5723a 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; } @@ -70,7 +69,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{} } @@ -1058,17 +1056,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; @@ -1234,7 +1230,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, shader = shader, passData = passData, diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/DeferredLights.cs b/Packages/com.unity.render-pipelines.universal/Runtime/DeferredLights.cs index 4ab5e97816b..6a0f880c667 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/DeferredLights.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/DeferredLights.cs @@ -444,7 +444,7 @@ internal void ReAllocateGBufferIfNeeded(RenderTextureDescriptor gbufferSlice, in if (this.GbufferRTHandles != null) { // In case DeferredLight does not own the RTHandle, we can skip realloc. - if (this.GbufferRTHandles[gbufferIndex].GetInstanceID() != this.GbufferAttachments[gbufferIndex].GetInstanceID()) + if (this.GbufferRTHandles[gbufferIndex].GetUniqueID() != this.GbufferAttachments[gbufferIndex].GetUniqueID()) return; gbufferSlice.depthStencilFormat = GraphicsFormat.None; // make sure no depth surface is actually created diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/LightCookieManager.cs b/Packages/com.unity.render-pipelines.universal/Runtime/LightCookieManager.cs index e27fc4e29dd..e5c20b91e39 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/LightCookieManager.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/LightCookieManager.cs @@ -677,7 +677,7 @@ Vector4 Fetch2D(CommandBuffer cmd, Texture cookie, int cookieSizeDivisor = 1) } else { - m_AdditionalLightsCookieAtlas.AllocateTexture(cmd, ref uvScaleOffset, cookie, scaledWidth, scaledHeight); + m_AdditionalLightsCookieAtlas.AllocateTexture(cmd, ref uvScaleOffset, cookie, scaledWidth, scaledHeight, Texture2DAtlas.TextureIdentifier.None); } AdjustUVRect(ref uvScaleOffset, cookie, ref scaledCookieSize); @@ -702,7 +702,7 @@ Vector4 FetchCube(CommandBuffer cmd, Texture cookie, int cookieSizeDivisor = 1) } else { - m_AdditionalLightsCookieAtlas.AllocateTexture(cmd, ref uvScaleOffset, cookie, scaledOctCookieSize, scaledOctCookieSize); + m_AdditionalLightsCookieAtlas.AllocateTexture(cmd, ref uvScaleOffset, cookie, scaledOctCookieSize, scaledOctCookieSize, Texture2DAtlas.TextureIdentifier.None); } // Cookie size in the atlas might not match CookieTexture size. 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 ae941941cfe..e1f9f84cd45 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/AdditionalLightsShadowCasterPass.cs @@ -715,7 +715,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/RTHandleUtils.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RTHandleUtils.cs index ba1ba87dd9b..7c7d394e81b 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RTHandleUtils.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RTHandleUtils.cs @@ -15,8 +15,8 @@ internal class RTHandleResourcePool { // Dictionary tracks resources by hash and stores resources with same hash in a List (list instead of a stack because we need to be able to remove stale allocations, potentially in the middle of the stack). // The list needs to be sorted otherwise you could get inconsistent resource usage from one frame to another. - protected Dictionary> m_ResourcePool = new Dictionary>(); - protected List m_RemoveList = new List(32); // Used to remove stale resources as there is no RemoveAll on SortedLists + protected Dictionary> m_ResourcePool = new Dictionary>(); + protected List m_RemoveList = new List(32); // Used to remove stale resources as there is no RemoveAll on SortedLists protected static int s_CurrentStaleResourceCount = 0; // Keep stale resources alive for 3 frames @@ -56,11 +56,11 @@ internal bool AddResourceToPool(in TextureDesc texDesc, RTHandle resource, int c if (!m_ResourcePool.TryGetValue(hashCode, out var list)) { // Init list with max capacity to avoid runtime GC.Alloc when calling list.Add(resize list) - list = new SortedList(s_StaleResourceMaxCapacity); + list = new SortedList(s_StaleResourceMaxCapacity); m_ResourcePool.Add(hashCode, list); } - list.Add(resource.GetInstanceID(), (resource, currentFrameIndex)); + list.Add(resource.GetUniqueID(), (resource, currentFrameIndex)); s_CurrentStaleResourceCount++; return true; @@ -71,7 +71,7 @@ internal bool AddResourceToPool(in TextureDesc texDesc, RTHandle resource, int c internal bool TryGetResource(in TextureDesc texDesc, out RTHandle resource, bool usepool = true) { int hashCode = GetHashCodeWithNameHash(texDesc); - if (usepool && m_ResourcePool.TryGetValue(hashCode, out SortedList list) && list.Count > 0) + if (usepool && m_ResourcePool.TryGetValue(hashCode, out SortedList list) && list.Count > 0) { resource = list.Values[list.Count - 1].resource; list.RemoveAt(list.Count - 1); // O(1) since it's the last element. diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/DecalRendererFeature.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/DecalRendererFeature.cs index f4cd828cf3d..f2d5cb60480 100644 --- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/DecalRendererFeature.cs +++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/DecalRendererFeature.cs @@ -88,7 +88,9 @@ public DecalEntityManager Get() m_DecalEntityManager = new DecalEntityManager(); + #pragma warning disable CS0618 // Type or member is obsolete var decalProjectors = GameObject.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete foreach (var decalProjector in decalProjectors) { if (!decalProjector.isActiveAndEnabled || m_DecalEntityManager.IsValid(decalProjector.decalEntity)) diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs b/Packages/com.unity.render-pipelines.universal/Runtime/UniversalRendererRenderGraph.cs index 543f1c8c2eb..557377db42c 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/Samples~/URPPackageSamples/SharedAssets/Scripts/CheckAssignedRenderPipelineAsset.cs b/Packages/com.unity.render-pipelines.universal/Samples~/URPPackageSamples/SharedAssets/Scripts/CheckAssignedRenderPipelineAsset.cs index 5a39ee48731..32bdf7f89e8 100644 --- a/Packages/com.unity.render-pipelines.universal/Samples~/URPPackageSamples/SharedAssets/Scripts/CheckAssignedRenderPipelineAsset.cs +++ b/Packages/com.unity.render-pipelines.universal/Samples~/URPPackageSamples/SharedAssets/Scripts/CheckAssignedRenderPipelineAsset.cs @@ -26,7 +26,7 @@ private void Update() private void SetAllCamerasEnabled(bool enable) { - Camera[] allCameras = FindObjectsByType(FindObjectsInactive.Include, FindObjectsSortMode.None); + Camera[] allCameras = FindObjectsByType(FindObjectsInactive.Include); foreach (Camera c in allCameras) c.enabled = enable; } diff --git a/Packages/com.unity.render-pipelines.universal/Tests/Editor/RenderPassCullingTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Editor/RenderPassCullingTests.cs index 4168f18fb1c..0aa8ae307b8 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Editor/RenderPassCullingTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Editor/RenderPassCullingTests.cs @@ -22,7 +22,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer var cullingResults = cullContextData.Cull(ref cullingParameters); - var lightsInScene = Object.FindObjectsByType(FindObjectsSortMode.None); + var lightsInScene = Object.FindObjectsByType(); Assert.IsTrue(cullingResults.visibleLights.Length == lightsInScene.Length); } } 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.render-pipelines.universal/Tests/Runtime/Light2DTests.cs b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/Light2DTests.cs index cc65f17420d..362572f4445 100644 --- a/Packages/com.unity.render-pipelines.universal/Tests/Runtime/Light2DTests.cs +++ b/Packages/com.unity.render-pipelines.universal/Tests/Runtime/Light2DTests.cs @@ -19,7 +19,7 @@ class MultipleObjectLight2DTests [OneTimeSetUp] public void OneTimeSetup() { - var allGameObjectsInScene = Object.FindObjectsByType(FindObjectsSortMode.None); + var allGameObjectsInScene = Object.FindObjectsByType(); foreach (var go in allGameObjectsInScene) { Object.DestroyImmediate(go); 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 dbf054a7067..17083ee1ac5 100644 --- a/Packages/com.unity.shadergraph/Documentation~/TableOfContents.md +++ b/Packages/com.unity.shadergraph/Documentation~/TableOfContents.md @@ -278,7 +278,6 @@ * [Terrain](Terrain-Nodes.md) * [Terrain Properties](Terrain-Properties-Node.md) * [Terrain Texture](Terrain-Texture-Node.md) - * Layers * [UI](ui-nodes.md) * [Default Bitmap Text](default-bitmap-text-node.md) * [Default Gradient](default-gradient-node.md) @@ -356,8 +355,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/Data/SubGraph/SubGraphOutputNode.cs b/Packages/com.unity.shadergraph/Editor/Data/SubGraph/SubGraphOutputNode.cs index d14dcd14e97..2b71f4fcc39 100644 --- a/Packages/com.unity.shadergraph/Editor/Data/SubGraph/SubGraphOutputNode.cs +++ b/Packages/com.unity.shadergraph/Editor/Data/SubGraph/SubGraphOutputNode.cs @@ -27,6 +27,12 @@ class SubGraphOutputNode : AbstractMaterialNode }; public bool IsFirstSlotValid = true; + // Returns true if the given slot is non-null and the slot's data may be used to render a preview + public static bool IsPreviewableType(MaterialSlot slot) + { + return slot == null ? false : s_ValidSlotTypes.Contains(slot.concreteValueType); + } + public SubGraphOutputNode() { name = "Output"; @@ -75,7 +81,7 @@ void ValidateSlotType() { owner.AddValidationError(objectId, s_MissingOutputSlot, ShaderCompilerMessageSeverity.Error); } - else if (!s_ValidSlotTypes.Contains(slots.FirstOrDefault().concreteValueType)) + else if (!IsPreviewableType(slots.FirstOrDefault())) { IsFirstSlotValid = false; owner.AddValidationError(objectId, "Preview can only compile if the first output slot is a Vector, Matrix, or Boolean type. Please adjust slot types.", ShaderCompilerMessageSeverity.Error); diff --git a/Packages/com.unity.shadergraph/Editor/Drawing/Inspector/MasterPreviewView.cs b/Packages/com.unity.shadergraph/Editor/Drawing/Inspector/MasterPreviewView.cs index 6780a27ef64..c661348917a 100644 --- a/Packages/com.unity.shadergraph/Editor/Drawing/Inspector/MasterPreviewView.cs +++ b/Packages/com.unity.shadergraph/Editor/Drawing/Inspector/MasterPreviewView.cs @@ -42,7 +42,6 @@ public VisualElement preview } List m_DoNotShowPrimitives = new List(new string[] { PrimitiveType.Plane.ToString() }); - static Type s_ObjectSelector = AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypesOrNothing()).FirstOrDefault(t => t.FullName == "UnityEditor.ObjectSelector"); public string assetName { @@ -154,12 +153,6 @@ void ChangeMesh(Mesh mesh) m_Graph.previewData.serializedMesh.mesh = changedMesh; } - private static EditorWindow Get() - { - PropertyInfo P = s_ObjectSelector.GetProperty("get", BindingFlags.Public | BindingFlags.Static); - return P.GetValue(null, null) as EditorWindow; - } - void OnMeshChanged(Object obj) { var mesh = obj as Mesh; @@ -178,9 +171,7 @@ void ChangeMeshSprite() void ChangeMeshCustom() { - var ShowMethod = s_ObjectSelector.GetMethod("Show", BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { typeof(UnityEngine.Object), typeof(Type), typeof(UnityEngine.Object), typeof(bool), typeof(List), typeof(Action), typeof(Action), typeof(bool) }, new ParameterModifier[8]); - m_PreviousMesh = m_Graph.previewData.serializedMesh.mesh; - ShowMethod.Invoke(Get(), new object[] { null, typeof(Mesh), null, false, null, (Action)OnMeshChanged, (Action)OnMeshChanged, false }); + InternalBridge.ObjectSelector.Show(null, typeof(Mesh), null, false, null, (Action)OnMeshChanged, (Action)OnMeshChanged, false); } void OnGeometryChanged(GeometryChangedEvent evt) diff --git a/Packages/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ShaderInputPropertyDrawer.cs b/Packages/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ShaderInputPropertyDrawer.cs index ba4199930cc..2657bbc4439 100644 --- a/Packages/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ShaderInputPropertyDrawer.cs +++ b/Packages/com.unity.shadergraph/Editor/Drawing/Inspector/PropertyDrawers/ShaderInputPropertyDrawer.cs @@ -1499,11 +1499,15 @@ void CustomAttributesAddCallbacks() m_CustomAttributesReorderableList.drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) => { var entry = (AbstractShaderProperty.PropertyAttribute)m_CustomAttributesReorderableList.list[index]; - Rect displayRect = new Rect(rect.x, rect.y, rect.width / 2, EditorGUIUtility.singleLineHeight); + float entryHeight = EditorGUIUtility.singleLineHeight; + float columnWidth = rect.width / 2; + float verticalPadding = (rect.height - entryHeight) / 2; + Rect nameDisplayRect = new Rect(rect.x, rect.y + verticalPadding, columnWidth, entryHeight); + Rect valueDisplayRect = new Rect(rect.x + columnWidth, rect.y + verticalPadding, columnWidth, entryHeight); EditorGUI.BeginChangeCheck(); - var name = EditorGUI.DelayedTextField(displayRect, entry.name, EditorStyles.label); - var value = EditorGUI.DelayedTextField(new Rect(rect.x + rect.width / 2, rect.y, rect.width / 2, EditorGUIUtility.singleLineHeight), entry.value); + var name = EditorGUI.DelayedTextField(nameDisplayRect, entry.name, EditorStyles.label); + var value = EditorGUI.DelayedTextField(valueDisplayRect, entry.value); if (EditorGUI.EndChangeCheck()) { 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.shadergraph/Editor/Drawing/Views/Slots/ColorRGBSlotControlView.cs b/Packages/com.unity.shadergraph/Editor/Drawing/Views/Slots/ColorRGBSlotControlView.cs index 65a6049a255..f47522c2ee7 100644 --- a/Packages/com.unity.shadergraph/Editor/Drawing/Views/Slots/ColorRGBSlotControlView.cs +++ b/Packages/com.unity.shadergraph/Editor/Drawing/Views/Slots/ColorRGBSlotControlView.cs @@ -17,7 +17,7 @@ public ColorRGBSlotControlView(ColorRGBMaterialSlot slot) m_Slot = slot; var colorField = new ColorField { - value = new Color(slot.value.x, slot.value.y, slot.value.z, 0), + value = new Color(slot.value.x, slot.value.y, slot.value.z, 1), showEyeDropper = false, showAlpha = false, hdr = (slot.colorMode == ColorMode.HDR) diff --git a/Packages/com.unity.shadergraph/Editor/Generation/Processors/GenerationUtils.cs b/Packages/com.unity.shadergraph/Editor/Generation/Processors/GenerationUtils.cs index 984f2c0b1dd..e64e1b0f20e 100644 --- a/Packages/com.unity.shadergraph/Editor/Generation/Processors/GenerationUtils.cs +++ b/Packages/com.unity.shadergraph/Editor/Generation/Processors/GenerationUtils.cs @@ -1040,7 +1040,7 @@ internal static void GenerateSurfaceDescriptionStruct(ShaderStringBuilder surfac if (isSubgraphOutput) { var firstSlot = slots.FirstOrDefault(); - if (firstSlot != null) + if (SubGraphOutputNode.IsPreviewableType(firstSlot)) { var hlslName = $"{NodeUtils.GetHLSLSafeName(firstSlot.shaderOutputName)}_{firstSlot.id}"; surfaceDescriptionStruct.AppendLine("{0} {1};", firstSlot.concreteValueType.ToShaderString(firstSlot.owner.concretePrecision), hlslName); @@ -1206,7 +1206,7 @@ static void GenerateSurfaceDescriptionRemap( else if (rootNode is SubGraphOutputNode) { var slot = slots.FirstOrDefault(); - if (slot != null) + if (SubGraphOutputNode.IsPreviewableType(slot)) { var foundEdges = graph.GetEdges(slot.slotReference).ToArray(); var hlslName = $"{NodeUtils.GetHLSLSafeName(slot.shaderOutputName)}_{slot.id}"; diff --git a/Packages/com.unity.shadergraph/Editor/InternalBridge.meta b/Packages/com.unity.shadergraph/Editor/InternalBridge.meta new file mode 100644 index 00000000000..2796bd32ce0 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/InternalBridge.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 50b9bb6f7fe7e51458e183e41bffa310 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.shadergraph/Editor/InternalBridge/AssemblyInfo.cs b/Packages/com.unity.shadergraph/Editor/InternalBridge/AssemblyInfo.cs new file mode 100644 index 00000000000..a4920ad6a35 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/InternalBridge/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Unity.ShaderGraph.Editor")] diff --git a/Packages/com.unity.shadergraph/Editor/InternalBridge/AssemblyInfo.cs.meta b/Packages/com.unity.shadergraph/Editor/InternalBridge/AssemblyInfo.cs.meta new file mode 100644 index 00000000000..bc8edc2440e --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/InternalBridge/AssemblyInfo.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: c32b02309f04b344ca1c4fad2f488866 \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/InternalBridge/ObjectSelector.cs b/Packages/com.unity.shadergraph/Editor/InternalBridge/ObjectSelector.cs new file mode 100644 index 00000000000..93b056e66b6 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/InternalBridge/ObjectSelector.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; +using System; +using UnityEngine; + +namespace UnityEditor.ShaderGraph.InternalBridge +{ + internal static class ObjectSelector + { + public static void Show(UnityEngine.Object obj, Type requiredType, UnityEngine.Object objectBeingEdited, + bool allowSceneObjects, List allowedEntityIds = null, + Action onObjectSelectorClosed = null, + Action onObjectSelectedUpdated = null, bool showNoneItem = true) + { + UnityEditor.ObjectSelector.get.Show(obj, requiredType, objectBeingEdited, allowSceneObjects, + allowedEntityIds, onObjectSelectorClosed, onObjectSelectedUpdated, showNoneItem); + } + } +} diff --git a/Packages/com.unity.shadergraph/Editor/InternalBridge/ObjectSelector.cs.meta b/Packages/com.unity.shadergraph/Editor/InternalBridge/ObjectSelector.cs.meta new file mode 100644 index 00000000000..46ab78589b9 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/InternalBridge/ObjectSelector.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: a6e816750db52e34e8e463c3377a974e \ No newline at end of file diff --git a/Packages/com.unity.shadergraph/Editor/InternalBridge/Unity.InternalAPIEditorBridge.ShaderGraph.Editor.asmdef b/Packages/com.unity.shadergraph/Editor/InternalBridge/Unity.InternalAPIEditorBridge.ShaderGraph.Editor.asmdef new file mode 100644 index 00000000000..c0bf03c82c3 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/InternalBridge/Unity.InternalAPIEditorBridge.ShaderGraph.Editor.asmdef @@ -0,0 +1,16 @@ +{ + "name": "Unity.InternalAPIEditorBridge.ShaderGraph.Editor", + "rootNamespace": "", + "references": [], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} diff --git a/Packages/com.unity.shadergraph/Editor/InternalBridge/Unity.InternalAPIEditorBridge.ShaderGraph.Editor.asmdef.meta b/Packages/com.unity.shadergraph/Editor/InternalBridge/Unity.InternalAPIEditorBridge.ShaderGraph.Editor.asmdef.meta new file mode 100644 index 00000000000..b7144fe72c1 --- /dev/null +++ b/Packages/com.unity.shadergraph/Editor/InternalBridge/Unity.InternalAPIEditorBridge.ShaderGraph.Editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 1a9e721432c3e5048950da7f3cf524e7 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Packages/com.unity.shadergraph/Editor/Unity.ShaderGraph.Editor.asmdef b/Packages/com.unity.shadergraph/Editor/Unity.ShaderGraph.Editor.asmdef index ff92c7fbe19..56222167c93 100644 --- a/Packages/com.unity.shadergraph/Editor/Unity.ShaderGraph.Editor.asmdef +++ b/Packages/com.unity.shadergraph/Editor/Unity.ShaderGraph.Editor.asmdef @@ -5,7 +5,8 @@ "GUID:ade7125e800904674ba0c115208f7ed5", "GUID:4988cf9794f41d64c884876ab6574b89", "GUID:df380645f10b7bc4b97d4f5eb6303d95", - "GUID:3eae0364be2026648bf74846acb8a731" + "GUID:3eae0364be2026648bf74846acb8a731", + "GUID:1a9e721432c3e5048950da7f3cf524e7" ], "includePlatforms": [ "Editor" diff --git a/Packages/com.unity.visualeffectgraph/Editor/Utilities/Playables/VisualEffectControlClipInspector.cs b/Packages/com.unity.visualeffectgraph/Editor/Utilities/Playables/VisualEffectControlClipInspector.cs index 4733ae0711b..731461d3cd8 100644 --- a/Packages/com.unity.visualeffectgraph/Editor/Utilities/Playables/VisualEffectControlClipInspector.cs +++ b/Packages/com.unity.visualeffectgraph/Editor/Utilities/Playables/VisualEffectControlClipInspector.cs @@ -30,7 +30,9 @@ public override void OnInspectorGUI() serializedObject.ApplyModifiedProperties(); //Modification on tracks doesn't trigger a refresh, calling manually the director refresh +#pragma warning disable CS0618 // Type or member is obsolete var allDirectors = FindObjectsByType(FindObjectsInactive.Exclude, FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete foreach (var director in allDirectors) { director.RebuildGraph(); 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/Packages/com.unity.testing.hdrp/Scripts/Editor/GraphicTestTools.cs b/Tests/SRPTests/Packages/com.unity.testing.hdrp/Scripts/Editor/GraphicTestTools.cs index e6197c2db82..23c56f79658 100644 --- a/Tests/SRPTests/Packages/com.unity.testing.hdrp/Scripts/Editor/GraphicTestTools.cs +++ b/Tests/SRPTests/Packages/com.unity.testing.hdrp/Scripts/Editor/GraphicTestTools.cs @@ -33,7 +33,9 @@ public static void MakeMaterialSceneInstance() [MenuItem("Internal/GraphicTest Tools/Update All Material Placers")] public static void UpdateAllPlacers() { +#pragma warning disable CS0618 // Type or member is obsolete MultiMaterialPlacer[] placers = Object.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete for (int i = 0; i < placers.Length; ++i) { diff --git a/Tests/SRPTests/Packages/com.unity.testing.hdrp/TestRunner/Editor/HDRP_TestSettings_Editor.cs b/Tests/SRPTests/Packages/com.unity.testing.hdrp/TestRunner/Editor/HDRP_TestSettings_Editor.cs index 6261a2c87cd..557261d805f 100644 --- a/Tests/SRPTests/Packages/com.unity.testing.hdrp/TestRunner/Editor/HDRP_TestSettings_Editor.cs +++ b/Tests/SRPTests/Packages/com.unity.testing.hdrp/TestRunner/Editor/HDRP_TestSettings_Editor.cs @@ -102,7 +102,9 @@ override public void OnInspectorGUI() if (GUILayout.Button("Fix Texts")) { +#pragma warning disable CS0618 // Type or member is obsolete TextMeshPixelSize[] texts = FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete foreach (TextMeshPixelSize text in texts) { text.CorrectPosition(); diff --git a/Tests/SRPTests/Packages/com.unity.testing.hdrp/TestRunner/HDRP_GraphicTestRunner.cs b/Tests/SRPTests/Packages/com.unity.testing.hdrp/TestRunner/HDRP_GraphicTestRunner.cs index 9faf120ee0f..ab1ccdccaaa 100644 --- a/Tests/SRPTests/Packages/com.unity.testing.hdrp/TestRunner/HDRP_GraphicTestRunner.cs +++ b/Tests/SRPTests/Packages/com.unity.testing.hdrp/TestRunner/HDRP_GraphicTestRunner.cs @@ -55,9 +55,9 @@ public static IEnumerator Run(SceneGraphicsTestCase testCase) for (int i = 0; i < 5; ++i) yield return new WaitForEndOfFrame(); - settings = GameObject.FindFirstObjectByType(); + settings = GameObject.FindAnyObjectByType(); camera = GameObject.FindGameObjectWithTag("MainCamera").GetComponent(); - if (camera == null) camera = GameObject.FindFirstObjectByType(); + if (camera == null) camera = GameObject.FindAnyObjectByType(); if (camera == null) { Assert.Fail("Missing camera for graphic tests."); @@ -103,9 +103,9 @@ public static IEnumerator Run(SceneGraphicsTestCase testCase) yield return new WaitForEndOfFrame(); // Need to retrieve objects again after scene reload. - settings = GameObject.FindFirstObjectByType(); + settings = GameObject.FindAnyObjectByType(); camera = GameObject.FindGameObjectWithTag("MainCamera").GetComponent(); - if (camera == null) camera = GameObject.FindFirstObjectByType(); + if (camera == null) camera = GameObject.FindAnyObjectByType(); if (camera == null) { Assert.Fail("Missing camera for graphic tests."); @@ -115,7 +115,9 @@ public static IEnumerator Run(SceneGraphicsTestCase testCase) HDCamera hdCamera = HDCamera.GetOrCreate(camera); //We need to get all the cameras to set accumulation in all of them for tests that uses multiple cameras +#pragma warning disable CS0618 // Type or member is obsolete cameras = GameObject.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 // Type or member is obsolete //Grab the HDCameras hdCameras = new HDCamera[cameras.Length]; @@ -158,7 +160,9 @@ public static IEnumerator Run(SceneGraphicsTestCase testCase) settings.ImageComparisonSettings.PerPixelCorrectnessThreshold *= settings.xrThresholdMultiplier; // Increase number of volumetric slices to compensate for initial half-resolution due to XR single-pass optimization +#pragma warning disable CS0618 // Type or member is obsolete foreach (var volume in GameObject.FindObjectsByType(FindObjectsSortMode.InstanceID)) +#pragma warning restore CS0618 // Type or member is obsolete { if (volume.profile.TryGet(out Fog fog)) fog.volumeSliceCount.value *= 2; @@ -216,7 +220,7 @@ public static IEnumerator Run(SceneGraphicsTestCase testCase) for (int i = 0; i < waitFrames; ++i) yield return new WaitForEndOfFrame(); - var settingsSG = (GameObject.FindFirstObjectByType() as HDRP_ShaderGraph_TestSettings); + var settingsSG = (GameObject.FindAnyObjectByType() as HDRP_ShaderGraph_TestSettings); if (settingsSG == null || !settingsSG.compareSGtoBI) { // Standard Test diff --git a/Tests/SRPTests/Packages/com.unity.testing.hdrp/TestRunner/TextMeshPixelSize.cs b/Tests/SRPTests/Packages/com.unity.testing.hdrp/TestRunner/TextMeshPixelSize.cs index 91c457590ef..ae7de1611ee 100644 --- a/Tests/SRPTests/Packages/com.unity.testing.hdrp/TestRunner/TextMeshPixelSize.cs +++ b/Tests/SRPTests/Packages/com.unity.testing.hdrp/TestRunner/TextMeshPixelSize.cs @@ -26,7 +26,7 @@ ImageComparisonSettings safeSettings if (testSettings != null) o = testSettings.ImageComparisonSettings; if (o == null && targetCamera != null) o = targetCamera.gameObject.GetComponentInChildren()?.ImageComparisonSettings; - if (o == null) o = FindFirstObjectByType()?.ImageComparisonSettings; + if (o == null) o = FindAnyObjectByType()?.ImageComparisonSettings; if (o == null) o = new ImageComparisonSettings() { TargetWidth = forceTargetDimensions.x, TargetHeight = forceTargetDimensions.y }; // use overrides as defaults return o; @@ -54,7 +54,7 @@ Vector2Int targetSize void CorrectSize() { - if (targetCamera == null) targetCamera = FindFirstObjectByType(); + if (targetCamera == null) targetCamera = FindAnyObjectByType(); if (targetCamera == null) return; if (textMesh == null) textMesh = GetComponent(); diff --git a/Tests/SRPTests/Packages/com.unity.testing.visualeffectgraph/Tests/Runtime/VFXGraphicsTests.cs b/Tests/SRPTests/Packages/com.unity.testing.visualeffectgraph/Tests/Runtime/VFXGraphicsTests.cs index 76a07a02f3e..723a1fb3c86 100644 --- a/Tests/SRPTests/Packages/com.unity.testing.visualeffectgraph/Tests/Runtime/VFXGraphicsTests.cs +++ b/Tests/SRPTests/Packages/com.unity.testing.visualeffectgraph/Tests/Runtime/VFXGraphicsTests.cs @@ -71,11 +71,13 @@ public static IEnumerator Run(SceneGraphicsTestCase testCase) Unity.Testing.XR.Runtime.ConfigureMockHMD.SetupTest(xrCompatible, 0, imageComparisonSettings); #if VFX_TESTS_HAS_HDRP +#pragma warning disable CS0618 foreach (var volume in GameObject.FindObjectsByType(FindObjectsSortMode.InstanceID)) { if (volume.profile.TryGet(out var fog)) fog.volumeSliceCount.value *= 2; } +#pragma warning restore CS0618 #endif } diff --git a/Tests/SRPTests/Projects/MultipleSRP_Tests/Assets/Common/Editor/BaseGraphicsTests.cs b/Tests/SRPTests/Projects/MultipleSRP_Tests/Assets/Common/Editor/BaseGraphicsTests.cs index c39dda05ebf..c0c32fab4f0 100644 --- a/Tests/SRPTests/Projects/MultipleSRP_Tests/Assets/Common/Editor/BaseGraphicsTests.cs +++ b/Tests/SRPTests/Projects/MultipleSRP_Tests/Assets/Common/Editor/BaseGraphicsTests.cs @@ -81,10 +81,10 @@ public IEnumerator Run(SceneGraphicsTestCase testCase) yield return new EnterPlayMode(); - var settings = Object.FindFirstObjectByType(); + var settings = Object.FindAnyObjectByType(); Assert.IsNotNull(settings, "Invalid test scene, couldn't find CrossPipelineTestsSettings"); - var camera = GameObject.FindFirstObjectByType(); + var camera = GameObject.FindAnyObjectByType(); Assert.IsNotNull(camera, "Missing camera for graphic tests."); //Adjust camera to be sure that everything required by the test fits in the FOV diff --git a/Tests/SRPTests/Projects/SRP_SmokeTest/Assets/Tests/Editor/RenderGraphViewer/RenderGraphViewerDebugDataSerializationTests.cs b/Tests/SRPTests/Projects/SRP_SmokeTest/Assets/Tests/Editor/RenderGraphViewer/RenderGraphViewerDebugDataSerializationTests.cs index eadd1842f18..4a30f84f4b6 100644 --- a/Tests/SRPTests/Projects/SRP_SmokeTest/Assets/Tests/Editor/RenderGraphViewer/RenderGraphViewerDebugDataSerializationTests.cs +++ b/Tests/SRPTests/Projects/SRP_SmokeTest/Assets/Tests/Editor/RenderGraphViewer/RenderGraphViewerDebugDataSerializationTests.cs @@ -11,6 +11,18 @@ namespace UnityEditor.Rendering.Tests { class RenderGraphViewerDebugDataSerializationTests { + static EntityId CreateTestEntityId(int intValue) + { + EntityId testEntityId; + unsafe + { + UnityEngine.Debug.Assert(sizeof(int) == sizeof(EntityId)); + testEntityId = *(EntityId*)&intValue; + } + + return testEntityId; + } + static RenderGraph.DebugData CreateTestDebugData() { RenderGraph.DebugData debugData = new("TestExecution"); @@ -156,9 +168,7 @@ public void DebugMessageHandler_DebugDataMessage_IsSerializedCorrectly() { version = DebugMessageHandler.k_Version, graphName = "TestGraph", -#pragma warning disable 618 // todo @emilie.thaulow replace with unique id - executionId = 123, -#pragma warning restore 618 + executionId = CreateTestEntityId(123), debugData = CreateTestDebugData() }; @@ -196,9 +206,7 @@ public void DebugMessageHandler_DebugDataMessage_IsCompatibleWithSerializedVersi Assert.True(deserializedPayload.isCompatible); Assert.AreEqual(DebugMessageHandler.k_Version, deserializedPayload.version); -#pragma warning disable 618 // todo @emilie.thaulow replace with unique id - Assert.AreEqual(123, (int)deserializedDebugDataPayload.executionId); -#pragma warning restore 618 + Assert.AreEqual(CreateTestEntityId(123), deserializedDebugDataPayload.executionId); Assert.AreEqual("TestGraph", deserializedDebugDataPayload.graphName); Assert.NotNull(deserializedDebugDataPayload.debugData); } @@ -210,9 +218,7 @@ public static void DoSomething() { version = DebugMessageHandler.k_Version, graphName = "TestGraph", -#pragma warning disable 618 // todo @emilie.thaulow replace with unique id - executionId = 123, -#pragma warning restore 618 + executionId = CreateTestEntityId(123), debugData = CreateTestDebugData() }; diff --git a/Tests/SRPTests/Projects/SRP_SmokeTest/Assets/Tests/Editor/SRPSmoke.Editor.Tests.asmdef b/Tests/SRPTests/Projects/SRP_SmokeTest/Assets/Tests/Editor/SRPSmoke.Editor.Tests.asmdef index 43b78e4f5bb..02c2be0bb2c 100644 --- a/Tests/SRPTests/Projects/SRP_SmokeTest/Assets/Tests/Editor/SRPSmoke.Editor.Tests.asmdef +++ b/Tests/SRPTests/Projects/SRP_SmokeTest/Assets/Tests/Editor/SRPSmoke.Editor.Tests.asmdef @@ -19,7 +19,7 @@ "Editor" ], "excludePlatforms": [], - "allowUnsafeCode": false, + "allowUnsafeCode": true, "overrideReferences": true, "precompiledReferences": [ "nunit.framework.dll" diff --git a/Tests/SRPTests/Projects/ShaderGraph/Assets/CommonAssets/Editor/MaterialCreator.cs b/Tests/SRPTests/Projects/ShaderGraph/Assets/CommonAssets/Editor/MaterialCreator.cs index 790d4d0dbc2..ebbbbec2b71 100644 --- a/Tests/SRPTests/Projects/ShaderGraph/Assets/CommonAssets/Editor/MaterialCreator.cs +++ b/Tests/SRPTests/Projects/ShaderGraph/Assets/CommonAssets/Editor/MaterialCreator.cs @@ -27,7 +27,9 @@ static void CreateMaterials() [MenuItem("Tools/SG Tests/Get Rid of Underscores")] static void KillUnderscores() { +#pragma warning disable CS0618 GameObject[] allObjects = UnityEngine.Object.FindObjectsByType(FindObjectsSortMode.InstanceID); +#pragma warning restore CS0618 foreach (GameObject go in allObjects) { go.name = go.name.Replace("_", ""); diff --git a/Tests/SRPTests/Projects/ShaderGraph/Assets/CommonAssets/Scripts/ShaderGraphGraphicsTests.cs b/Tests/SRPTests/Projects/ShaderGraph/Assets/CommonAssets/Scripts/ShaderGraphGraphicsTests.cs index 603f9859a81..32fcb688f72 100644 --- a/Tests/SRPTests/Projects/ShaderGraph/Assets/CommonAssets/Scripts/ShaderGraphGraphicsTests.cs +++ b/Tests/SRPTests/Projects/ShaderGraph/Assets/CommonAssets/Scripts/ShaderGraphGraphicsTests.cs @@ -43,7 +43,7 @@ public IEnumerator Run(SceneGraphicsTestCase testCase) yield return null; var camera = GameObject.FindGameObjectWithTag("MainCamera").GetComponent(); - var settings = Object.FindFirstObjectByType(); + var settings = Object.FindAnyObjectByType(); Assert.IsNotNull(settings, "Invalid test scene, couldn't find ShaderGraphGraphicsTestSettings"); settings.OnTestBegin(); diff --git a/Tests/SRPTests/Projects/ShaderGraphUniversalStereo/Assets/CommonAssets/Scripts/LWGraphicsTests.cs b/Tests/SRPTests/Projects/ShaderGraphUniversalStereo/Assets/CommonAssets/Scripts/LWGraphicsTests.cs index cecf3b0033d..4553a3ac321 100644 --- a/Tests/SRPTests/Projects/ShaderGraphUniversalStereo/Assets/CommonAssets/Scripts/LWGraphicsTests.cs +++ b/Tests/SRPTests/Projects/ShaderGraphUniversalStereo/Assets/CommonAssets/Scripts/LWGraphicsTests.cs @@ -27,7 +27,7 @@ public IEnumerator Run(GraphicsTestCase testCase) yield return null; var cameras = GameObject.FindGameObjectsWithTag("MainCamera").Select(x=>x.GetComponent()); - var settings = Object.FindFirstObjectByType(); + var settings = Object.FindAnyObjectByType(); Assert.IsNotNull(settings, "Invalid test scene, couldn't find LWGraphicsTestSettings"); // Stereo screen capture on Mac generates monoscopic images and won't be fixed. diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937.meta new file mode 100644 index 00000000000..fa89a8aef99 --- /dev/null +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 631a99d02461475cb9d48a3b86a70960 +timeCreated: 1764124845 \ No newline at end of file diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources.meta new file mode 100644 index 00000000000..16ce83418d2 --- /dev/null +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 55a1a5558f68a2c47825a9bcb4382453 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources/UUM127937SG.shadergraph b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources/UUM127937SG.shadergraph new file mode 100644 index 00000000000..249d6bc1cd0 --- /dev/null +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources/UUM127937SG.shadergraph @@ -0,0 +1,949 @@ +{ + "m_SGVersion": 3, + "m_Type": "UnityEditor.ShaderGraph.GraphData", + "m_ObjectId": "468cad4b8a9d47c0b94f545a25290969", + "m_Properties": [ + { + "m_Id": "717c4bfd2adf4f5dbb84b2d5d712ded2" + }, + { + "m_Id": "f83f36a9fa5748158e136fc667b47c71" + } + ], + "m_Keywords": [], + "m_Dropdowns": [], + "m_CategoryData": [ + { + "m_Id": "891621aaec554f0b97981df82914be23" + } + ], + "m_Nodes": [ + { + "m_Id": "d9a1fe5907164a40af97432a3e6c957c" + }, + { + "m_Id": "71e89e1482b5425a99f5e9c3428f99ea" + }, + { + "m_Id": "0cf20c690b37412b9ffe64bf2c2241f9" + }, + { + "m_Id": "3c923239e3e34109945dfc365b82686c" + }, + { + "m_Id": "54b906f5dfb24981b1f22716eaeaf4f4" + }, + { + "m_Id": "2b8eb6bcbcd54392a7e6cb3758839e88" + }, + { + "m_Id": "19d2d4f1e8db47068cb5e3ba63723c75" + }, + { + "m_Id": "9503b50f8dcc4061958b8ac5d0d5ddf5" + }, + { + "m_Id": "599646d3eb46420aa9a247281e93d8dc" + } + ], + "m_GroupDatas": [], + "m_StickyNoteDatas": [], + "m_Edges": [ + { + "m_OutputSlot": { + "m_Node": { + "m_Id": "19d2d4f1e8db47068cb5e3ba63723c75" + }, + "m_SlotId": 0 + }, + "m_InputSlot": { + "m_Node": { + "m_Id": "2b8eb6bcbcd54392a7e6cb3758839e88" + }, + "m_SlotId": 1 + } + }, + { + "m_OutputSlot": { + "m_Node": { + "m_Id": "2b8eb6bcbcd54392a7e6cb3758839e88" + }, + "m_SlotId": 0 + }, + "m_InputSlot": { + "m_Node": { + "m_Id": "599646d3eb46420aa9a247281e93d8dc" + }, + "m_SlotId": 0 + } + }, + { + "m_OutputSlot": { + "m_Node": { + "m_Id": "599646d3eb46420aa9a247281e93d8dc" + }, + "m_SlotId": 2 + }, + "m_InputSlot": { + "m_Node": { + "m_Id": "3c923239e3e34109945dfc365b82686c" + }, + "m_SlotId": 0 + } + }, + { + "m_OutputSlot": { + "m_Node": { + "m_Id": "9503b50f8dcc4061958b8ac5d0d5ddf5" + }, + "m_SlotId": 0 + }, + "m_InputSlot": { + "m_Node": { + "m_Id": "599646d3eb46420aa9a247281e93d8dc" + }, + "m_SlotId": 1 + } + } + ], + "m_VertexContext": { + "m_Position": { + "x": 0.0, + "y": 0.0 + }, + "m_Blocks": [ + { + "m_Id": "d9a1fe5907164a40af97432a3e6c957c" + }, + { + "m_Id": "71e89e1482b5425a99f5e9c3428f99ea" + }, + { + "m_Id": "0cf20c690b37412b9ffe64bf2c2241f9" + } + ] + }, + "m_FragmentContext": { + "m_Position": { + "x": 0.0, + "y": 200.0 + }, + "m_Blocks": [ + { + "m_Id": "3c923239e3e34109945dfc365b82686c" + }, + { + "m_Id": "54b906f5dfb24981b1f22716eaeaf4f4" + } + ] + }, + "m_PreviewData": { + "serializedMesh": { + "m_SerializedMesh": "{\"mesh\":{\"instanceID\":0}}", + "m_Guid": "" + }, + "preventRotation": false + }, + "m_Path": "Shader Graphs", + "m_GraphPrecision": 1, + "m_PreviewMode": 2, + "m_OutputNode": { + "m_Id": "" + }, + "m_SubDatas": [], + "m_ActiveTargets": [ + { + "m_Id": "46e90e85969c4afabc6b33999c4a5695" + } + ] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Vector3MaterialSlot", + "m_ObjectId": "030da3741548473fa9e150d5af8dbdf5", + "m_Id": 2, + "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 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "0cf20c690b37412b9ffe64bf2c2241f9", + "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": "9ca59f6665fd410a8b6e4358f7828d00" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_DismissedVersion": 0, + "m_PreviewMode": 0, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "VertexDescription.Tangent" +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Vector1MaterialSlot", + "m_ObjectId": "0d3e5445e17f44b8a36051d7b0759e12", + "m_Id": 1, + "m_DisplayName": "Saturation", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "Saturation", + "m_StageCapability": 3, + "m_Value": 1.0, + "m_DefaultValue": 1.0, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.PropertyNode", + "m_ObjectId": "19d2d4f1e8db47068cb5e3ba63723c75", + "m_Group": { + "m_Id": "" + }, + "m_Name": "Property", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": -852.3104858398438, + "y": 152.48277282714845, + "width": 0.0, + "height": 0.0 + } + }, + "m_Slots": [ + { + "m_Id": "7bd84d8534e345f780d11d9992f2fe60" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_DismissedVersion": 0, + "m_PreviewMode": 0, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_Property": { + "m_Id": "717c4bfd2adf4f5dbb84b2d5d712ded2" + } +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Vector1MaterialSlot", + "m_ObjectId": "1b4c48b74a7342fa8d413677c86b4ece", + "m_Id": 7, + "m_DisplayName": "A", + "m_SlotType": 1, + "m_Hidden": false, + "m_ShaderOutputName": "A", + "m_StageCapability": 2, + "m_Value": 0.0, + "m_DefaultValue": 0.0, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Vector1MaterialSlot", + "m_ObjectId": "20b90824bd4846ce9cf6ac8bf1782774", + "m_Id": 0, + "m_DisplayName": "Saturation", + "m_SlotType": 1, + "m_Hidden": false, + "m_ShaderOutputName": "Out", + "m_StageCapability": 3, + "m_Value": 0.0, + "m_DefaultValue": 0.0, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.SampleTexture2DNode", + "m_ObjectId": "2b8eb6bcbcd54392a7e6cb3758839e88", + "m_Group": { + "m_Id": "" + }, + "m_Name": "Sample Texture 2D", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": -606.517333984375, + "y": 137.68966674804688, + "width": 0.0, + "height": 0.0 + } + }, + "m_Slots": [ + { + "m_Id": "5be952bc445647b79ff490e718778679" + }, + { + "m_Id": "a1bc0453052f4515b5cb293e976a574e" + }, + { + "m_Id": "b63cab73877f4727a3772aa9d08d83de" + }, + { + "m_Id": "c8335c78228c47eda1c4430043158f95" + }, + { + "m_Id": "1b4c48b74a7342fa8d413677c86b4ece" + }, + { + "m_Id": "47bea00c95b142429e8cdcae907e5bac" + }, + { + "m_Id": "6323a38d96d94769b0f7065537799ed8" + }, + { + "m_Id": "3675d7a152944690b984a041ee47e9e3" + } + ], + "synonyms": [ + "tex2d" + ], + "m_Precision": 0, + "m_PreviewExpanded": false, + "m_DismissedVersion": 0, + "m_PreviewMode": 0, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_TextureType": 0, + "m_NormalMapSpace": 0, + "m_EnableGlobalMipBias": true, + "m_MipSamplingMode": 0 +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.SamplerStateMaterialSlot", + "m_ObjectId": "3675d7a152944690b984a041ee47e9e3", + "m_Id": 3, + "m_DisplayName": "Sampler", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "Sampler", + "m_StageCapability": 3, + "m_BareResource": false +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "3c923239e3e34109945dfc365b82686c", + "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": "db0ffc587e2b43c49843f46ff88ee9c4" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_DismissedVersion": 0, + "m_PreviewMode": 0, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "SurfaceDescription.BaseColor" +} + +{ + "m_SGVersion": 1, + "m_Type": "UnityEditor.Rendering.Universal.ShaderGraph.UniversalTarget", + "m_ObjectId": "46e90e85969c4afabc6b33999c4a5695", + "m_Datas": [], + "m_ActiveSubTarget": { + "m_Id": "fa5aca91ee5443edac682642281bd154" + }, + "m_AllowMaterialOverride": false, + "m_SurfaceType": 0, + "m_ZTestMode": 4, + "m_ZWriteControl": 0, + "m_AlphaMode": 0, + "m_RenderFace": 2, + "m_AlphaClip": false, + "m_CastShadows": true, + "m_ReceiveShadows": true, + "m_DisableTint": false, + "m_AdditionalMotionVectorMode": 0, + "m_AlembicMotionVectors": false, + "m_SupportsLODCrossFade": false, + "m_CustomEditorGUI": "", + "m_SupportVFX": false +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Texture2DInputMaterialSlot", + "m_ObjectId": "47bea00c95b142429e8cdcae907e5bac", + "m_Id": 1, + "m_DisplayName": "Texture", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "Texture", + "m_StageCapability": 3, + "m_BareResource": false, + "m_Texture": { + "m_SerializedTexture": "", + "m_Guid": "" + }, + "m_DefaultType": 0 +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "54b906f5dfb24981b1f22716eaeaf4f4", + "m_Group": { + "m_Id": "" + }, + "m_Name": "SurfaceDescription.Alpha", + "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": "749366c0afac4d7898a504b283c0c086" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_DismissedVersion": 0, + "m_PreviewMode": 0, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "SurfaceDescription.Alpha" +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.SaturationNode", + "m_ObjectId": "599646d3eb46420aa9a247281e93d8dc", + "m_Group": { + "m_Id": "" + }, + "m_Name": "Saturation", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": -257.0, + "y": 171.0, + "width": 173.99996948242188, + "height": 117.99996948242188 + } + }, + "m_Slots": [ + { + "m_Id": "8dd80cdda9fb421585b59b9282dad629" + }, + { + "m_Id": "0d3e5445e17f44b8a36051d7b0759e12" + }, + { + "m_Id": "030da3741548473fa9e150d5af8dbdf5" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": false, + "m_DismissedVersion": 0, + "m_PreviewMode": 0, + "m_CustomColors": { + "m_SerializableColors": [] + } +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Vector4MaterialSlot", + "m_ObjectId": "5be952bc445647b79ff490e718778679", + "m_Id": 0, + "m_DisplayName": "RGBA", + "m_SlotType": 1, + "m_Hidden": false, + "m_ShaderOutputName": "RGBA", + "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.UVMaterialSlot", + "m_ObjectId": "6323a38d96d94769b0f7065537799ed8", + "m_Id": 2, + "m_DisplayName": "UV", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "UV", + "m_StageCapability": 3, + "m_Value": { + "x": 0.0, + "y": 0.0 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0 + }, + "m_Labels": [], + "m_Channel": 0 +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Internal.Texture2DShaderProperty", + "m_ObjectId": "717c4bfd2adf4f5dbb84b2d5d712ded2", + "m_Guid": { + "m_GuidSerialized": "ec020eae-8f7c-43a3-ab40-8b828b1e3148" + }, + "m_Name": "MainTex", + "m_DefaultRefNameVersion": 1, + "m_RefNameGeneratedByDisplayName": "MainTex", + "m_DefaultReferenceName": "_MainTex", + "m_OverrideReferenceName": "", + "m_GeneratePropertyBlock": true, + "m_UseCustomSlotLabel": false, + "m_CustomSlotLabel": "", + "m_DismissedVersion": 0, + "m_Precision": 0, + "overrideHLSLDeclaration": false, + "hlslDeclarationOverride": 0, + "m_Hidden": false, + "m_Value": { + "m_SerializedTexture": "", + "m_Guid": "" + }, + "isMainTexture": false, + "useTilingAndOffset": false, + "m_Modifiable": true, + "m_DefaultType": 0 +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "71e89e1482b5425a99f5e9c3428f99ea", + "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": "89b68402558a4dc4bd5f8f4fdb048401" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_DismissedVersion": 0, + "m_PreviewMode": 0, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "VertexDescription.Normal" +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Vector1MaterialSlot", + "m_ObjectId": "749366c0afac4d7898a504b283c0c086", + "m_Id": 0, + "m_DisplayName": "Alpha", + "m_SlotType": 0, + "m_Hidden": false, + "m_ShaderOutputName": "Alpha", + "m_StageCapability": 2, + "m_Value": 1.0, + "m_DefaultValue": 1.0, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Texture2DMaterialSlot", + "m_ObjectId": "7bd84d8534e345f780d11d9992f2fe60", + "m_Id": 0, + "m_DisplayName": "MainTex", + "m_SlotType": 1, + "m_Hidden": false, + "m_ShaderOutputName": "Out", + "m_StageCapability": 3, + "m_BareResource": false +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.CategoryData", + "m_ObjectId": "891621aaec554f0b97981df82914be23", + "m_Name": "", + "m_ChildObjectList": [ + { + "m_Id": "717c4bfd2adf4f5dbb84b2d5d712ded2" + }, + { + "m_Id": "f83f36a9fa5748158e136fc667b47c71" + } + ] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.PositionMaterialSlot", + "m_ObjectId": "899d02fd88664dca848b4ae9fbdae787", + "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.NormalMaterialSlot", + "m_ObjectId": "89b68402558a4dc4bd5f8f4fdb048401", + "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.Vector3MaterialSlot", + "m_ObjectId": "8dd80cdda9fb421585b59b9282dad629", + "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 + }, + "m_DefaultValue": { + "x": 0.0, + "y": 0.0, + "z": 0.0 + }, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.PropertyNode", + "m_ObjectId": "9503b50f8dcc4061958b8ac5d0d5ddf5", + "m_Group": { + "m_Id": "" + }, + "m_Name": "Property", + "m_DrawState": { + "m_Expanded": true, + "m_Position": { + "serializedVersion": "2", + "x": -396.0, + "y": 296.0, + "width": 129.0, + "height": 34.0 + } + }, + "m_Slots": [ + { + "m_Id": "20b90824bd4846ce9cf6ac8bf1782774" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_DismissedVersion": 0, + "m_PreviewMode": 0, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_Property": { + "m_Id": "f83f36a9fa5748158e136fc667b47c71" + } +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.TangentMaterialSlot", + "m_ObjectId": "9ca59f6665fd410a8b6e4358f7828d00", + "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.Vector1MaterialSlot", + "m_ObjectId": "a1bc0453052f4515b5cb293e976a574e", + "m_Id": 4, + "m_DisplayName": "R", + "m_SlotType": 1, + "m_Hidden": false, + "m_ShaderOutputName": "R", + "m_StageCapability": 2, + "m_Value": 0.0, + "m_DefaultValue": 0.0, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Vector1MaterialSlot", + "m_ObjectId": "b63cab73877f4727a3772aa9d08d83de", + "m_Id": 5, + "m_DisplayName": "G", + "m_SlotType": 1, + "m_Hidden": false, + "m_ShaderOutputName": "G", + "m_StageCapability": 2, + "m_Value": 0.0, + "m_DefaultValue": 0.0, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.Vector1MaterialSlot", + "m_ObjectId": "c8335c78228c47eda1c4430043158f95", + "m_Id": 6, + "m_DisplayName": "B", + "m_SlotType": 1, + "m_Hidden": false, + "m_ShaderOutputName": "B", + "m_StageCapability": 2, + "m_Value": 0.0, + "m_DefaultValue": 0.0, + "m_Labels": [] +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.BlockNode", + "m_ObjectId": "d9a1fe5907164a40af97432a3e6c957c", + "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": "899d02fd88664dca848b4ae9fbdae787" + } + ], + "synonyms": [], + "m_Precision": 0, + "m_PreviewExpanded": true, + "m_DismissedVersion": 0, + "m_PreviewMode": 0, + "m_CustomColors": { + "m_SerializableColors": [] + }, + "m_SerializedDescriptor": "VertexDescription.Position" +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.ShaderGraph.ColorRGBMaterialSlot", + "m_ObjectId": "db0ffc587e2b43c49843f46ff88ee9c4", + "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.5, + "y": 0.5, + "z": 0.5 + }, + "m_Labels": [], + "m_ColorMode": 0, + "m_DefaultColor": { + "r": 0.5, + "g": 0.5, + "b": 0.5, + "a": 1.0 + } +} + +{ + "m_SGVersion": 1, + "m_Type": "UnityEditor.ShaderGraph.Internal.Vector1ShaderProperty", + "m_ObjectId": "f83f36a9fa5748158e136fc667b47c71", + "m_Guid": { + "m_GuidSerialized": "176f765f-1b1b-4d70-90be-4e64c089d6c6" + }, + "m_Name": "Saturation", + "m_DefaultRefNameVersion": 1, + "m_RefNameGeneratedByDisplayName": "Saturation", + "m_DefaultReferenceName": "_Saturation", + "m_OverrideReferenceName": "", + "m_GeneratePropertyBlock": true, + "m_UseCustomSlotLabel": false, + "m_CustomSlotLabel": "", + "m_DismissedVersion": 0, + "m_Precision": 0, + "overrideHLSLDeclaration": false, + "hlslDeclarationOverride": 0, + "m_Hidden": false, + "m_Value": 1.0, + "m_FloatType": 0, + "m_RangeValues": { + "x": 0.0, + "y": 1.0 + } +} + +{ + "m_SGVersion": 0, + "m_Type": "UnityEditor.Rendering.Universal.ShaderGraph.UniversalSpriteUnlitSubTarget", + "m_ObjectId": "fa5aca91ee5443edac682642281bd154" +} + diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources/UUM127937SG.shadergraph.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources/UUM127937SG.shadergraph.meta new file mode 100644 index 00000000000..506e03daa7a --- /dev/null +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources/UUM127937SG.shadergraph.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 1c620119ff2084043832208bbe47fd6d +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources/smallGreenStar.png b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources/smallGreenStar.png new file mode 100644 index 00000000000..4c671a71d58 Binary files /dev/null and b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources/smallGreenStar.png differ diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources/smallGreenStar.png.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources/smallGreenStar.png.meta new file mode 100644 index 00000000000..e7b5dca049d --- /dev/null +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/Resources/smallGreenStar.png.meta @@ -0,0 +1,170 @@ +fileFormatVersion: 2 +guid: 219bc3fdfd18baf4ca58e09a522239b5 +TextureImporter: + fileIDToRecycleName: {} + externalObjects: {} + serializedVersion: 7 + 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: 1 + 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: 0 + lightmap: 0 + compressionQuality: 50 + spriteMode: 1 + 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: 1 + spriteTessellationDetail: -1 + textureType: 8 + textureShape: 1 + singleChannelComponent: 0 + maxTextureSizeSet: 0 + compressionQualitySet: 0 + textureFormatSet: 0 + platformSettings: + - serializedVersion: 2 + buildTarget: DefaultTexturePlatform + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + - serializedVersion: 2 + buildTarget: Standalone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + - serializedVersion: 2 + buildTarget: iPhone + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + - serializedVersion: 2 + buildTarget: tvOS + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + - serializedVersion: 2 + buildTarget: WebGL + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + - serializedVersion: 2 + buildTarget: Windows Store Apps + maxTextureSize: 2048 + resizeAlgorithm: 0 + textureFormat: -1 + textureCompression: 1 + compressionQuality: 50 + crunchedCompression: 0 + allowsAlphaSplitting: 0 + overridden: 0 + androidETC2FallbackOverride: 0 + spriteSheet: + serializedVersion: 2 + sprites: [] + outline: + - - {x: -7, y: 16} + - {x: -16, y: 7} + - {x: -16, y: -13} + - {x: -15, y: -16} + - {x: 16, y: -16} + - {x: 16, y: 14} + - {x: 10, y: 16} + physicsShape: + - - {x: 2, y: 15} + - {x: -1, y: 15} + - {x: -4, y: 4} + - {x: -14.931009, y: 3.978939} + - {x: -15, y: 1} + - {x: -7, y: -4} + - {x: -7, y: -6} + - {x: -10, y: -15} + - {x: -7, y: -15} + - {x: 1, y: -9} + - {x: 7, y: -15} + - {x: 11, y: -15} + - {x: 8, y: -4} + - {x: 16, y: 2} + - {x: 16, y: 4} + - {x: 5, y: 4} + - - {x: -2, y: -4} + - {x: -2, y: 1} + - {x: 4, y: 1} + - {x: 4, y: -4} + bones: [] + spriteID: 2e67f41127f80634b8bbd443a396fec5 + vertices: [] + indices: + edges: [] + weights: [] + spritePackingTag: + pSDRemoveMatte: 0 + pSDShowRemoveMatteOption: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/UUM127937.cs b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/UUM127937.cs new file mode 100644 index 00000000000..c7df87bc43f --- /dev/null +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/UUM127937.cs @@ -0,0 +1,32 @@ +using UnityEngine; + +namespace SpriteRendererTests +{ + [RequireComponent(typeof(SpriteRenderer))] + public class UUM127937: MonoBehaviour + { + private static readonly int Saturation = Shader.PropertyToID("_Saturation"); + private static readonly int AnotherProp = Shader.PropertyToID("_AnotherProp"); + + public static readonly float sDefault = 0.2f; + + private void Start() + { + SpriteRenderer ren = this.GetComponent(); + MaterialPropertyBlock propertyBlock = new(); + ren.GetPropertyBlock(propertyBlock); + propertyBlock.SetFloat(Saturation, sDefault); + propertyBlock.SetFloat(AnotherProp, sDefault); + ren.SetPropertyBlock(propertyBlock); + } + + public float GetSaturation() + { + SpriteRenderer ren = this.GetComponent(); + MaterialPropertyBlock propertyBlock = new(); + ren.GetPropertyBlock(propertyBlock); + var saturation = propertyBlock.GetFloat(Saturation); + return saturation; + } + } +} diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/UUM127937.cs.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/UUM127937.cs.meta new file mode 100644 index 00000000000..4ec71bb36f5 --- /dev/null +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/UUM127937.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 009846b1a4b14bbcac6569bf36b91f7f +timeCreated: 1764124864 \ No newline at end of file diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/UUM127937Test.cs b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/UUM127937Test.cs new file mode 100644 index 00000000000..1a488bf8e79 --- /dev/null +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/UUM127937Test.cs @@ -0,0 +1,145 @@ +using System.Collections; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Rendering.Universal; +using UnityEngine.TestTools; + +#if UNITY_EDITOR +using UnityEditor; +#endif + +namespace SpriteRendererTests +{ + public class UUM127937Test + { + GameObject m_TestGo; + SpriteRenderer m_SpriteRenderer; + UUM127937 m_UUM127937; + + private GameObject m_BaseObj; + private Camera m_BaseCamera; + private UniversalAdditionalCameraData m_BaseCameraData; + + private bool m_OriginalUseSRPBatching = true; + + [OneTimeSetUp] + public void OneTimeSetup() + { + m_BaseObj = new GameObject(); + m_BaseObj.transform.position = new Vector3(0.0f, 0.0f, -10.0f); + m_BaseObj.transform.forward = Vector3.forward; + m_BaseCamera = m_BaseObj.AddComponent(); + m_BaseCameraData = m_BaseObj.AddComponent(); + + m_BaseCamera.allowHDR = false; + m_BaseCamera.clearFlags = CameraClearFlags.SolidColor; + m_BaseCameraData.SetRenderer(2); // 2D Renderer. See the list of Renderers in CommonAssets/UniversalRPAsset. + m_BaseCameraData.renderType = CameraRenderType.Base; + m_BaseCameraData.renderPostProcessing = false; + m_BaseCamera.targetTexture = new RenderTexture(m_BaseCamera.pixelWidth, m_BaseCamera.pixelHeight, 24); + +#if UNITY_EDITOR + EditorApplication.ExecuteMenuItem("Window/General/Game"); +#endif + } + + [SetUp] + public void Setup() + { + m_TestGo = new GameObject("TestGo"); + m_SpriteRenderer = m_TestGo.AddComponent(); + var sprite = Resources.Load("smallGreenStar"); + var material = Resources.Load("UUM127937SG"); + Assert.NotNull(sprite); + Assert.NotNull(material); + m_SpriteRenderer.sprite = sprite; + m_SpriteRenderer.material = material; + m_UUM127937 = m_TestGo.AddComponent(); + } + + [TearDown] + public void TearDown() + { + Object.Destroy(m_TestGo); + } + + [OneTimeTearDown] + public void OneTimeCleanup() + { + Object.DestroyImmediate(m_BaseObj); + } + + [UnityTest] + [UnityPlatform(RuntimePlatform.OSXEditor, RuntimePlatform.LinuxEditor, RuntimePlatform.WindowsEditor)] + public IEnumerator SpriteRenderer_ChangeSerializedProperty_Color_DoesNotClearMaterialPropertyBlock() + { + yield return null; + yield return null; + + var startSaturation = m_UUM127937.GetSaturation(); + + Assert.AreEqual(UUM127937.sDefault, startSaturation); + + yield return null; + +#if UNITY_EDITOR + SerializedObject so = new SerializedObject(m_SpriteRenderer); + SerializedProperty sp = so.FindProperty("m_Color"); + Assert.NotNull(sp); + + so.Update(); + + sp.colorValue = Color.white; + sp.colorValue = Color.rebeccaPurple; + + so.ApplyModifiedProperties(); + + yield return null; + + Assert.AreEqual(Color.rebeccaPurple, m_SpriteRenderer.color); +#endif + + yield return null; + + var endSaturation = m_UUM127937.GetSaturation(); + + Assert.AreEqual(startSaturation, endSaturation); + } + + [UnityTest] + [UnityPlatform(RuntimePlatform.OSXEditor, RuntimePlatform.LinuxEditor, RuntimePlatform.WindowsEditor)] + public IEnumerator SpriteRenderer_ChangeSerializedProperty_Flip_DoesNotClearMaterialPropertyBlock() + { + yield return null; + yield return null; + + var startSaturation = m_UUM127937.GetSaturation(); + + Assert.AreEqual(UUM127937.sDefault, startSaturation); + + yield return null; + +#if UNITY_EDITOR + SerializedObject so = new SerializedObject(m_SpriteRenderer); + SerializedProperty sp = so.FindProperty("m_FlipX"); + Assert.NotNull(sp); + + so.Update(); + + sp.boolValue = !sp.boolValue; + + so.ApplyModifiedProperties(); + + yield return null; + + Assert.AreEqual(true, m_SpriteRenderer.flipX); +#endif + + yield return null; + + var endSaturation = m_UUM127937.GetSaturation(); + + Assert.AreEqual(startSaturation, endSaturation); + } + } +} diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/UUM127937Test.cs.meta b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/UUM127937Test.cs.meta new file mode 100644 index 00000000000..a9c406a6069 --- /dev/null +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_2D/Assets/Test/Runtime/UUM127937/UUM127937Test.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ce52904ff5d44b79ba074c5344e2ec5f +timeCreated: 1764124779 \ No newline at end of file diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/210_Motion_Vectors/Scripts/FixedTimeParamsUploader.cs b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/210_Motion_Vectors/Scripts/FixedTimeParamsUploader.cs index aa78d362f83..0a79f9d72dd 100644 --- a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/210_Motion_Vectors/Scripts/FixedTimeParamsUploader.cs +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/210_Motion_Vectors/Scripts/FixedTimeParamsUploader.cs @@ -11,7 +11,9 @@ public class FixedTimeParamsUploader : MonoBehaviour void Start() { - m_MeshRenderers = FindObjectsByType(FindObjectsInactive.Include, FindObjectsSortMode.None); +#pragma warning disable CS0618 // Type or member is obsolete + m_MeshRenderers = FindObjectsByType(FindObjectsInactive.Include); +#pragma warning restore CS0618 // Type or member is obsolete } void Update() diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/210_Motion_Vectors/Scripts/SceneFixedTimeAnimatorUpdater.cs b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/210_Motion_Vectors/Scripts/SceneFixedTimeAnimatorUpdater.cs index 0ea55d8aa65..5e7bb6c96e0 100644 --- a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/210_Motion_Vectors/Scripts/SceneFixedTimeAnimatorUpdater.cs +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/210_Motion_Vectors/Scripts/SceneFixedTimeAnimatorUpdater.cs @@ -10,7 +10,9 @@ public class SceneFixedTimeAnimatorUpdater : MonoBehaviour void Start() { m_SceneAnimators = new List(); - var foundObjects = FindObjectsByType(FindObjectsInactive.Include, FindObjectsSortMode.None); +#pragma warning disable CS0618 // Type or member is obsolete + var foundObjects = FindObjectsByType(FindObjectsInactive.Include); +#pragma warning restore CS0618 // Type or member is obsolete if (foundObjects != null) { foreach (var obj in foundObjects) diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/210_Motion_Vectors/Scripts/SceneFixedTimePlayableDirectorUpdater.cs b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/210_Motion_Vectors/Scripts/SceneFixedTimePlayableDirectorUpdater.cs index c6d68c6d5cc..2b5158e1b1f 100644 --- a/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/210_Motion_Vectors/Scripts/SceneFixedTimePlayableDirectorUpdater.cs +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_Foundation/Assets/Scenes/210_Motion_Vectors/Scripts/SceneFixedTimePlayableDirectorUpdater.cs @@ -12,7 +12,9 @@ public class SceneFixedTimePlayableDirectorUpdater : MonoBehaviour void Start() { m_ScenePlayableDirectors = new List(); - var foundObjects = FindObjectsByType(FindObjectsInactive.Include, FindObjectsSortMode.None); +#pragma warning disable CS0618 // Type or member is obsolete + var foundObjects = FindObjectsByType(FindObjectsInactive.Include); +#pragma warning restore CS0618 // Type or member is obsolete if (foundObjects != null) { foreach (var obj in foundObjects) diff --git a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/133_DepthOfField_DynamicResolution/SetDynamicResolution.cs b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/133_DepthOfField_DynamicResolution/SetDynamicResolution.cs index a631e0467cf..81ba6e12cd1 100644 --- a/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/133_DepthOfField_DynamicResolution/SetDynamicResolution.cs +++ b/Tests/SRPTests/Projects/UniversalGraphicsTest_PostPro/Assets/Scenes/133_DepthOfField_DynamicResolution/SetDynamicResolution.cs @@ -8,7 +8,7 @@ public class SetDynamicResolution : MonoBehaviour private void Start() { - var cameras = FindObjectsByType(FindObjectsInactive.Exclude, FindObjectsSortMode.None); + var cameras = FindObjectsByType(FindObjectsInactive.Exclude); foreach (var camera in cameras) camera.allowDynamicResolution = true; ScalableBufferManager.ResizeBuffers(scale, scale); diff --git a/Tests/SRPTests/Projects/VisualEffectGraph_URP/Assets/GraphicsTests/Instancing/SplitGroupStressTest.cs b/Tests/SRPTests/Projects/VisualEffectGraph_URP/Assets/GraphicsTests/Instancing/SplitGroupStressTest.cs index f7e9189e533..2402cd7541a 100644 --- a/Tests/SRPTests/Projects/VisualEffectGraph_URP/Assets/GraphicsTests/Instancing/SplitGroupStressTest.cs +++ b/Tests/SRPTests/Projects/VisualEffectGraph_URP/Assets/GraphicsTests/Instancing/SplitGroupStressTest.cs @@ -23,7 +23,7 @@ public class SplitGroupStressTest : MonoBehaviour void Start() { - m_OriginalVisualEffects = new List(FindObjectsByType(FindObjectsSortMode.None)); + m_OriginalVisualEffects = new List(FindObjectsByType()); m_VisualEffects = new List(MaxInstanceCount); // To test global texture support