Example #1
0
        public override void Build()
        {
            m_cubemapSize = GetCubemapResolutionFromQualityLevel(QualitySettings.GetQualityLevel());

            m_spaceSkyMaterial             = CoreUtils.CreateEngineMaterial("Hidden/SpaceSky");
            m_spaceSkyCubemapRenderTexture = HDRenderUtilities.CreateReflectionProbeRenderTarget(m_cubemapSize);
        }
 public void RenderThrowWhenFrameSettingsIsNull()
 {
     Assert.Throws <ArgumentNullException>(() => HDRenderUtilities.Render(
                                               default(CameraSettings),
                                               default(CameraPositionSettings),
                                               Texture2D.whiteTexture
                                               ));
 }
 public void RenderThrowWhenTargetIsNull()
 {
     Assert.Throws <ArgumentNullException>(() => HDRenderUtilities.Render(
                                               default(CameraSettings),
                                               default(CameraPositionSettings),
                                               null
                                               ));
 }
 public void RenderThrowWhenFrameSettingsIsNull()
 {
     // should throw error that Texture2D is no RenderTexture
     Assert.Throws <ArgumentException>(() => HDRenderUtilities.Render(
                                           default(CameraSettings),
                                           default(CameraPositionSettings),
                                           Texture2D.whiteTexture
                                           ));
 }
 public void RenderThrowWhenTargetIsNotARenderTextureForTex2DRendering()
 {
     Assert.Throws <ArgumentException>(() => HDRenderUtilities.Render(
                                           new CameraSettings
     {
         frameSettings = new FrameSettings()
     },
                                           default(CameraPositionSettings),
                                           Texture2D.whiteTexture
                                           ));
 }
Example #6
0
        internal static void RenderAndWriteToFile(
            HDProbe probe, string targetFile,
            RenderTexture cubeRT, RenderTexture planarRT,
            out CameraSettings cameraSettings,
            out CameraPositionSettings cameraPositionSettings
            )
        {
            var settings = probe.settings;

            switch (settings.type)
            {
            case ProbeSettings.ProbeType.ReflectionProbe:
            {
                var positionSettings = ProbeCapturePositionSettings.ComputeFrom(probe, null);
                HDRenderUtilities.Render(probe.settings, positionSettings, cubeRT,
                                         out cameraSettings, out cameraPositionSettings,
                                         forceFlipY: true,
                                         forceInvertBackfaceCulling: true, // Cubemap have an RHS standard, so we need to invert the face culling
                                         (uint)StaticEditorFlags.ReflectionProbeStatic
                                         );
                HDBakingUtilities.CreateParentDirectoryIfMissing(targetFile);
                Checkout(targetFile);
                HDTextureUtilities.WriteTextureFileToDisk(cubeRT, targetFile);
                break;
            }

            case ProbeSettings.ProbeType.PlanarProbe:
            {
                var planarProbe      = (PlanarReflectionProbe)probe;
                var positionSettings = ProbeCapturePositionSettings.ComputeFromMirroredReference(
                    probe,
                    planarProbe.referencePosition
                    );

                HDRenderUtilities.Render(
                    settings,
                    positionSettings,
                    planarRT,
                    out cameraSettings, out cameraPositionSettings
                    );
                HDBakingUtilities.CreateParentDirectoryIfMissing(targetFile);
                Checkout(targetFile);
                HDTextureUtilities.WriteTextureFileToDisk(planarRT, targetFile);
                var renderData           = new HDProbe.RenderData(cameraSettings, cameraPositionSettings);
                var targetRenderDataFile = targetFile + ".renderData";
                Checkout(targetRenderDataFile);
                HDBakingUtilities.TrySerializeToDisk(renderData, targetRenderDataFile);
                break;
            }

            default: throw new ArgumentOutOfRangeException(nameof(probe.settings.type));
            }
        }
Example #7
0
        protected override bool Update(BuiltinSkyParameters builtinParams)
        {
            var newResolution = GetCubemapResolutionFromQualityLevel(QualitySettings.GetQualityLevel());

            if (m_cubemapSize != newResolution)
            {
                CoreUtils.Destroy(m_spaceSkyCubemapRenderTexture);
                m_cubemapSize = newResolution;
                m_spaceSkyCubemapRenderTexture = HDRenderUtilities.CreateReflectionProbeRenderTarget(m_cubemapSize);
                m_prevHashCodeInitialized      = false;

                return(true);
            }

            return(false);
        }
Example #8
0
        /// <summary>
        ///     Bakes the <paramref name="probe" /> and updates its baked texture.
        ///
        ///     Note: The update of the probe is persistent only in editor mode.
        /// </summary>
        /// <param name="probe">The probe to bake.</param>
        /// <param name="path">The asset path to write the baked texture to.</param>
        /// <param name="options">The options to use for the bake.</param>
        /// <returns>
        ///     Returns <c>null</c> if successful. Otherwise, returns the error that occured.
        ///     The error can be:
        ///     * <see cref="ArgumentException" /> if the <paramref name="path" /> is invalid.
        ///     * <see cref="ArgumentNullException" /> if the <paramref name="probe" /> is <c>null</c>.
        ///     * <see cref="Exception" /> if the <paramref name="probe" /> is not supported. Only
        ///     This functional currently only supports <see cref="HDAdditionalReflectionData" /> probes.
        /// </returns>
        public static Exception BakeProbe([NotNull] HDProbe probe, [NotNull] string path, BakeProbeOptions options)
        {
            // Check arguments
            if (probe == null || probe.Equals(null))
            {
                return(new ArgumentNullException(nameof(probe)));
            }
            if (string.IsNullOrEmpty(path))
            {
                return(new ArgumentException($"{nameof(path)} must not be empty or null."));
            }

            // We force RGBAHalf as we don't support 11-11-10 textures (only RT)
            var probeFormat = GraphicsFormat.R16G16B16A16_SFloat;

            switch (probe)
            {
            case HDAdditionalReflectionData _:
            {
                // Get the texture size from the probe
                var textureSize = options.textureSize.Evaluate(probe);

                // Render and write
                var cubeRT = HDRenderUtilities.CreateReflectionProbeRenderTarget(textureSize, probeFormat);
                HDBakedReflectionSystem.RenderAndWriteToFile(probe, path, cubeRT, null);
                cubeRT.Release();

                // Import asset at target location
                AssetDatabase.ImportAsset(path);
                HDBakedReflectionSystem.ImportAssetAt(probe, path);

                // Assign to the probe the baked texture
                var bakedTexture = AssetDatabase.LoadAssetAtPath <Texture>(path);
                probe.SetTexture(ProbeSettings.Mode.Baked, bakedTexture);

                // Mark probe as dirty
                EditorUtility.SetDirty(probe);

                return(null);
            }

            case PlanarReflectionProbe _:
                return(new Exception("Planar reflection probe baking is not supported."));

            default: return(new Exception($"Cannot handle probe type: {probe.GetType()}"));
            }
        }
Example #9
0
        static void Gizmos_CapturePoint(ReflectionProbe target)
        {
            if (sphere == null)
            {
                sphere = Resources.GetBuiltinResource <Mesh>("New-Sphere.fbx");
            }
            if (material == null)
            {
                material = new Material(Shader.Find("Debug/ReflectionProbePreview"));
            }
            var probe = target.GetComponent <HDAdditionalReflectionData>();
            var probePositionSettings = ProbeCapturePositionSettings.ComputeFrom(probe, null);

            HDRenderUtilities.ComputeCameraSettingsFromProbeSettings(
                probe.settings, probePositionSettings,
                out _, out var cameraPositionSettings
                );
            var capturePosition = cameraPositionSettings.position;

            material.SetTexture("_Cubemap", probe.texture);
            material.SetPass(0);
            Graphics.DrawMeshNow(sphere, Matrix4x4.TRS(capturePosition, Quaternion.identity, Vector3.one * capturePointPreviewSize));

            var ray = new Ray(capturePosition, Vector3.down);

            if (Physics.Raycast(ray, out RaycastHit hit))
            {
                var startPoint = capturePosition - Vector3.up * 0.5f * capturePointPreviewSize;
                var c          = InfluenceVolumeUI.k_GizmoThemeColorBase;
                c.a           = 0.8f;
                Handles.color = c;
                Handles.zTest = UnityEngine.Rendering.CompareFunction.LessEqual;
                Handles.DrawLine(startPoint, hit.point);
                Handles.DrawWireDisc(hit.point, hit.normal, 0.5f);

                c.a           = 0.25f;
                Handles.color = c;
                Handles.zTest = UnityEngine.Rendering.CompareFunction.Greater;
                Handles.DrawLine(capturePosition, hit.point);
                Handles.DrawWireDisc(hit.point, hit.normal, 0.5f);
            }
        }
Example #10
0
        public override void Tick(
            SceneStateHash sceneStateHash,
            IScriptableBakedReflectionSystemStageNotifier handle
            )
        {
            if (!AreAllOpenedSceneSaved())
            {
                handle.SetIsDone(true);
                return;
            }

            // On the C# side, we don't have non blocking asset import APIs, and we don't want to block the
            //   UI when the user is editing the world.
            //   So, we skip the baking when the user is editing any UI control.
            if (GUIUtility.hotControl != 0)
            {
                return;
            }

            if (!IsCurrentSRPValid(out HDRenderPipeline hdPipeline))
            {
                if (ShouldIssueWarningForCurrentSRP())
                {
                    Debug.LogWarning("HDBakedReflectionSystem work with HDRP, " +
                                     "Either switch your render pipeline or use a different reflection system. You may need to trigger a " +
                                     "C# domain reload to initialize the appropriate reflection system. One way to do this is to compile a script.");
                }

                handle.ExitStage((int)BakingStages.ReflectionProbes);
                handle.SetIsDone(true);
                return;
            }

            var ambientProbeHash = sceneStateHash.ambientProbeHash;
            var sceneObjectsHash = sceneStateHash.sceneObjectsHash;
            var skySettingsHash  = sceneStateHash.skySettingsHash;

            DeleteCubemapAssets(true);

            // Explanation of the algorithm:
            // 1. First we create the hash of the world that can impact the reflection probes.
            // 2. Then for each probe, we calculate a hash that represent what this specific probe should have baked.
            // 3. We compare those hashes against the baked one and decide:
            //   a. If we have to remove a baked data
            //   b. If we have to bake a probe
            // 4. Bake all required probes
            //   a. Bake probe that were added or modified
            //   b. Bake probe with a missing baked texture
            // 5. Remove unused baked data
            // 6. Update probe assets

            // == 1. ==
            var allProbeDependencyHash = new Hash128();

            // TODO: All baked probes depend on custom probes (hash all custom probes and set as dependency)
            // TODO: All baked probes depend on HDRP specific Light settings
            HashUtilities.AppendHash(ref ambientProbeHash, ref allProbeDependencyHash);
            HashUtilities.AppendHash(ref sceneObjectsHash, ref allProbeDependencyHash);
            HashUtilities.AppendHash(ref skySettingsHash, ref allProbeDependencyHash);

            var bakedProbes     = HDProbeSystem.bakedProbes;
            var bakedProbeCount = HDProbeSystem.bakedProbeCount;

            // == 2. ==
            var states = stackalloc HDProbeBakingState[bakedProbeCount];
            // A list of indices of probe we may want to force to rebake, even if the hashes matches.
            // Usually, add a probe when something external to its state or the world state forces the bake.
            var probeForcedToBakeIndices      = stackalloc int[bakedProbeCount];
            var probeForcedToBakeIndicesCount = 0;
            var probeForcedToBakeIndicesList  = new ListBuffer <int>(
                probeForcedToBakeIndices,
                &probeForcedToBakeIndicesCount,
                bakedProbeCount
                );

            ComputeProbeInstanceID(bakedProbes, states);
            ComputeProbeSettingsHashes(bakedProbes, states);
            // TODO: Handle bounce dependency here
            ComputeProbeBakingHashes(bakedProbeCount, allProbeDependencyHash, states);

            // Force to rebake probe with missing baked texture
            for (var i = 0; i < bakedProbeCount; ++i)
            {
                var instanceId = states[i].instanceID;
                var probe      = (HDProbe)EditorUtility.InstanceIDToObject(instanceId);
                if (probe.bakedTexture != null && !probe.bakedTexture.Equals(null))
                {
                    continue;
                }

                probeForcedToBakeIndicesList.TryAdd(i);
            }

            CoreUnsafeUtils.QuickSort <HDProbeBakingState, Hash128, HDProbeBakingState.ProbeBakingHash>(
                bakedProbeCount, states
                );

            int operationCount = 0, addCount = 0, remCount = 0;
            var maxProbeCount = Mathf.Max(bakedProbeCount, m_HDProbeBakedStates.Length);
            var addIndices    = stackalloc int[maxProbeCount];
            var remIndices    = stackalloc int[maxProbeCount];

            if (m_HDProbeBakedStates.Length == 0)
            {
                for (int i = 0; i < bakedProbeCount; ++i)
                {
                    addIndices[addCount++] = i;
                }
                operationCount = addCount;
            }
            else
            {
                fixed(HDProbeBakedState *oldBakedStates = &m_HDProbeBakedStates[0])
                {
                    // == 3. ==
                    // Compare hashes between baked probe states and desired probe states
                    operationCount = CoreUnsafeUtils.CompareHashes <
                        HDProbeBakedState, HDProbeBakedState.ProbeBakedHash,
                        HDProbeBakingState, HDProbeBakingState.ProbeBakingHash
                        > (
                        m_HDProbeBakedStates.Length, oldBakedStates, // old hashes
                        bakedProbeCount, states,                     // new hashes
                        addIndices, remIndices,
                        out addCount, out remCount
                        );
                }
            }

            if (operationCount > 0 || probeForcedToBakeIndicesList.Count > 0)
            {
                // == 4. ==
                var cubemapSize = (int)hdPipeline.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionCubemapSize;
                // We force RGBAHalf as we don't support 11-11-10 textures (only RT)
                var probeFormat = GraphicsFormat.R16G16B16A16_SFloat;

                var cubeRT = HDRenderUtilities.CreateReflectionProbeRenderTarget(cubemapSize, probeFormat);

                handle.EnterStage(
                    (int)BakingStages.ReflectionProbes,
                    string.Format("Reflection Probes | {0} jobs", addCount),
                    0
                    );

                // Compute indices of probes to bake: added, modified probe or with a missing baked texture.
                var toBakeIndices      = stackalloc int[bakedProbeCount];
                var toBakeIndicesCount = 0;
                var toBakeIndicesList  = new ListBuffer <int>(toBakeIndices, &toBakeIndicesCount, bakedProbeCount);
                {
                    // Note: we will add probes from change check and baked texture missing check.
                    //   So we can add at most 2 time the probe in the list.
                    var toBakeIndicesTmp      = stackalloc int[bakedProbeCount * 2];
                    var toBakeIndicesTmpCount = 0;
                    var toBakeIndicesTmpList  =
                        new ListBuffer <int>(toBakeIndicesTmp, &toBakeIndicesTmpCount, bakedProbeCount * 2);

                    // Add the indices from the added or modified detection check
                    toBakeIndicesTmpList.TryCopyFrom(addIndices, addCount);
                    // Add the probe with missing baked texture check
                    probeForcedToBakeIndicesList.TryCopyTo(toBakeIndicesTmpList);

                    // Sort indices
                    toBakeIndicesTmpList.QuickSort();
                    // Add to final list without the duplicates
                    var lastValue = int.MaxValue;
                    for (var i = 0; i < toBakeIndicesTmpList.Count; ++i)
                    {
                        if (lastValue == toBakeIndicesTmpList.GetUnchecked(i))
                        {
                            // Skip duplicates
                            continue;
                        }

                        lastValue = toBakeIndicesTmpList.GetUnchecked(i);
                        toBakeIndicesList.TryAdd(lastValue);
                    }
                }

                // Render probes that were added or modified
                for (int i = 0; i < toBakeIndicesList.Count; ++i)
                {
                    handle.EnterStage(
                        (int)BakingStages.ReflectionProbes,
                        string.Format("Reflection Probes | {0} jobs", addCount),
                        i / (float)toBakeIndicesCount
                        );

                    var index      = toBakeIndicesList.GetUnchecked(i);
                    var instanceId = states[index].instanceID;
                    var probe      = (HDProbe)EditorUtility.InstanceIDToObject(instanceId);
                    var cacheFile  = GetGICacheFileForHDProbe(states[index].probeBakingHash);

                    // Get from cache or render the probe
                    if (!File.Exists(cacheFile))
                    {
                        var planarRT = HDRenderUtilities.CreatePlanarProbeRenderTarget((int)probe.resolution, probeFormat);
                        RenderAndWriteToFile(probe, cacheFile, cubeRT, planarRT);
                        planarRT.Release();
                    }
                }
                cubeRT.Release();

                // Copy texture from cache
                for (int i = 0; i < toBakeIndicesList.Count; ++i)
                {
                    var index      = toBakeIndicesList.GetUnchecked(i);
                    var instanceId = states[index].instanceID;
                    var probe      = (HDProbe)EditorUtility.InstanceIDToObject(instanceId);
                    var cacheFile  = GetGICacheFileForHDProbe(states[index].probeBakingHash);

                    if (string.IsNullOrEmpty(probe.gameObject.scene.path))
                    {
                        continue;
                    }

                    Assert.IsTrue(File.Exists(cacheFile));

                    var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);
                    HDBakingUtilities.CreateParentDirectoryIfMissing(bakedTexturePath);
                    Checkout(bakedTexturePath);
                    // Checkout will make those file writeable, but this is not immediate,
                    // so we retries when this fails.
                    if (!HDEditorUtils.CopyFileWithRetryOnUnauthorizedAccess(cacheFile, bakedTexturePath))
                    {
                        return;
                    }
                }
                // AssetPipeline bug
                // Sometimes, the baked texture reference is destroyed during 'AssetDatabase.StopAssetEditing()'
                //   thus, the reference to the baked texture in the probe is lost
                // Although, importing twice the texture seems to workaround the issue
                for (int j = 0; j < 2; ++j)
                {
                    AssetDatabase.StartAssetEditing();
                    for (int i = 0; i < bakedProbeCount; ++i)
                    {
                        var index      = toBakeIndicesList.GetUnchecked(i);
                        var instanceId = states[index].instanceID;
                        var probe      = (HDProbe)EditorUtility.InstanceIDToObject(instanceId);
                        if (string.IsNullOrEmpty(probe.gameObject.scene.path))
                        {
                            continue;
                        }

                        var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);
                        AssetDatabase.ImportAsset(bakedTexturePath);
                        ImportAssetAt(probe, bakedTexturePath);
                    }
                    AssetDatabase.StopAssetEditing();
                }
                // Import assets
                AssetDatabase.StartAssetEditing();
                for (int i = 0; i < toBakeIndicesList.Count; ++i)
                {
                    var index      = toBakeIndicesList.GetUnchecked(i);
                    var instanceId = states[index].instanceID;
                    var probe      = (HDProbe)EditorUtility.InstanceIDToObject(instanceId);
                    if (string.IsNullOrEmpty(probe.gameObject.scene.path))
                    {
                        continue;
                    }

                    var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);
                    var bakedTexture     = AssetDatabase.LoadAssetAtPath <Texture>(bakedTexturePath);
                    Assert.IsNotNull(bakedTexture, "The baked texture was imported before, " +
                                     "so it must exists in AssetDatabase");

                    probe.SetTexture(ProbeSettings.Mode.Baked, bakedTexture);
                    EditorUtility.SetDirty(probe);
                }
                AssetDatabase.StopAssetEditing();

                // == 5. ==

                // Create new baked state array
                var targetSize        = m_HDProbeBakedStates.Length - remCount + toBakeIndicesList.Count;
                var targetBakedStates = stackalloc HDProbeBakedState[targetSize];
                // Copy baked state that are not removed
                var targetI = 0;
                for (int i = 0; i < m_HDProbeBakedStates.Length; ++i)
                {
                    if (CoreUnsafeUtils.IndexOf(remIndices, remCount, i) != -1)
                    {
                        continue;
                    }
                    Assert.IsTrue(targetI < targetSize);
                    targetBakedStates[targetI++] = m_HDProbeBakedStates[i];
                }
                // Add new baked states
                for (int i = 0; i < toBakeIndicesList.Count; ++i)
                {
                    var state = states[toBakeIndicesList.GetUnchecked(i)];
                    Assert.IsTrue(targetI < targetSize);
                    targetBakedStates[targetI++] = new HDProbeBakedState
                    {
                        instanceID     = state.instanceID,
                        probeBakedHash = state.probeBakingHash
                    };
                }
                CoreUnsafeUtils.QuickSort <HDProbeBakedState, Hash128, HDProbeBakedState.ProbeBakedHash>(
                    targetI, targetBakedStates
                    );

                Array.Resize(ref m_HDProbeBakedStates, targetSize);
                if (targetSize > 0)
                {
                    fixed(HDProbeBakedState *bakedStates = &m_HDProbeBakedStates[0])
                    {
                        UnsafeUtility.MemCpy(
                            bakedStates,
                            targetBakedStates,
                            sizeof(HDProbeBakedState) * targetSize
                            );
                    }
                }

                // Update state hash
                Array.Resize(ref m_StateHashes, m_HDProbeBakedStates.Length);
                for (int i = 0; i < m_HDProbeBakedStates.Length; ++i)
                {
                    m_StateHashes[i] = m_HDProbeBakedStates[i].probeBakedHash;
                }
                stateHashes = m_StateHashes;
            }

            handle.ExitStage((int)BakingStages.ReflectionProbes);

            handle.SetIsDone(true);
        }
Example #11
0
        public static bool BakeProbes(IEnumerable <HDProbe> bakedProbes)
        {
            if (!(RenderPipelineManager.currentPipeline is HDRenderPipeline hdPipeline))
            {
                Debug.LogWarning("HDBakedReflectionSystem only works with HDRP, " +
                                 "please switch your render pipeline or use another reflection probe system.");
                return(false);
            }

            hdPipeline.reflectionProbeBaking = true;

            var cubemapSize = (int)hdPipeline.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionCubemapSize;
            // We force RGBAHalf as we don't support 11-11-10 textures (only RT)
            var probeFormat = GraphicsFormat.R16G16B16A16_SFloat;

            var cubeRT = HDRenderUtilities.CreateReflectionProbeRenderTarget(cubemapSize, probeFormat);

            // Render and write the result to disk
            foreach (var probe in bakedProbes)
            {
                if (string.IsNullOrEmpty(probe.gameObject.scene.path))
                {
                    continue;
                }

                var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);
                var planarRT         = HDRenderUtilities.CreatePlanarProbeRenderTarget((int)probe.resolution, probeFormat);
                RenderAndWriteToFile(probe, bakedTexturePath, cubeRT, planarRT);
                planarRT.Release();
            }

            // AssetPipeline bug
            // Sometimes, the baked texture reference is destroyed during 'AssetDatabase.StopAssetEditing()'
            //   thus, the reference to the baked texture in the probe is lost
            // Although, importing twice the texture seems to workaround the issue
            for (int j = 0; j < 2; ++j)
            {
                AssetDatabase.StartAssetEditing();
                foreach (var probe in bakedProbes)
                {
                    if (string.IsNullOrEmpty(probe.gameObject.scene.path))
                    {
                        continue;
                    }

                    var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);
                    AssetDatabase.ImportAsset(bakedTexturePath);
                    ImportAssetAt(probe, bakedTexturePath);
                }
                AssetDatabase.StopAssetEditing();
            }

            AssetDatabase.StartAssetEditing();
            foreach (var probe in bakedProbes)
            {
                if (string.IsNullOrEmpty(probe.gameObject.scene.path))
                {
                    continue;
                }

                var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);

                // Get or create the baked texture asset for the probe
                var bakedTexture = AssetDatabase.LoadAssetAtPath <Texture>(bakedTexturePath);
                Assert.IsNotNull(bakedTexture, "The baked texture was imported before, " +
                                 "so it must exists in AssetDatabase");

                // Update import settings
                ImportAssetAt(probe, bakedTexturePath);
                probe.SetTexture(ProbeSettings.Mode.Baked, bakedTexture);
                AssignRenderData(probe, bakedTexturePath);
                EditorUtility.SetDirty(probe);
            }
            AssetDatabase.StopAssetEditing();

            // case 1158677
            // The AssetPipeline will destroy and recreate the textures
            // So all transient data will be lost after the call to `AssetDatabase.StopAssetEditing`
            // Here, we increment the updateCount to with an arbitrary number to force the reflection probe cache
            // to update the texture.
            // updateCount is a transient data, so don't execute this code before the asset reload.
            {
                UnityEngine.Random.InitState((int)(1000 * EditorApplication.timeSinceStartup));
                foreach (var probe in bakedProbes)
                {
                    var c = UnityEngine.Random.Range(2, 10);
                    while (probe.texture.updateCount < c)
                    {
                        probe.texture.IncrementUpdateCount();
                    }
                }
            }

            cubeRT.Release();

            hdPipeline.reflectionProbeBaking = false;

            return(true);
        }
        public override void Tick(
            SceneStateHash sceneStateHash,
            IScriptableBakedReflectionSystemStageNotifier handle
            )
        {
            if (!AreAllOpenedSceneSaved())
            {
                handle.SetIsDone(true);
                return;
            }

            // On the C# side, we don't have non blocking asset import APIs, and we don't want to block the
            //   UI when the user is editing the world.
            //   So, we skip the baking when the user is editing any UI control.
            if (GUIUtility.hotControl != 0)
            {
                return;
            }

            if (!IsCurrentSRPValid(out HDRenderPipeline hdPipeline))
            {
                if (ShouldIssueWarningForCurrentSRP())
                {
                    Debug.LogWarning("HDBakedReflectionSystem work with HDRP, " +
                                     "please switch your render pipeline or use another reflection system");
                }

                handle.ExitStage((int)BakingStages.ReflectionProbes);
                handle.SetIsDone(true);
                return;
            }

            var ambientProbeHash = sceneStateHash.ambientProbeHash;
            var sceneObjectsHash = sceneStateHash.sceneObjectsHash;
            var skySettingsHash  = sceneStateHash.skySettingsHash;

            DeleteCubemapAssets(true);

            // Explanation of the algorithm:
            // 1. First we create the hash of the world that can impact the reflection probes.
            // 2. Then for each probe, we calculate a hash that represent what this specific probe should have baked.
            // 3. We compare those hashes against the baked one and decide:
            //   a. If we have to remove a baked data
            //   b. If we have to bake a probe
            // 4. Bake all required probes
            // 5. Remove unused baked data
            // 6. Update probe assets

            // == 1. ==
            var allProbeDependencyHash = new Hash128();

            // TODO: All baked probes depend on custom probes (hash all custom probes and set as dependency)
            // TODO: All baked probes depend on HDRP specific Light settings
            HashUtilities.AppendHash(ref ambientProbeHash, ref allProbeDependencyHash);
            HashUtilities.AppendHash(ref sceneObjectsHash, ref allProbeDependencyHash);
            HashUtilities.AppendHash(ref skySettingsHash, ref allProbeDependencyHash);

            var bakedProbes = HDProbeSystem.bakedProbes;

            // == 2. ==
            var states = stackalloc HDProbeBakingState[bakedProbes.Count];

            ComputeProbeInstanceID(bakedProbes, states);
            ComputeProbeSettingsHashes(bakedProbes, states);
            // TODO: Handle bounce dependency here
            ComputeProbeBakingHashes(bakedProbes.Count, allProbeDependencyHash, states);

            CoreUnsafeUtils.QuickSort <HDProbeBakingState, Hash128, HDProbeBakingState.ProbeBakingHash>(
                bakedProbes.Count, states
                );

            int operationCount = 0, addCount = 0, remCount = 0;
            var maxProbeCount = Mathf.Max(bakedProbes.Count, m_HDProbeBakedStates.Length);
            var addIndices    = stackalloc int[maxProbeCount];
            var remIndices    = stackalloc int[maxProbeCount];

            if (m_HDProbeBakedStates.Length == 0)
            {
                for (int i = 0; i < bakedProbes.Count; ++i)
                {
                    addIndices[addCount++] = i;
                }
                operationCount = addCount;
            }
            else
            {
                fixed(HDProbeBakedState *oldBakedStates = &m_HDProbeBakedStates[0])
                {
                    // == 3. ==
                    // Compare hashes between baked probe states and desired probe states
                    operationCount = CoreUnsafeUtils.CompareHashes <
                        HDProbeBakedState, HDProbeBakedState.ProbeBakedHash,
                        HDProbeBakingState, HDProbeBakingState.ProbeBakingHash
                        > (
                        m_HDProbeBakedStates.Length, oldBakedStates, // old hashes
                        bakedProbes.Count, states,                   // new hashes
                        addIndices, remIndices,
                        out addCount, out remCount
                        );
                }
            }

            if (operationCount > 0)
            {
                // == 4. ==
                var cubemapSize = (int)hdPipeline.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionCubemapSize;
                var planarSize  = (int)hdPipeline.currentPlatformRenderPipelineSettings.lightLoopSettings.planarReflectionTextureSize;
                var cubeRT      = HDRenderUtilities.CreateReflectionProbeRenderTarget(cubemapSize);
                var planarRT    = HDRenderUtilities.CreatePlanarProbeRenderTarget(planarSize);

                handle.EnterStage(
                    (int)BakingStages.ReflectionProbes,
                    string.Format("Reflection Probes | {0} jobs", addCount),
                    0
                    );

                // Render probes
                for (int i = 0; i < addCount; ++i)
                {
                    handle.EnterStage(
                        (int)BakingStages.ReflectionProbes,
                        string.Format("Reflection Probes | {0} jobs", addCount),
                        i / (float)addCount
                        );

                    var index      = addIndices[i];
                    var instanceId = states[index].instanceID;
                    var probe      = (HDProbe)EditorUtility.InstanceIDToObject(instanceId);
                    var cacheFile  = GetGICacheFileForHDProbe(states[index].probeBakingHash);

                    // Get from cache or render the probe
                    if (!File.Exists(cacheFile))
                    {
                        RenderAndWriteToFile(probe, cacheFile, cubeRT, planarRT);
                    }
                }
                cubeRT.Release();
                planarRT.Release();

                // Copy texture from cache
                for (int i = 0; i < addCount; ++i)
                {
                    var index      = addIndices[i];
                    var instanceId = states[index].instanceID;
                    var probe      = (HDProbe)EditorUtility.InstanceIDToObject(instanceId);
                    var cacheFile  = GetGICacheFileForHDProbe(states[index].probeBakingHash);

                    Assert.IsTrue(File.Exists(cacheFile));

                    var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);
                    HDBakingUtilities.CreateParentDirectoryIfMissing(bakedTexturePath);
                    Checkout(bakedTexturePath);
                    // Checkout will make those file writeable, but this is not immediate,
                    // so we retries when this fails.
                    if (!HDEditorUtils.CopyFileWithRetryOnUnauthorizedAccess(cacheFile, bakedTexturePath))
                    {
                        return;
                    }
                }
                // AssetPipeline bug
                // Sometimes, the baked texture reference is destroyed during 'AssetDatabase.StopAssetEditing()'
                //   thus, the reference to the baked texture in the probe is lost
                // Although, importing twice the texture seems to workaround the issue
                for (int j = 0; j < 2; ++j)
                {
                    AssetDatabase.StartAssetEditing();
                    for (int i = 0; i < bakedProbes.Count; ++i)
                    {
                        var index            = addIndices[i];
                        var instanceId       = states[index].instanceID;
                        var probe            = (HDProbe)EditorUtility.InstanceIDToObject(instanceId);
                        var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);
                        AssetDatabase.ImportAsset(bakedTexturePath);
                        ImportAssetAt(probe, bakedTexturePath);
                    }
                    AssetDatabase.StopAssetEditing();
                }
                // Import assets
                AssetDatabase.StartAssetEditing();
                for (int i = 0; i < addCount; ++i)
                {
                    var index            = addIndices[i];
                    var instanceId       = states[index].instanceID;
                    var probe            = (HDProbe)EditorUtility.InstanceIDToObject(instanceId);
                    var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);
                    var bakedTexture     = AssetDatabase.LoadAssetAtPath <Texture>(bakedTexturePath);
                    Assert.IsNotNull(bakedTexture, "The baked texture was imported before, " +
                                     "so it must exists in AssetDatabase");

                    probe.SetTexture(ProbeSettings.Mode.Baked, bakedTexture);
                    EditorUtility.SetDirty(probe);
                }
                AssetDatabase.StopAssetEditing();

                // == 5. ==

                // Create new baked state array
                var targetSize        = m_HDProbeBakedStates.Length + addCount - remCount;
                var targetBakedStates = stackalloc HDProbeBakedState[targetSize];
                // Copy baked state that are not removed
                var targetI = 0;
                for (int i = 0; i < m_HDProbeBakedStates.Length; ++i)
                {
                    if (CoreUnsafeUtils.IndexOf(remIndices, remCount, i) != -1)
                    {
                        continue;
                    }
                    targetBakedStates[targetI++] = m_HDProbeBakedStates[i];
                }
                // Add new baked states
                for (int i = 0; i < addCount; ++i)
                {
                    var state = states[addIndices[i]];
                    targetBakedStates[targetI++] = new HDProbeBakedState
                    {
                        instanceID     = state.instanceID,
                        probeBakedHash = state.probeBakingHash
                    };
                }
                CoreUnsafeUtils.QuickSort <HDProbeBakedState, Hash128, HDProbeBakedState.ProbeBakedHash>(
                    targetI, targetBakedStates
                    );

                Array.Resize(ref m_HDProbeBakedStates, targetSize);
                if (targetSize > 0)
                {
                    fixed(HDProbeBakedState *bakedStates = &m_HDProbeBakedStates[0])
                    {
                        UnsafeUtility.MemCpy(
                            bakedStates,
                            targetBakedStates,
                            sizeof(HDProbeBakedState) * targetSize
                            );
                    }
                }

                // Update state hash
                Array.Resize(ref m_StateHashes, m_HDProbeBakedStates.Length);
                for (int i = 0; i < m_HDProbeBakedStates.Length; ++i)
                {
                    m_StateHashes[i] = m_HDProbeBakedStates[i].probeBakedHash;
                }
                stateHashes = m_StateHashes;
            }

            handle.ExitStage((int)BakingStages.ReflectionProbes);

            handle.SetIsDone(true);
        }
        public static bool BakeProbes(IList <HDProbe> bakedProbes)
        {
            if (!(RenderPipelineManager.currentPipeline is HDRenderPipeline hdPipeline))
            {
                Debug.LogWarning("HDBakedReflectionSystem work with HDRP, " +
                                 "please switch your render pipeline or use another reflection system");
                return(false);
            }

            var cubemapSize = (int)hdPipeline.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionCubemapSize;
            var planarSize  = (int)hdPipeline.currentPlatformRenderPipelineSettings.lightLoopSettings.planarReflectionTextureSize;

            var cubeRT   = HDRenderUtilities.CreateReflectionProbeRenderTarget(cubemapSize);
            var planarRT = HDRenderUtilities.CreatePlanarProbeRenderTarget(planarSize);

            // Render and write the result to disk
            for (int i = 0; i < bakedProbes.Count; ++i)
            {
                var probe            = bakedProbes[i];
                var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);
                RenderAndWriteToFile(probe, bakedTexturePath, cubeRT, planarRT);
            }

            // AssetPipeline bug
            // Sometimes, the baked texture reference is destroyed during 'AssetDatabase.StopAssetEditing()'
            //   thus, the reference to the baked texture in the probe is lost
            // Although, importing twice the texture seems to workaround the issue
            for (int j = 0; j < 2; ++j)
            {
                AssetDatabase.StartAssetEditing();
                for (int i = 0; i < bakedProbes.Count; ++i)
                {
                    var probe            = bakedProbes[i];
                    var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);
                    AssetDatabase.ImportAsset(bakedTexturePath);
                    ImportAssetAt(probe, bakedTexturePath);
                }
                AssetDatabase.StopAssetEditing();
            }

            AssetDatabase.StartAssetEditing();
            for (int i = 0; i < bakedProbes.Count; ++i)
            {
                var probe            = bakedProbes[i];
                var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);

                // Get or create the baked texture asset for the probe
                var bakedTexture = AssetDatabase.LoadAssetAtPath <Texture>(bakedTexturePath);
                Assert.IsNotNull(bakedTexture, "The baked texture was imported before, " +
                                 "so it must exists in AssetDatabase");

                // Update import settings
                ImportAssetAt(probe, bakedTexturePath);
                probe.SetTexture(ProbeSettings.Mode.Baked, bakedTexture);
                AssignRenderData(probe, bakedTexturePath);
                EditorUtility.SetDirty(probe);
            }
            AssetDatabase.StopAssetEditing();

            // case 1158677
            // The AssetPipeline will destroy and recreate the textures
            // So all transient data will be lost after the call to `AssetDatabase.StopAssetEditing`
            // Here, we increment the updateCount to with an arbitrary number to force the reflection probe cache
            // to update the texture.
            // updateCount is a transient data, so don't execute this code before the asset reload.
            {
                UnityEngine.Random.InitState((int)Time.realtimeSinceStartup);
                for (int i = 0; i < bakedProbes.Count; ++i)
                {
                    var probe = bakedProbes[i];
                    var c     = UnityEngine.Random.Range(2, 10);
                    while (probe.texture.updateCount < c)
                    {
                        probe.texture.IncrementUpdateCount();
                    }
                }
            }

            cubeRT.Release();
            planarRT.Release();

            return(true);
        }
Example #14
0
 public override void Build()
 {
     m_spaceSkyMaterial             = CoreUtils.CreateEngineMaterial("Hidden/SpaceSky");
     m_spaceSkyCubemapRenderTexture = HDRenderUtilities.CreateReflectionProbeRenderTarget(4096);
 }
Example #15
0
        public static bool BakeProbes(IList <HDProbe> bakedProbes)
        {
            if (!(RenderPipelineManager.currentPipeline is HDRenderPipeline hdPipeline))
            {
                Debug.LogWarning("HDBakedReflectionSystem work with HDRP, " +
                                 "please switch your render pipeline or use another reflection system");
                return(false);
            }

            var cubemapSize = (int)hdPipeline.currentPlatformRenderPipelineSettings.lightLoopSettings.reflectionCubemapSize;
            var planarSize  = (int)hdPipeline.currentPlatformRenderPipelineSettings.lightLoopSettings.planarReflectionTextureSize;

            var cubeRT   = HDRenderUtilities.CreateReflectionProbeRenderTarget(cubemapSize);
            var planarRT = HDRenderUtilities.CreatePlanarProbeRenderTarget(planarSize);

            // Render and write the result to disk
            for (int i = 0; i < bakedProbes.Count; ++i)
            {
                var probe            = bakedProbes[i];
                var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);
                RenderAndWriteToFile(probe, bakedTexturePath, cubeRT, planarRT);
            }

            // AssetPipeline bug
            // Sometimes, the baked texture reference is destroyed during 'AssetDatabase.StopAssetEditing()'
            //   thus, the reference to the baked texture in the probe is lost
            // Although, importing twice the texture seems to workaround the issue
            for (int j = 0; j < 2; ++j)
            {
                AssetDatabase.StartAssetEditing();
                for (int i = 0; i < bakedProbes.Count; ++i)
                {
                    var probe            = bakedProbes[i];
                    var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);
                    AssetDatabase.ImportAsset(bakedTexturePath);
                    ImportAssetAt(probe, bakedTexturePath);
                }
                AssetDatabase.StopAssetEditing();
            }

            AssetDatabase.StartAssetEditing();
            for (int i = 0; i < bakedProbes.Count; ++i)
            {
                var probe            = bakedProbes[i];
                var bakedTexturePath = HDBakingUtilities.GetBakedTextureFilePath(probe);

                // Get or create the baked texture asset for the probe
                var bakedTexture = AssetDatabase.LoadAssetAtPath <Texture>(bakedTexturePath);
                Assert.IsNotNull(bakedTexture, "The baked texture was imported before, " +
                                 "so it must exists in AssetDatabase");

                // Update import settings
                ImportAssetAt(probe, bakedTexturePath);
                probe.SetTexture(ProbeSettings.Mode.Baked, bakedTexture);
                AssignRenderData(probe, bakedTexturePath);
                EditorUtility.SetDirty(probe);
            }
            AssetDatabase.StopAssetEditing();

            cubeRT.Release();
            planarRT.Release();

            return(true);
        }