コード例 #1
0
 protected override void Execute(ScriptableRenderContext context, CommandBuffer cmd, HDCamera camera, CullingResults cullingResult)
 {
     UnityEngine.Profiling.Profiler.BeginSample("ALINE");
     DrawingManager.instance.SubmitFrame(camera.camera, cmd, true);
     UnityEngine.Profiling.Profiler.EndSample();
 }
コード例 #2
0
    protected override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera camera, CullingResults cullingResult)
    {
        // if (!render || camera.camera == bakingCamera)
        //     return;

        bakingCamera.TryGetCullingParameters(out var cullingParams);
        cullingParams.cullingOptions = CullingOptions.ShadowCasters;
        cullingResult = renderContext.Cull(ref cullingParams);

        var result = new RendererListDesc(shaderTags, cullingResult, bakingCamera)
        {
            rendererConfiguration      = PerObjectData.None,
            renderQueueRange           = RenderQueueRange.all,
            sortingCriteria            = SortingCriteria.BackToFront,
            excludeObjectMotionVectors = false,
            layerMask = -1,
        };

        var       p           = GL.GetGPUProjectionMatrix(bakingCamera.projectionMatrix, true);
        Matrix4x4 scaleMatrix = Matrix4x4.identity;

        scaleMatrix.m22 = -1.0f;
        var v  = scaleMatrix * bakingCamera.transform.localToWorldMatrix.inverse;
        var vp = p * v;

        cmd.SetGlobalMatrix("_ViewMatrix", v);
        cmd.SetGlobalMatrix("_InvViewMatrix", v.inverse);
        cmd.SetGlobalMatrix("_ProjMatrix", p);
        cmd.SetGlobalMatrix("_InvProjMatrix", p.inverse);
        cmd.SetGlobalMatrix("_ViewProjMatrix", vp);
        cmd.SetGlobalMatrix("_InvViewProjMatrix", vp.inverse);
        cmd.SetGlobalMatrix("_CameraViewProjMatrix", vp);
        cmd.SetGlobalVector("_WorldSpaceCameraPos", Vector3.zero);

        CoreUtils.SetRenderTarget(cmd, targetTexture, ClearFlag.Depth);
        HDUtils.DrawRendererList(renderContext, cmd, RendererList.Create(result));
    }
コード例 #3
0
ファイル: CloudPass.cs プロジェクト: D4KU/Clouds
    protected override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResult)
    {
        // Validate inputs
        if (material == null || material.shader != shader)
        {
            material = new Material(shader);
        }
        numStepsLight = Mathf.Max(1, numStepsLight);

        // Noise
        var noise = Object.FindObjectOfType <NoiseGenerator> ();

        noise.UpdateNoise();

        material.SetTexture("NoiseTex", noise.shapeTexture);
        material.SetTexture("DetailNoiseTex", noise.detailTexture);
        material.SetTexture("BlueNoise", blueNoise);

        // Weathermap
        //var weatherMapGen = Object.FindObjectOfType<WeatherMap>();
        //if (!Application.isPlaying)
        //{
        //    weatherMapGen.UpdateMap();
        //}
        //material.SetTexture("WeatherMap", weatherMapGen.weatherMap);

        Vector3 size   = container.localScale;
        int     width  = Mathf.CeilToInt(size.x);
        int     height = Mathf.CeilToInt(size.y);
        int     depth  = Mathf.CeilToInt(size.z);

        material.SetFloat("scale", cloudScale);
        material.SetFloat("densityMultiplier", densityMultiplier);
        material.SetFloat("densityOffset", densityOffset);
        material.SetFloat("lightAbsorptionThroughCloud", lightAbsorptionThroughCloud);
        material.SetFloat("lightAbsorptionTowardSun", lightAbsorptionTowardSun);
        material.SetFloat("darknessThreshold", darknessThreshold);
        material.SetVector("params", cloudTestParams);
        material.SetFloat("rayOffsetStrength", rayOffsetStrength);

        material.SetFloat("detailNoiseScale", detailNoiseScale);
        material.SetFloat("detailNoiseWeight", detailNoiseWeight);
        material.SetVector("shapeOffset", shapeOffset);
        material.SetVector("detailOffset", detailOffset);
        material.SetVector("detailWeights", detailNoiseWeights);
        material.SetVector("shapeNoiseWeights", shapeNoiseWeights);
        material.SetVector("phaseParams", new Vector4(forwardScattering, backScattering, baseBrightness, phaseFactor));

        material.SetVector("boundsMin", container.position - container.localScale / 2);
        material.SetVector("boundsMax", container.position + container.localScale / 2);
        material.SetInt("numStepsLight", numStepsLight);
        material.SetVector("mapSize", new Vector4(width, height, depth, 0));

        material.SetFloat("timeScale", (Application.isPlaying) ? timeScale : 0);
        material.SetFloat("baseSpeed", baseSpeed);
        material.SetFloat("detailSpeed", detailSpeed);

        // Set debug params
        SetDebugParams();
        material.SetColor("colA", colA);
        material.SetColor("colB", colB);

        // Bind the camera color buffer along with depth without clearing the buffers.
        // Or set the a custom render target with CoreUtils.SetRenderTarget()
        SetCameraRenderTarget(cmd);
        CoreUtils.DrawFullScreen(cmd, material, shaderPassId: 0);
    }
コード例 #4
0
//---------------------------------------------------------------------------------------------------------------------
    public void BlitRenderStreamingRT(UnityEngine.Rendering.ScriptableRenderContext context, HDCamera cam)
    {
        Graphics.Blit(m_rtCamera.targetTexture, (RenderTexture)null);
    }
コード例 #5
0
 protected override void AggregateCullingParameters(ref ScriptableCullingParameters cullingParameters, HDCamera hdCamera)
 => cullingParameters.cullingMask |= (uint)maskLayer.value;
コード例 #6
0
        // Denoiser variant when history is stored in an array and the validation buffer is seperate
        public void DenoiseBuffer(CommandBuffer cmd, HDCamera hdCamera,
                                  RTHandle noisySignal, RTHandle historySignal, RTHandle validationHistory, RTHandle velocityBuffer,
                                  RTHandle outputSignal,
                                  int sliceIndex, Vector4 channelMask, bool singleChannel = true, float historyValidity = 1.0f)
        {
            // If we do not have a depth and normal history buffers, we can skip right away
            var historyDepthBuffer  = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.Depth);
            var historyNormalBuffer = hdCamera.GetCurrentFrameRT((int)HDCameraFrameHistoryType.Normal);

            if (historyDepthBuffer == null || historyNormalBuffer == null)
            {
                HDUtils.BlitCameraTexture(cmd, noisySignal, historySignal);
                HDUtils.BlitCameraTexture(cmd, noisySignal, outputSignal);
                return;
            }

            // Fetch texture dimensions
            int texWidth  = hdCamera.actualWidth;
            int texHeight = hdCamera.actualHeight;

            // Evaluate the dispatch parameters
            int areaTileSize = 8;
            int numTilesX    = (texWidth + (areaTileSize - 1)) / areaTileSize;
            int numTilesY    = (texHeight + (areaTileSize - 1)) / areaTileSize;

            // Request the intermediate buffer we need
            RTHandle validationBuffer = m_RenderPipeline.GetRayTracingBuffer(InternalRayTracingBuffers.R0);

            // First of all we need to validate the history to know where we can or cannot use the history signal
            int m_KernelFilter = m_TemporalFilterCS.FindKernel("ValidateHistory");
            var historyScale   = new Vector2(hdCamera.actualWidth / (float)historySignal.rt.width, hdCamera.actualHeight / (float)historySignal.rt.height);

            cmd.SetComputeVectorParam(m_TemporalFilterCS, HDShaderIDs._RTHandleScaleHistory, historyScale);
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._HistoryDepthTexture, historyDepthBuffer);
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._NormalBufferTexture, m_SharedRTManager.GetNormalBuffer());
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._HistoryNormalBufferTexture, historyNormalBuffer);
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._ValidationBufferRW, validationBuffer);
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._VelocityBuffer, velocityBuffer);
            cmd.SetComputeFloatParam(m_TemporalFilterCS, HDShaderIDs._HistoryValidity, historyValidity);
            cmd.SetComputeFloatParam(m_TemporalFilterCS, HDShaderIDs._PixelSpreadAngleTangent, HDRenderPipeline.GetPixelSpreadTangent(hdCamera.camera.fieldOfView, hdCamera.actualWidth, hdCamera.actualHeight));
            cmd.DispatchCompute(m_TemporalFilterCS, m_KernelFilter, numTilesX, numTilesY, hdCamera.viewCount);

            // Now that we have validated our history, let's accumulate
            m_KernelFilter = m_TemporalFilterCS.FindKernel(singleChannel ? "TemporalAccumulationSingleArray" : "TemporalAccumulationColorArray");
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._DenoiseInputTexture, noisySignal);
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._HistoryBuffer, historySignal);
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._HistoryValidityBuffer, validationHistory);
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._DepthTexture, m_SharedRTManager.GetDepthStencilBuffer());
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._DenoiseOutputTextureRW, outputSignal);
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._ValidationBuffer, validationBuffer);
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._VelocityBuffer, velocityBuffer);
            cmd.SetComputeIntParam(m_TemporalFilterCS, HDShaderIDs._DenoisingHistorySlice, sliceIndex);
            cmd.SetComputeVectorParam(m_TemporalFilterCS, HDShaderIDs._DenoisingHistoryMask, channelMask);
            cmd.DispatchCompute(m_TemporalFilterCS, m_KernelFilter, numTilesX, numTilesY, hdCamera.viewCount);

            // Make sure to copy the new-accumulated signal in our history buffer
            m_KernelFilter = m_TemporalFilterCS.FindKernel(singleChannel ? "CopyHistorySingleArray" : "CopyHistoryColorArray");
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._DenoiseInputTexture, outputSignal);
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._DenoiseOutputTextureRW, historySignal);
            cmd.SetComputeTextureParam(m_TemporalFilterCS, m_KernelFilter, HDShaderIDs._ValidityOutputTextureRW, validationHistory);
            cmd.SetComputeIntParam(m_TemporalFilterCS, HDShaderIDs._DenoisingHistorySlice, sliceIndex);
            cmd.SetComputeVectorParam(m_TemporalFilterCS, HDShaderIDs._DenoisingHistoryMask, channelMask);
            cmd.DispatchCompute(m_TemporalFilterCS, m_KernelFilter, numTilesX, numTilesY, hdCamera.viewCount);
        }
コード例 #7
0
        private void RenderSolidCore(
            CommandBuffer cmd,
            HDCamera targetCamera,
            RTHandle cameraColorBuffer,
            bool calculateNormals,
            bool smoothNormals,
            ViewportSettings viewportSettings,
            CubemapFace cubemapFace = CubemapFace.Unknown)
        {
            var rt       = Resources.GetRTHandle(RTUsage.PointRender);
            var rt1      = Resources.GetRTHandle(RTUsage.Generic0);
            var rt2      = Resources.GetRTHandle(RTUsage.Generic1);
            var rtColor  = Resources.GetRTHandle(RTUsage.ColorBuffer);
            var rtDepth  = Resources.GetRTHandle(RTUsage.DepthBuffer);
            var rtDepth2 = Resources.GetRTHandle(RTUsage.DepthBuffer2);

            // TODO: handle resolutions above reference size
            // Custom cubemap target can have resolution higher than RT reference size, in which case it will be cut
            var width   = viewportSettings.width;
            var height  = viewportSettings.height;
            var refSize = rt.referenceSize;

            var msaaSamples = ((HDRenderPipeline)RenderPipelineManager.currentPipeline).MSAASamples;

            // TODO: verify if this is still needed after updating HDRP above 10.3.2
            // In previous versions (7.3) viewport size was updated automatically - now it has to be manually managed
            // This can have critical performance impact if new MSAA samples settings don't not match current settings
            RTHandles.SetReferenceSize(width, height, msaaSamples);

            var resolution = new Vector2Int(width, height);

            var fov = viewportSettings.fieldOfView;

            if (SolidFovReprojection)
            {
                fov *= ReprojectionRatio;
            }

            var size = Math.Max(width, height);

            var maxLevel = 0;

            while (size >> maxLevel >= 16)
            {
                maxLevel++;
            }

            CalculateMatrices(targetCamera, viewportSettings, out var projMatrix, out var invProjMatrix, out var invViewMatrix, out var invViewProjMatrix, out var solidRenderMvp);

            var cs = Resources.SolidComputeShader;

            cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.TextureSize, new Vector4(width - 1, height - 1, 1f / width, 1f / height));
            cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.FullRTSize, new Vector4(refSize.x - 1, refSize.y - 1, 1f / refSize.x, 1f / refSize.y));
            cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.FarPlane, targetCamera.camera.farClipPlane);
            cmd.SetComputeMatrixParam(cs, PointCloudShaderIDs.SolidCompute.ProjectionMatrix, projMatrix);
            cmd.SetComputeMatrixParam(cs, PointCloudShaderIDs.SolidCompute.InverseProjectionMatrix, invProjMatrix);
            cmd.SetComputeMatrixParam(cs, PointCloudShaderIDs.SolidCompute.InverseViewMatrix, invViewMatrix);
            cmd.SetComputeMatrixParam(cs, PointCloudShaderIDs.SolidCompute.InverseVPMatrix, invViewProjMatrix);
            cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.InverseReprojectionVector, GetInverseUvFovReprojectionVector(viewportSettings));

            cmd.SetGlobalBuffer(PointCloudShaderIDs.Shared.Buffer, GetBufferForCamera(targetCamera));
            cmd.SetGlobalInt(PointCloudShaderIDs.Shared.Colorize, (int)Colorize);
            cmd.SetGlobalFloat(PointCloudShaderIDs.Shared.MinHeight, Bounds.min.y);
            cmd.SetGlobalFloat(PointCloudShaderIDs.Shared.MaxHeight, Bounds.max.y);
            cmd.SetGlobalMatrix(PointCloudShaderIDs.SolidRender.MVPMatrix, solidRenderMvp);

            if (ForcedFill == ForcedFillMode.HorizonAndDepth || SolidRemoveHidden && HiddenPointRemoval == HprMode.DepthPrepass)
            {
                SetCirclesMaterialProperties(cmd, targetCamera);
                CoreUtils.SetRenderTarget(cmd, rt2, rtDepth2);
                CoreUtils.ClearRenderTarget(cmd, ClearFlag.All, Color.clear);
                var pass = Resources.Passes.circlesDepthPrepass;
                cmd.DrawProcedural(Matrix4x4.identity, Resources.CirclesMaterial, pass, MeshTopology.Points, GetPointCountForCamera(targetCamera));
            }

            if (ForcedFill == ForcedFillMode.HorizonAndDepth)
            {
                var setupCopyFill = Resources.Kernels.Setup;
                cmd.SetComputeTextureParam(cs, setupCopyFill, PointCloudShaderIDs.SolidCompute.SetupCopy.InputPosition, rtDepth2, 0);
                cmd.SetComputeTextureParam(cs, setupCopyFill, PointCloudShaderIDs.SolidCompute.SetupCopy.OutputPosition, rt1, 0);
                cmd.DispatchCompute(cs, setupCopyFill, GetGroupSize(width, 8), GetGroupSize(height, 8), 1);

                // Prepare rough depth with hole fixing
                var downsample = Resources.Kernels.Downsample;
                // TODO: only go down to MIP3
                for (var i = 1; i <= maxLevel + 3; i++)
                {
                    GetMipData(resolution, i - 1, out var mipRes, out var mipVec);
                    cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.MipTextureSize, mipVec);
                    cmd.SetComputeTextureParam(cs, downsample, PointCloudShaderIDs.SolidCompute.Downsample.InputPosition, rt1, i - 1);
                    cmd.SetComputeTextureParam(cs, downsample, PointCloudShaderIDs.SolidCompute.Downsample.OutputPosition, rt1, i);
                    cmd.DispatchCompute(cs, downsample, GetGroupSize(mipRes.x, 16), GetGroupSize(mipRes.y, 16), 1);
                }

                var fillHolesKernel = Resources.Kernels.FillRoughDepth;
                GetMipData(resolution, 4, out var gmipRes, out var higherMipVec);
                GetMipData(resolution, 4 - 1, out _, out var gmipVec);
                cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.MipTextureSize, gmipVec);
                cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.HigherMipTextureSize, higherMipVec);
                cmd.SetComputeTextureParam(cs, fillHolesKernel, PointCloudShaderIDs.SolidCompute.FillRoughHoles.TexIn, rt1);
                cmd.SetComputeTextureParam(cs, fillHolesKernel, PointCloudShaderIDs.SolidCompute.FillRoughHoles.TexOut, rt2, 4);
                cmd.DispatchCompute(cs, fillHolesKernel, GetGroupSize(gmipRes.x, 8), GetGroupSize(gmipRes.y, 8), 1);
            }

            CoreUtils.SetRenderTarget(cmd, rt, rtDepth);
            CoreUtils.ClearRenderTarget(cmd, ClearFlag.All, Color.clear);

            cmd.DrawProcedural(Matrix4x4.identity, Resources.SolidRenderMaterial, 0, MeshTopology.Points, GetPointCountForCamera(targetCamera));

            var setupCopy = Resources.Kernels.Setup;

            cmd.SetComputeTextureParam(cs, setupCopy, PointCloudShaderIDs.SolidCompute.SetupCopy.InputPosition, rtDepth, 0);
            cmd.SetComputeTextureParam(cs, setupCopy, PointCloudShaderIDs.SolidCompute.SetupCopy.OutputPosition, rt1, 0);
            cmd.DispatchCompute(cs, setupCopy, GetGroupSize(width, 8), GetGroupSize(height, 8), 1);

            var blendSky = DebugBlendSky && cameraColorBuffer != null;
            var skyBlend = Resources.Kernels.GetSkyBlendKernel(ForcedFill, blendSky);

            cmd.SetComputeTextureParam(cs, skyBlend, PointCloudShaderIDs.SolidCompute.SkyBlend.ViewPos, rt1, 0);
            cmd.SetComputeTextureParam(cs, skyBlend, PointCloudShaderIDs.SolidCompute.SkyBlend.ColorIn, rt, 0);
            cmd.SetComputeTextureParam(cs, skyBlend, PointCloudShaderIDs.SolidCompute.SkyBlend.ColorOut, rtColor, 0);
            if (blendSky)
            {
                cmd.SetComputeTextureParam(cs, skyBlend, PointCloudShaderIDs.SolidCompute.SkyBlend.PostSkyPreRenderTexture, cameraColorBuffer, 0);
            }
            if (ForcedFill == ForcedFillMode.HorizonAndDepth)
            {
                cmd.SetComputeTextureParam(cs, skyBlend, PointCloudShaderIDs.SolidCompute.SkyBlend.RoughDepth, rt2, 0);
            }
            cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.SkyBlend.HorizonThreshold, DebugFillThreshold);
            cmd.DispatchCompute(cs, skyBlend, GetGroupSize(width, 8), GetGroupSize(height, 8), 1);

            if (SolidRemoveHidden)
            {
                switch (HiddenPointRemoval)
                {
                case HprMode.ScreenSpace:
                {
                    var downsample = Resources.Kernels.Downsample;
                    for (var i = 1; i <= maxLevel + 3; i++)
                    {
                        GetMipData(resolution, i - 1, out var mipRes, out var mipVec);
                        cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.MipTextureSize, mipVec);
                        cmd.SetComputeTextureParam(cs, downsample, PointCloudShaderIDs.SolidCompute.Downsample.InputPosition, rt1, i - 1);
                        cmd.SetComputeTextureParam(cs, downsample, PointCloudShaderIDs.SolidCompute.Downsample.OutputPosition, rt1, i);
                        cmd.DispatchCompute(cs, downsample, GetGroupSize(mipRes.x, 16), GetGroupSize(mipRes.y, 16), 1);
                    }

                    DebugSolidFixedLevel = Math.Min(Math.Max(DebugSolidFixedLevel, 0), maxLevel);

                    var removeHidden      = Resources.Kernels.GetRemoveHiddenKernel(DebugShowRemoveHiddenCascades);
                    var removeHiddenMagic = RemoveHiddenCascadeOffset * height * 0.5f / Mathf.Tan(0.5f * fov * Mathf.Deg2Rad);

                    cmd.SetComputeIntParam(cs, PointCloudShaderIDs.SolidCompute.RemoveHidden.LevelCount, maxLevel);
                    cmd.SetComputeTextureParam(cs, removeHidden, PointCloudShaderIDs.SolidCompute.RemoveHidden.Position, rt1);
                    cmd.SetComputeTextureParam(cs, removeHidden, PointCloudShaderIDs.SolidCompute.RemoveHidden.PositionRough, rt1);
                    cmd.SetComputeTextureParam(cs, removeHidden, PointCloudShaderIDs.SolidCompute.RemoveHidden.Color, rtColor, 0);
                    cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.RemoveHidden.CascadesOffset, removeHiddenMagic);
                    cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.RemoveHidden.CascadesSize, RemoveHiddenCascadeSize);
                    cmd.SetComputeIntParam(cs, PointCloudShaderIDs.SolidCompute.RemoveHidden.FixedLevel, DebugSolidFixedLevel);
                    cmd.DispatchCompute(cs, removeHidden, GetGroupSize(width, 8), GetGroupSize(height, 8), 1);
                }
                break;

                case HprMode.DepthPrepass:
                {
                    var removeHidden = Resources.Kernels.RemoveHiddenDepthPrepass;
                    cmd.SetComputeTextureParam(cs, removeHidden, PointCloudShaderIDs.SolidCompute.RemoveHidden.Position, rt1);
                    cmd.SetComputeTextureParam(cs, removeHidden, PointCloudShaderIDs.SolidCompute.RemoveHidden.EarlyDepth, rtDepth2, 0);
                    cmd.SetComputeTextureParam(cs, removeHidden, PointCloudShaderIDs.SolidCompute.RemoveHidden.Color, rtColor, 0);
                    cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.RemoveHidden.PointScale, AbsoluteSize);
                    cmd.DispatchCompute(cs, removeHidden, GetGroupSize(width, 8), GetGroupSize(height, 8), 1);
                }
                break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            if (DebugSolidPullPush)
            {
                var pullKernel = Resources.Kernels.Pull;
                cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.PullKernel.FilterExponent, DebugSolidPullParam);

                for (var i = 1; i <= maxLevel; i++)
                {
                    GetMipData(resolution, i, out var mipRes, out var higherMipVec);
                    GetMipData(resolution, i - 1, out _, out var mipVec);
                    cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.MipTextureSize, mipVec);
                    cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.HigherMipTextureSize, higherMipVec);
                    cmd.SetComputeIntParam(cs, PointCloudShaderIDs.SolidCompute.PullKernel.SkipWeightMul, i == maxLevel ? 1 : 0);
                    cmd.SetComputeTextureParam(cs, pullKernel, PointCloudShaderIDs.SolidCompute.PullKernel.InputColor, rtColor, i - 1);
                    cmd.SetComputeTextureParam(cs, pullKernel, PointCloudShaderIDs.SolidCompute.PullKernel.OutputColor, rtColor, i);
                    cmd.DispatchCompute(cs, pullKernel, GetGroupSize(mipRes.x, 8), GetGroupSize(mipRes.y, 8), 1);
                }

                var pushKernel = Resources.Kernels.Push;

                for (var i = maxLevel; i > 0; i--)
                {
                    GetMipData(resolution, i - 1, out var mipRes, out var mipVec);
                    GetMipData(resolution, i, out _, out var lowerMipVec);
                    cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.MipTextureSize, mipVec);
                    cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.HigherMipTextureSize, lowerMipVec);
                    cmd.SetComputeIntParam(cs, PointCloudShaderIDs.SolidCompute.PushKernel.InputLevel, i);
                    cmd.SetComputeTextureParam(cs, pushKernel, PointCloudShaderIDs.SolidCompute.PushKernel.InputColor, rtColor, i);
                    cmd.SetComputeTextureParam(cs, pushKernel, PointCloudShaderIDs.SolidCompute.PushKernel.OutputColor, rtColor, i - 1);
                    cmd.DispatchCompute(cs, pushKernel, GetGroupSize(mipRes.x, 8), GetGroupSize(mipRes.y, 8), 1);
                }

                if (calculateNormals)
                {
                    var calculateNormalsKernel = Resources.Kernels.CalculateNormals;
                    var normalsTarget          = smoothNormals ? rt2 : rt1;

                    for (var i = 0; i < maxLevel; ++i)
                    {
                        GetMipData(resolution, i, out var mipRes, out var mipVec);
                        cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.MipTextureSize, mipVec);
                        cmd.SetComputeIntParam(cs, PointCloudShaderIDs.SolidCompute.CalculateNormals.InputLevel, i);
                        cmd.SetComputeTextureParam(cs, calculateNormalsKernel, PointCloudShaderIDs.SolidCompute.CalculateNormals.Input, rtColor);
                        cmd.SetComputeTextureParam(cs, calculateNormalsKernel, PointCloudShaderIDs.SolidCompute.CalculateNormals.Output, normalsTarget, i);
                        cmd.DispatchCompute(cs, calculateNormalsKernel, GetGroupSize(mipRes.x, 8), GetGroupSize(mipRes.x, 8), 1);
                    }

                    if (smoothNormals)
                    {
                        var smoothNormalsKernel = Resources.Kernels.GetSmoothNormalsKernel(DebugShowSmoothNormalsCascades);
                        var smoothNormalsMagic  = SmoothNormalsCascadeOffset * height * 0.5f / Mathf.Tan(0.5f * fov * Mathf.Deg2Rad);

                        cmd.SetComputeTextureParam(cs, smoothNormalsKernel, PointCloudShaderIDs.SolidCompute.SmoothNormals.Input, rt2);
                        cmd.SetComputeTextureParam(cs, smoothNormalsKernel, PointCloudShaderIDs.SolidCompute.SmoothNormals.Output, rt1, 0);
                        cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.SmoothNormals.CascadesOffset, smoothNormalsMagic);
                        cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.SmoothNormals.CascadesSize, SmoothNormalsCascadeSize);
                        if (DebugShowSmoothNormalsCascades)
                        {
                            cmd.SetComputeTextureParam(cs, smoothNormalsKernel, PointCloudShaderIDs.SolidCompute.SmoothNormals.ColorDebug, rtColor, 0);
                        }
                        cmd.DispatchCompute(cs, smoothNormalsKernel, GetGroupSize(width, 8), GetGroupSize(height, 8), 1);
                    }
                }
            }
        }
コード例 #8
0
        private void RenderSolidCore(CommandBuffer cmd, HDCamera targetCamera, RTHandle cameraColorBuffer, bool calculateNormals, bool smoothNormals)
        {
            CoreUtils.SetKeyword(cmd, PointCloudShaderIDs.SolidCompose.LinearDepthKeyword, DebugUseLinearDepth);

            var rt      = Resources.GetRTHandle(RTUsage.PointRender);
            var rt1     = Resources.GetRTHandle(RTUsage.Generic0);
            var rt2     = Resources.GetRTHandle(RTUsage.Generic1);
            var rtColor = Resources.GetRTHandle(RTUsage.ColorBuffer);
            var rtDepth = Resources.GetRTHandle(RTUsage.DepthBuffer);

            var width   = targetCamera.actualWidth;
            var height  = targetCamera.actualHeight;
            var refSize = rt.referenceSize;

            var resolution = new Vector2Int(width, height);

            var fov = targetCamera.camera.fieldOfView;

            if (SolidFovReprojection)
            {
                fov *= ReprojectionRatio;
            }

            var size = Math.Max(width, height);

            var maxLevel = 0;

            while (size >> maxLevel >= 16)
            {
                maxLevel++;
            }

            CoreUtils.SetRenderTarget(cmd, rt, rtDepth);
            CoreUtils.ClearRenderTarget(cmd, ClearFlag.All, Color.clear);

            CalculateMatrices(targetCamera, out var projMatrix, out var invProjMatrix, out var invViewProjMatrix, out var solidRenderMvp);

            cmd.SetGlobalBuffer(PointCloudShaderIDs.Shared.Buffer, GetBufferForCamera(targetCamera));
            cmd.SetGlobalInt(PointCloudShaderIDs.Shared.Colorize, (int)Colorize);
            cmd.SetGlobalFloat(PointCloudShaderIDs.Shared.MinHeight, Bounds.min.y);
            cmd.SetGlobalFloat(PointCloudShaderIDs.Shared.MaxHeight, Bounds.max.y);
            cmd.SetGlobalMatrix(PointCloudShaderIDs.SolidRender.MVPMatrix, solidRenderMvp);
            cmd.DrawProcedural(Matrix4x4.identity, Resources.SolidRenderMaterial, 0, MeshTopology.Points, GetPointCountForCamera(targetCamera));

            var cs = Resources.SolidComputeShader;

            cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.TextureSize, new Vector4(width - 1, height - 1, 1f / width, 1f / height));
            cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.FullRTSize, new Vector4(refSize.x - 1, refSize.y - 1, 1f / refSize.x, 1f / refSize.y));
            cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.FarPlane, targetCamera.camera.farClipPlane);
            cmd.SetComputeMatrixParam(cs, PointCloudShaderIDs.SolidCompute.ProjectionMatrix, projMatrix);
            cmd.SetComputeMatrixParam(cs, PointCloudShaderIDs.SolidCompute.InverseProjectionMatrix, invProjMatrix);
            cmd.SetComputeMatrixParam(cs, PointCloudShaderIDs.SolidCompute.InverseVPMatrix, invViewProjMatrix);
            cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.InverseReprojectionVector, GetInverseUvFovReprojectionVector(targetCamera.camera));

            var blendSky  = DebugBlendSky && cameraColorBuffer != null;
            var setupCopy = Resources.Kernels.GetSetupKernel(DebugUseLinearDepth, DebugForceFill, blendSky);

            cmd.SetComputeTextureParam(cs, setupCopy, PointCloudShaderIDs.SolidCompute.SetupCopy.InputColor, rt, 0);
            cmd.SetComputeTextureParam(cs, setupCopy, PointCloudShaderIDs.SolidCompute.SetupCopy.InputPosition, rtDepth, 0);
            cmd.SetComputeTextureParam(cs, setupCopy, PointCloudShaderIDs.SolidCompute.SetupCopy.OutputPosition, rt1, 0);
            cmd.SetComputeTextureParam(cs, setupCopy, PointCloudShaderIDs.SolidCompute.SetupCopy.OutputColor, rtColor, 0);
            if (blendSky)
            {
                cmd.SetComputeTextureParam(cs, setupCopy, PointCloudShaderIDs.SolidCompute.SetupCopy.PostSkyPreRenderTexture, cameraColorBuffer, 0);
            }
            cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.SetupCopy.HorizonThreshold, DebugFillThreshold);
            cmd.DispatchCompute(cs, setupCopy, GetGroupSize(width, 8), GetGroupSize(height, 8), 1);

            if (SolidRemoveHidden)
            {
                var downsample = Resources.Kernels.Downsample;
                for (var i = 1; i <= maxLevel + 3; i++)
                {
                    GetMipData(resolution, i - 1, out var mipRes, out var mipVec);
                    cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.MipTextureSize, mipVec);
                    cmd.SetComputeTextureParam(cs, downsample, PointCloudShaderIDs.SolidCompute.Downsample.InputPosition, rt1, i - 1);
                    cmd.SetComputeTextureParam(cs, downsample, PointCloudShaderIDs.SolidCompute.Downsample.OutputPosition, rt1, i);
                    cmd.DispatchCompute(cs, downsample, GetGroupSize(mipRes.x, 16), GetGroupSize(mipRes.y, 16), 1);
                }

                DebugSolidFixedLevel = Math.Min(Math.Max(DebugSolidFixedLevel, 0), maxLevel);

                var removeHidden      = Resources.Kernels.GetRemoveHiddenKernel(DebugShowRemoveHiddenCascades);
                var removeHiddenMagic = RemoveHiddenCascadeOffset * height * 0.5f / Mathf.Tan(0.5f * fov * Mathf.Deg2Rad);

                cmd.SetComputeIntParam(cs, PointCloudShaderIDs.SolidCompute.RemoveHidden.LevelCount, maxLevel);
                cmd.SetComputeTextureParam(cs, removeHidden, PointCloudShaderIDs.SolidCompute.RemoveHidden.Position, rt1);
                cmd.SetComputeTextureParam(cs, removeHidden, PointCloudShaderIDs.SolidCompute.RemoveHidden.Color, rtColor, 0);
                cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.RemoveHidden.CascadesOffset, removeHiddenMagic);
                cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.RemoveHidden.CascadesSize, RemoveHiddenCascadeSize);
                cmd.SetComputeIntParam(cs, PointCloudShaderIDs.SolidCompute.RemoveHidden.FixedLevel, DebugSolidFixedLevel);
                cmd.DispatchCompute(cs, removeHidden, GetGroupSize(width, 8), GetGroupSize(height, 8), 1);
            }

            if (DebugSolidPullPush)
            {
                var pullKernel = Resources.Kernels.Pull;
                cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.PullKernel.FilterExponent, DebugSolidPullParam);

                for (var i = 1; i <= maxLevel; i++)
                {
                    GetMipData(resolution, i, out var mipRes, out var higherMipVec);
                    GetMipData(resolution, i - 1, out _, out var mipVec);
                    cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.MipTextureSize, mipVec);
                    cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.HigherMipTextureSize, higherMipVec);
                    cmd.SetComputeIntParam(cs, PointCloudShaderIDs.SolidCompute.PullKernel.SkipWeightMul, i == maxLevel ? 1 : 0);
                    cmd.SetComputeIntParam(cs, PointCloudShaderIDs.SolidCompute.PullKernel.InputLevel, i - 1);
                    cmd.SetComputeTextureParam(cs, pullKernel, PointCloudShaderIDs.SolidCompute.PullKernel.InputColor, rtColor, i - 1);
                    cmd.SetComputeTextureParam(cs, pullKernel, PointCloudShaderIDs.SolidCompute.PullKernel.OutputColor, rtColor, i);
                    cmd.DispatchCompute(cs, pullKernel, GetGroupSize(mipRes.x, 8), GetGroupSize(mipRes.y, 8), 1);
                }

                var pushKernel = Resources.Kernels.Push;

                for (var i = maxLevel; i > 0; i--)
                {
                    GetMipData(resolution, i - 1, out var mipRes, out var mipVec);
                    GetMipData(resolution, i, out _, out var lowerMipVec);
                    cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.MipTextureSize, mipVec);
                    cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.HigherMipTextureSize, lowerMipVec);
                    cmd.SetComputeIntParam(cs, PointCloudShaderIDs.SolidCompute.PushKernel.InputLevel, i);
                    cmd.SetComputeTextureParam(cs, pushKernel, PointCloudShaderIDs.SolidCompute.PushKernel.InputColor, rtColor, i);
                    cmd.SetComputeTextureParam(cs, pushKernel, PointCloudShaderIDs.SolidCompute.PushKernel.OutputColor, rtColor, i - 1);
                    cmd.DispatchCompute(cs, pushKernel, GetGroupSize(mipRes.x, 8), GetGroupSize(mipRes.y, 8), 1);
                }

                if (calculateNormals)
                {
                    var calculateNormalsKernel = Resources.Kernels.GetCalculateNormalsKernel(DebugUseLinearDepth);
                    var normalsTarget          = smoothNormals ? rt2 : rt1;

                    for (var i = 0; i < maxLevel; ++i)
                    {
                        GetMipData(resolution, i, out var mipRes, out var mipVec);
                        cmd.SetComputeVectorParam(cs, PointCloudShaderIDs.SolidCompute.MipTextureSize, mipVec);
                        cmd.SetComputeIntParam(cs, PointCloudShaderIDs.SolidCompute.CalculateNormals.InputLevel, i);
                        cmd.SetComputeTextureParam(cs, calculateNormalsKernel, PointCloudShaderIDs.SolidCompute.CalculateNormals.Input, rtColor);
                        cmd.SetComputeTextureParam(cs, calculateNormalsKernel, PointCloudShaderIDs.SolidCompute.CalculateNormals.Output, normalsTarget, i);
                        cmd.DispatchCompute(cs, calculateNormalsKernel, GetGroupSize(mipRes.x, 8), GetGroupSize(mipRes.x, 8), 1);
                    }

                    if (smoothNormals)
                    {
                        var smoothNormalsKernel = Resources.Kernels.GetSmoothNormalsKernel(DebugUseLinearDepth, DebugShowSmoothNormalsCascades);
                        var smoothNormalsMagic  = SmoothNormalsCascadeOffset * height * 0.5f / Mathf.Tan(0.5f * fov * Mathf.Deg2Rad);

                        cmd.SetComputeTextureParam(cs, smoothNormalsKernel, PointCloudShaderIDs.SolidCompute.SmoothNormals.Input, rt2);
                        cmd.SetComputeTextureParam(cs, smoothNormalsKernel, PointCloudShaderIDs.SolidCompute.SmoothNormals.Output, rt1, 0);
                        cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.SmoothNormals.CascadesOffset, smoothNormalsMagic);
                        cmd.SetComputeFloatParam(cs, PointCloudShaderIDs.SolidCompute.SmoothNormals.CascadesSize, SmoothNormalsCascadeSize);
                        if (DebugShowSmoothNormalsCascades)
                        {
                            cmd.SetComputeTextureParam(cs, smoothNormalsKernel, PointCloudShaderIDs.SolidCompute.SmoothNormals.ColorDebug, rtColor, 0);
                        }
                        cmd.DispatchCompute(cs, smoothNormalsKernel, GetGroupSize(width, 8), GetGroupSize(height, 8), 1);
                    }
                }
            }
        }
コード例 #9
0
    void GenerateGaussianMips(CommandBuffer cmd, HDCamera hdCam)
    {
        RTHandle   source;
        Vector2Int size = new Vector2Int(hdCam.actualWidth, hdCam.actualHeight);

        if (targetColorBuffer == TargetBuffer.Camera)
        {
            GetCameraBuffers(out source, out _);
        }
        else
        {
            GetCustomBuffers(out source, out _);
        }

        int dstMipWidth  = Mathf.Max(1, size.x >> 1);
        int dstMipHeight = Mathf.Max(1, size.y >> 1);

        // Scale for downsample
        float scaleX = ((float)size.x / source.rt.width);
        float scaleY = ((float)size.y / source.rt.height);

        if (useMask)
        {
            // Save the non blurred color into a copy:
            cmd.CopyTexture(source, colorCopy);
        }

        // Downsample.
        using (new ProfilingSample(cmd, "Downsample", CustomSampler.Create("Downsample")))
        {
            var downsampleProperties = new MaterialPropertyBlock();
            downsampleProperties.SetTexture(ShaderID._BlitTexture, source);
            downsampleProperties.SetVector(ShaderID._BlitScaleBias, new Vector4(scaleX, scaleY, 0f, 0f));
            downsampleProperties.SetFloat(ShaderID._BlitMipLevel, 0);
            CoreUtils.SetRenderTarget(cmd, downSampleBuffer, ClearFlag.None);
            cmd.SetViewport(new Rect(0, 0, dstMipWidth, dstMipHeight));
            cmd.DrawProcedural(Matrix4x4.identity, HDUtils.GetBlitMaterial(source.rt.dimension), 1, MeshTopology.Triangles, 3, 1, downsampleProperties);
        }

        // Horizontal Blur
        using (new ProfilingSample(cmd, "H Blur", CustomSampler.Create("H Blur")))
        {
            var hBlurProperties = new MaterialPropertyBlock();
            CoreUtils.SetRenderTarget(cmd, blurBuffer, ClearFlag.None);
            hBlurProperties.SetFloat(ShaderID._Radius, radius / 4.0f);      // The blur is 4 pixel wide in the shader
            hBlurProperties.SetTexture(ShaderID._Source, downSampleBuffer); // The blur is 4 pixel wide in the shader
            hBlurProperties.SetFloat(ShaderID._UVScale, 2);
            cmd.SetViewport(new Rect(0, 0, dstMipWidth, dstMipHeight));
            CoreUtils.DrawFullScreen(cmd, blurMaterial, shaderPassId: 0, properties: hBlurProperties); // Do not forget the shaderPassId: ! or it won't work
        }

        // Copy back the result in the color buffer while doing a vertical blur
        using (new ProfilingSample(cmd, "V Blur + Copy back", CustomSampler.Create("V Blur + Copy back")))
        {
            var vBlurProperties = new MaterialPropertyBlock();
            // When we use a mask, we do the vertical blur into the downsampling buffer instead of the camera buffer
            // We need that because we're going to write to the color buffer and read from this blured buffer which we can't do
            // if they are in the same buffer
            CoreUtils.SetRenderTarget(cmd, (useMask) ? downSampleBuffer : source, ClearFlag.None);
            vBlurProperties.SetFloat(ShaderID._Radius, radius / 4.0f); // The blur is 4 pixel wide in the shader
            vBlurProperties.SetTexture(ShaderID._Source, blurBuffer);
            vBlurProperties.SetFloat(ShaderID._UVScale, (useMask) ? 2 : 1);
            CoreUtils.DrawFullScreen(cmd, blurMaterial, shaderPassId: 1, properties: vBlurProperties);
        }

        if (useMask)
        {
            using (new ProfilingSample(cmd, "Compose Mask Blur", CustomSampler.Create("Compose Mask Blur")))
            {
                var compositingProperties = new MaterialPropertyBlock();

                CoreUtils.SetRenderTarget(cmd, source, ClearFlag.None);
                compositingProperties.SetFloat(ShaderID._Radius, radius / 4.0f); // The blur is 4 pixel wide in the shader
                compositingProperties.SetTexture(ShaderID._Source, downSampleBuffer);
                compositingProperties.SetTexture(ShaderID._ColorBufferCopy, colorCopy);
                compositingProperties.SetTexture(ShaderID._Mask, maskBuffer);
                compositingProperties.SetTexture(ShaderID._MaskDepth, maskDepthBuffer);
                compositingProperties.SetFloat(ShaderID._InvertMask, invertMask ? 1 : 0);
                CoreUtils.DrawFullScreen(cmd, blurMaterial, shaderPassId: 2, properties: compositingProperties);
            }
        }
    }
コード例 #10
0
        void OnOverlayGUI(Object target, SceneView sceneView)
        {
            // Draw a preview of the captured texture from the planar reflection

            // Get the exposure texture used in this scene view
            if (!(RenderPipelineManager.currentPipeline is HDRenderPipeline hdrp))
            {
                return;
            }
            var hdCamera    = HDCamera.GetOrCreate(sceneView.camera);
            var exposureTex = hdrp.GetExposureTexture(hdCamera);

            var index = Array.IndexOf(m_TypedTargets, target);

            if (index == -1)
            {
                return;
            }
            var p = m_TypedTargets[index];

            if (p.texture == null)
            {
                return;
            }

            var previewWidth = k_PreviewHeight;
            var previewSize  = new Rect(previewWidth, k_PreviewHeight + EditorGUIUtility.singleLineHeight + 2, 0, 0);

            if (Event.current.type == EventType.Layout ||
                !firstDraw && Event.current.type == EventType.Repaint)
            {
                // Get and reserve rect
                //this can cause the following issue if calls on a repaint before a layout:
                //ArgumentException: Getting control 0's position in a group with only 0 controls when doing repaint
                var cameraRect = GUILayoutUtility.GetRect(previewSize.x, previewSize.y);
                firstDraw = false;

                // The aspect ratio of the capture texture may not be the aspect of the texture
                // So we need to stretch back the texture to the aspect used during the capture
                // to give users a non distorded preview of the capture.
                // Here we compute a centered rect that has the correct aspect for the texture preview.
                var c = new Rect(cameraRect);
                c.y += EditorGUIUtility.singleLineHeight + 2;
                if (p.renderData.aspect > 1)
                {
                    c.width  = k_PreviewHeight;
                    c.height = k_PreviewHeight / p.renderData.aspect;
                    c.y     += (k_PreviewHeight - c.height) * 0.5f;
                }
                else
                {
                    c.width  = k_PreviewHeight * p.renderData.aspect;
                    c.height = k_PreviewHeight;
                    c.x     += (k_PreviewHeight - c.width) * 0.5f;
                }

                // Setup the material to draw the quad with the exposure texture
                var material = GUITextureBlit2SRGBMaterial;
                material.SetTexture("_Exposure", exposureTex);
                Graphics.DrawTexture(c, p.texture, new Rect(0, 0, 1, 1), 0, 0, 0, 0, GUI.color, material, -1);

                // We now display the FoV and aspect used during the capture of the planar reflection
                var fovRect = new Rect(cameraRect);
                fovRect.x     += 5;
                fovRect.y     += 2;
                fovRect.width -= 10;
                fovRect.height = EditorGUIUtility.singleLineHeight;
                var width = fovRect.width;
                fovRect.width = width * 0.5f;
                GUI.TextField(fovRect, $"F: {p.renderData.fieldOfView:F2}°");
                fovRect.x    += width * 0.5f;
                fovRect.width = width * 0.5f;
                GUI.TextField(fovRect, $"A: {p.renderData.aspect:F2}");
            }
        }
コード例 #11
0
        public void RenderDepth(CommandBuffer cmd, HDCamera targetCamera, RTHandle colorBuffer, RTHandle depthBuffer)
        {
            var solid = RenderMode == RenderType.Solid;

            RenderDepth(cmd, targetCamera, colorBuffer, depthBuffer, solid);
        }
コード例 #12
0
        private void UpdateShaderVariablesProbeVolumes(ref ShaderVariablesGlobal cb, HDCamera hdCamera)
        {
            bool loadedData = ProbeReferenceVolume.instance.DataHasBeenLoaded();

            cb._EnableProbeVolumes = (hdCamera.frameSettings.IsEnabled(FrameSettingsField.ProbeVolume) && loadedData) ? 1u : 0u;
        }
コード例 #13
0
        protected sealed override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResult)
        {
            if (PostProcessSystem == null)
            {
                return;
            }

            var sensor = hdCamera.camera.GetComponent <CameraSensorBase>();

            if (sensor == null || sensor.Postprocessing == null || sensor.Postprocessing.Count == 0)
            {
                return;
            }

            // Late postprocessing queue is always called directly, never executed through volume
            if (PostProcessSystem.IsLatePostprocess(sensor, typeof(TData)))
            {
                return;
            }

            GetCameraBuffers(out var colorBuffer, out _);

            if (!IsActive)
            {
                PostProcessSystem.Skip(cmd, colorBuffer, sensor, true, false);
                return;
            }

            TData data = null;

            foreach (var sensorData in sensor.Postprocessing)
            {
                if (sensorData is TData matchingData)
                {
                    data = matchingData;
                    break;
                }
            }

            if (data == null)
            {
                return;
            }

            PostProcessSystem.GetRTHandles(cmd, colorBuffer, sensor, true, false, out var source, out var target);

            Render(cmd, hdCamera, source, target, data);

            PostProcessSystem.RecycleSourceRT(source, colorBuffer, true);
        }
コード例 #14
0
 /// <summary>
 /// <para>Called when this postprocessing pass is supposed to be rendered.</para>
 /// <para>All rendering code for this pass should be executed here.</para>
 /// </summary>
 /// <param name="cmd">Buffer used to queue commands.</param>
 /// <param name="camera">HD camera used by the sensor.</param>
 /// <param name="source"><see cref="RTHandle"/> that should be used as a source (can be sampled).</param>
 /// <param name="destination"><see cref="RTHandle"/> that should be used as a target (can't be sampled).</param>
 /// <param name="data">Data container for postprocessing parameters.</param>
 protected abstract void Render(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination, TData data);
コード例 #15
0
        void ExecuteNormalBufferBlur(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, RTHandle cameraColor, RTHandle cameraDepth, RTHandle cameraNormal, CullingResults cullingResults)
        {
            if (!EnsureMaterial(ref passMaterial, NAME_SHADER))
            {
                return;
            }

            if (layerMask == 0)
            {
                return;
            }

            if (!hdCamera.frameSettings.IsEnabled(FrameSettingsField.Decals))
            {
                return;
            }

            int bufferW = cameraColor.rt.width;
            int bufferH = cameraColor.rt.height;

            // allocate temporary buffers
            cmd.GetTemporaryRT(rtRegions, bufferW, bufferH, (int)DepthBits.None, FilterMode.Point, RenderTextureFormat.R8, RenderTextureReadWrite.Linear, 1, false);
            cmd.GetTemporaryRT(rtDecoded, bufferW, bufferH, (int)DepthBits.None, FilterMode.Point, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear, 1, false);

            // render decals to mark blur regions
            CoreUtils.SetRenderTarget(cmd,
                                      rtRegions, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store,
                                      cameraDepth, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store,
                                      ClearFlag.Color, Color.white
                                      );
            CoreUtils.SetViewport(cmd, cameraDepth);

            RendererListDesc renderListDesc = new RendererListDesc(NAME_PASS_REPLACE_TAG, cullingResults, hdCamera.camera)
            {
                rendererConfiguration      = PerObjectData.None,
                renderQueueRange           = GetRenderQueueRange(queue),
                sortingCriteria            = SortingCriteria.None,
                layerMask                  = layerMask,
                overrideMaterial           = passMaterial,
                overrideMaterialPassIndex  = PASS_MARK,
                stateBlock                 = null,
                excludeObjectMotionVectors = false,
            };

#if UNITY_2020_2_OR_NEWER
            CoreUtils.DrawRendererList(renderContext, cmd, RendererList.Create(renderListDesc));
#else
            HDUtils.DrawRendererList(renderContext, cmd, RendererList.Create(renderListDesc));
#endif

            // decode normal buffer in marked regions
            CoreUtils.SetRenderTarget(cmd,
                                      rtDecoded, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store,
                                      cameraDepth, RenderBufferLoadAction.Load, RenderBufferStoreAction.DontCare,
                                      ClearFlag.None
                                      );
            CoreUtils.SetViewport(cmd, cameraDepth);

            cmd.SetRandomWriteTarget(2, cameraNormal);
            cmd.DrawProcedural(Matrix4x4.identity, passMaterial, PASS_DECODE, MeshTopology.Triangles, 3, 1);
            cmd.ClearRandomWriteTargets();

            // blur and re-encode normals in marked regions
            cmd.SetGlobalTexture(rtRegions, rtRegions);
            cmd.SetGlobalTexture(rtDecoded, rtDecoded);

            if (dbufferNormalMaskRTIDs != null)
            {
                CoreUtils.SetRenderTarget(cmd,
                                          dbufferNormalMaskRTIDs,
                                          cameraDepth,
                                          ClearFlag.None);
                CoreUtils.SetViewport(cmd, cameraDepth);

                cmd.SetRandomWriteTarget(2, cameraNormal);
                cmd.DrawProcedural(Matrix4x4.identity, passMaterial, PASS_BLUR_AND_ENCODE_AND_DECAL, MeshTopology.Triangles, 3, 1);
                cmd.ClearRandomWriteTargets();
            }
            else
            {
                CoreUtils.SetRenderTarget(cmd,
                                          cameraDepth, RenderBufferLoadAction.Load, RenderBufferStoreAction.Store,
                                          ClearFlag.None
                                          );
                CoreUtils.SetViewport(cmd, cameraDepth);

                cmd.SetRandomWriteTarget(2, cameraNormal);
                cmd.DrawProcedural(Matrix4x4.identity, passMaterial, PASS_BLUR_AND_ENCODE, MeshTopology.Triangles, 3, 1);
                cmd.ClearRandomWriteTargets();
            }

            // free temporary buffers
            cmd.ReleaseTemporaryRT(rtRegions);
            cmd.ReleaseTemporaryRT(rtDecoded);
        }
コード例 #16
0
    public override void Render(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination)
    {
        //mat is the material which contains the shader
        //we are passing the destination RenderTexture to

        if (m_Material == null)
        {
            // Debug.Log("material stuck at null");
            return;
        }

        if (rth1 == null)
        {
            rth1 = GetNewRTHandle(camera);
        }
        if (rth2 == null)
        {
            rth2 = GetNewRTHandle(camera);
        }

        // Init ();
        buffersToDispose = new List <ComputeBuffer> ();

        // InitRenderTexture ();
        // CreateScene ();
        // SetParameters ();

        // get depth texture
        Vector4 parameters = new Vector4(depthDistance.value, depthDistance.value, depthDistance.value, depthDistance.value);

        m_Material.SetVector("_Params", parameters);
        m_Material.SetTexture("_InputTexture", source);
        HDUtils.DrawFullScreen(cmd, m_Material, rth1, matProperties, 3);

        // // RenderTexture sourceCopy = source;
        // HDUtils.DrawFullScreen(cmd, m_Material, rth1);
        //
        // // Graphics.Blit(source,depthTexture);
        //
        raymarching.SetTexture(0, "Depth", source.rt);
        raymarching.SetTexture(0, "Source", source);
        raymarching.SetTexture(0, "Destination", rth1);

        raymarching.SetFloat("nearPlane", nearPlaneDepth);
        raymarching.SetFloat("farPlane", farPlaneDepth);

        int threadGroupsX = Mathf.CeilToInt(cam.pixelWidth / 8.0f);
        int threadGroupsY = Mathf.CeilToInt(cam.pixelHeight / 8.0f);
        int kernelHandle  = raymarching.FindKernel("CSMain");

        raymarching.Dispatch(kernelHandle, threadGroupsX, threadGroupsY, 1);
        // Graphics.Blit(target, destination);

        m_Material.SetTexture("_InputTexture", rth1);
        HDUtils.DrawFullScreen(cmd, m_Material, destination);
        // cam.targetTexture = depthTexture;
        // mask things

        // RenderTexture.ReleaseTemporary(depthTexture);
        foreach (var buffer in buffersToDispose)
        {
            buffer.Dispose();
        }
    }
コード例 #17
0
 protected override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera camera, CullingResults cullingResult)
 {
     // Executed every frame for all the camera inside the pass volume
 }
コード例 #18
0
ファイル: SunFlareFX.cs プロジェクト: yangjunwhy/simulator
        protected override void Render(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination, SunFlare data)
        {
            var cam         = camera.camera;
            var sunForward  = sunTransform.forward;
            var sunWorldPos = cam.transform.position - sunForward * 1000f;
            var sunViewPos  = cam.WorldToViewportPoint(sunWorldPos);

            var intensity  = Mathf.Clamp01(Vector3.Dot(cam.transform.forward, -sunForward));
            var sunVisible = sunViewPos.z > 0 && sunViewPos.x >= -0.1f && sunViewPos.x < 1.1f &&
                             sunViewPos.y >= -0.1f && sunViewPos.y < 1.1f;

            if (!sunVisible)
            {
                if (Physics.Raycast(cam.transform.position, -sunForward, 1000f, LayerMask))
                {
                    intensity = 0f;
                }
            }

            if (intensity > 0f)
            {
                GetCameraBuffers(out _, out var depthBuffer);
                var depthTexRes      = depthBuffer.referenceSize;
                var actualCameraSize = new Vector2Int(camera.actualWidth, camera.actualHeight);
                var occlTexRes       = new Vector2Int(OcclusionRes, OcclusionRes);

                var scaleRatio  = new Vector2((float)actualCameraSize.x / depthTexRes.x, (float)actualCameraSize.y / depthTexRes.y);
                var aspectRatio = (float)actualCameraSize.y / actualCameraSize.x;
                var scaledSun   = new Vector4(sunViewPos.x * scaleRatio.x, sunViewPos.y * scaleRatio.y,
                                              0.1f * aspectRatio * scaleRatio.x, 0.1f * scaleRatio.y);

                cmd.SetComputeVectorParam(computeShader, DepthTextureRes,
                                          new Vector4(depthTexRes.x, depthTexRes.y, 1f / depthTexRes.x, 1f / depthTexRes.y));
                cmd.SetComputeVectorParam(computeShader, OcclusionTextureRes,
                                          new Vector4(occlTexRes.x, occlTexRes.y, 1f / occlTexRes.x, 1f / occlTexRes.y));
                cmd.SetComputeVectorParam(computeShader, SunViewPos, scaledSun);

                var kernel = textureOcclusionKernel;
                cmd.SetComputeTextureParam(computeShader, kernel, DepthTexture, depthBuffer);
                cmd.SetComputeTextureParam(computeShader, kernel, OcclusionTextureOut, occlusionTextureA);
                cmd.DispatchCompute(computeShader, kernel, OcclusionRes / 8, OcclusionRes / 8, 1);

                kernel = blurTextureOcclusionKernel;
                cmd.SetComputeTextureParam(computeShader, kernel, OcclusionTextureIn, occlusionTextureA);
                cmd.SetComputeTextureParam(computeShader, kernel, OcclusionTextureOut, occlusionTextureB);
                cmd.DispatchCompute(computeShader, kernel, OcclusionRes / 8, OcclusionRes / 8, 1);

                kernel = reduceTextureOcclusionKernel;
                cmd.SetComputeTextureParam(computeShader, kernel, OcclusionTextureIn, occlusionTextureB);
                cmd.SetComputeTextureParam(computeShader, kernel, OcclusionTextureOut, occlusionTextureA);
                cmd.DispatchCompute(computeShader, kernel, 1, 1, 1);

                kernel = angleOcclusionKernel;
                cmd.SetComputeTextureParam(computeShader, kernel, OcclusionTextureIn, occlusionTextureB);
                cmd.SetComputeBufferParam(computeShader, kernel, AngleOcclusion, angleOcclusion);
                cmd.DispatchCompute(computeShader, kernel, AngleSamples / 64, 1, 1);

                cmd.SetGlobalVector(SunViewPos, sunViewPos);
                cmd.SetGlobalVector(SunSettings,
                                    new Vector4(data.sunIntensity, data.haloIntensity, data.ghostingIntensity, intensity));
                cmd.SetGlobalTexture(InputTexture, source);
                cmd.SetGlobalTexture(OcclusionTextureIn, occlusionTextureA);
                cmd.SetGlobalTexture(OcclusionTextureOut, occlusionTextureB);
                cmd.SetGlobalBuffer(AngleOcclusion, angleOcclusion);
                HDUtils.DrawFullScreen(cmd, material, destination);
            }
            else
            {
                HDUtils.BlitCameraTexture(cmd, source, destination);
            }
        }
コード例 #19
0
        public void RenderDepth(CommandBuffer cmd, HDCamera targetCamera, RTHandle colorBuffer, RTHandle depthBuffer, CubemapFace cubemapFace = CubemapFace.Unknown)
        {
            var solid = RenderMode == RenderType.Solid;

            RenderDepth(cmd, targetCamera, colorBuffer, depthBuffer, solid, cubemapFace);
        }
 protected override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResults)
 {
     Profiler.BeginSample("NormalBufferBlurPass");
     ExecuteNormalBufferBlur(renderContext, cmd, hdCamera, cullingResults);
     Profiler.EndSample();
 }
コード例 #21
0
    protected override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera camera, CullingResults cullingResult)
    {
        DrawOutlineMeshes(renderContext, cmd, camera, cullingResult);

        SetCameraRenderTarget(cmd);

        outlineProperties.SetColor("_OutlineColor", outlineColor);
        outlineProperties.SetTexture("_OutlineBuffer", outlineBuffer);
        outlineProperties.SetFloat("_Threshold", threshold);
        CoreUtils.DrawFullScreen(cmd, fullscreenOutline, outlineProperties, shaderPassId: 0);
    }
コード例 #22
0
        protected sealed override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResult)
        {
            // CustomPasses are executed for each camera. We only want to run for the target camera
            if (hdCamera.camera != targetCamera)
            {
                return;
            }

            ExecutePass(renderContext, cmd, hdCamera, cullingResult);
        }
コード例 #23
0
    protected override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResult)
    {
        AllocateMaskBuffersIfNeeded();

        if (blurMaterial != null && radius > 0)
        {
            if (useMask)
            {
                DrawMaskObjects(renderContext, cmd, hdCamera, cullingResult);
            }

            GenerateGaussianMips(cmd, hdCamera);
        }
    }
コード例 #24
0
 protected abstract void ExecutePass(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResult);
コード例 #25
0
    void GenerateGaussianMips(CommandBuffer cmd, HDCamera hdCam)
    {
        RTHandle source;

        // Retrieve the target buffer of the blur from the UI:
        if (targetColorBuffer == TargetBuffer.Camera)
        {
            GetCameraBuffers(out source, out _);
        }
        else
        {
            GetCustomBuffers(out source, out _);
        }

        // Save the non blurred color into a copy if the mask is enabled:
        if (useMask)
        {
            cmd.CopyTexture(source, colorCopy);
        }

        // Downsample
        using (new ProfilingSample(cmd, "Downsample", CustomSampler.Create("Downsample")))
        {
            // This Blit will automatically downsample the color because our target buffer have been allocated in half resolution
            HDUtils.BlitCameraTexture(cmd, source, downSampleBuffer, 0);
        }

        // Horizontal Blur
        using (new ProfilingSample(cmd, "H Blur", CustomSampler.Create("H Blur")))
        {
            var hBlurProperties = new MaterialPropertyBlock();
            hBlurProperties.SetFloat(ShaderID._Radius, radius / 4.0f);                               // The blur is 4 pixel wide in the shader
            hBlurProperties.SetTexture(ShaderID._Source, downSampleBuffer);                          // The blur is 4 pixel wide in the shader
            SetViewPortSize(cmd, hBlurProperties, blurBuffer);
            HDUtils.DrawFullScreen(cmd, blurMaterial, blurBuffer, hBlurProperties, shaderPassId: 0); // Do not forget the shaderPassId: ! or it won't work
        }

        // Copy back the result in the color buffer while doing a vertical blur
        using (new ProfilingSample(cmd, "V Blur + Copy back", CustomSampler.Create("V Blur + Copy back")))
        {
            var vBlurProperties = new MaterialPropertyBlock();
            // When we use a mask, we do the vertical blur into the downsampling buffer instead of the camera buffer
            // We need that because we're going to write to the color buffer and read from this blured buffer which we can't do
            // if they are in the same buffer
            vBlurProperties.SetFloat(ShaderID._Radius, radius / 4.0f); // The blur is 4 pixel wide in the shader
            vBlurProperties.SetTexture(ShaderID._Source, blurBuffer);
            var targetBuffer = (useMask) ? downSampleBuffer : source;
            SetViewPortSize(cmd, vBlurProperties, targetBuffer);
            HDUtils.DrawFullScreen(cmd, blurMaterial, targetBuffer, vBlurProperties, shaderPassId: 1); // Do not forget the shaderPassId: ! or it won't work
        }

        if (useMask)
        {
            // Merge the non blur copy and the blurred version using the mask buffers
            using (new ProfilingSample(cmd, "Compose Mask Blur", CustomSampler.Create("Compose Mask Blur")))
            {
                var compositingProperties = new MaterialPropertyBlock();

                compositingProperties.SetFloat(ShaderID._Radius, radius / 4.0f); // The blur is 4 pixel wide in the shader
                compositingProperties.SetTexture(ShaderID._Source, downSampleBuffer);
                compositingProperties.SetTexture(ShaderID._ColorBufferCopy, colorCopy);
                compositingProperties.SetTexture(ShaderID._Mask, maskBuffer);
                compositingProperties.SetTexture(ShaderID._MaskDepth, maskDepthBuffer);
                compositingProperties.SetFloat(ShaderID._InvertMask, invertMask ? 1 : 0);
                SetViewPortSize(cmd, compositingProperties, source);
                HDUtils.DrawFullScreen(cmd, blurMaterial, source, compositingProperties, shaderPassId: 2); // Do not forget the shaderPassId: ! or it won't work
            }
        }
    }
コード例 #26
0
        // We have to lock api.ActionsSemaphore before the first continuation (await)
        // to make sure API calls are executed one after the other
        public async void Execute(JSONNode args)
        {
            var sim = SimulatorManager.Instance;
            var api = ApiManager.Instance;

            // instead of relying on ApiMAnager's exception handling,
            // we wrap the whole method since we are async
            try
            {
                if (sim == null)
                {
                    throw new Exception("SimulatorManager not found! Is scene loaded?");
                }

                var name             = args["name"].Value;
                var type             = args["type"].AsInt;
                var position         = args["state"]["transform"]["position"].ReadVector3();
                var rotation         = args["state"]["transform"]["rotation"].ReadVector3();
                var velocity         = args["state"]["velocity"].ReadVector3();
                var angular_velocity = args["state"]["angular_velocity"].ReadVector3();

                string uid;
                var    argsUid = args["uid"];
                if (argsUid == null)
                {
                    uid = System.Guid.NewGuid().ToString();
                    // Add uid key to arguments, as it will be distributed to the clients' simulations
                    if (Loader.Instance.Network.IsMaster)
                    {
                        args.Add("uid", uid);
                    }
                }
                else
                {
                    uid = argsUid.Value;
                }

                if (type == (int)AgentType.Ego)
                {
                    var        agents  = SimulatorManager.Instance.AgentManager;
                    GameObject agentGO = null;

                    VehicleDetailData vehicleData = await ConnectionManager.API.GetByIdOrName <VehicleDetailData>(name);

                    var config = new AgentConfig(vehicleData.ToVehicleData());
                    config.Position = position;
                    config.Rotation = Quaternion.Euler(rotation);

                    if (ApiManager.Instance.CachedVehicles.ContainsKey(vehicleData.Name))
                    {
                        config.Prefab = ApiManager.Instance.CachedVehicles[vehicleData.Name];
                    }
                    else
                    {
                        var assetModel = await DownloadManager.GetAsset(BundleConfig.BundleTypes.Vehicle, vehicleData.AssetGuid, vehicleData.Name);

                        config.Prefab = Loader.LoadVehicleBundle(assetModel.LocalPath);
                    }

                    if (config.Prefab == null)
                    {
                        throw new Exception($"failed to acquire ego prefab");
                    }

                    var downloads = new List <Task>();
                    List <SensorData> sensorsToDownload = new List <SensorData>();
                    ConcurrentDictionary <Task, string> assetDownloads = new ConcurrentDictionary <Task, string>();

                    if (config.Sensors != null)
                    {
                        foreach (var plugin in config.Sensors)
                        {
                            if (plugin.Plugin.AssetGuid != null && sensorsToDownload.FirstOrDefault(s => s.Plugin.AssetGuid == plugin.Plugin.AssetGuid) == null)
                            {
                                sensorsToDownload.Add(plugin);
                            }
                        }
                    }

                    if (config.BridgeData != null)
                    {
                        var pluginTask = DownloadManager.GetAsset(BundleConfig.BundleTypes.Bridge, config.BridgeData.AssetGuid, config.BridgeData.Name);
                        downloads.Add(pluginTask);
                        assetDownloads.TryAdd(pluginTask, config.BridgeData.Type);
                    }

                    foreach (var sensor in sensorsToDownload)
                    {
                        var pluginTask = DownloadManager.GetAsset(BundleConfig.BundleTypes.Sensor, sensor.Plugin.AssetGuid,
                                                                  sensor.Name);
                        downloads.Add(pluginTask);
                        assetDownloads.TryAdd(pluginTask, sensor.Type);
                    }

                    await Task.WhenAll(downloads);

                    foreach (var download in downloads)
                    {
                        assetDownloads.TryRemove(download, out _);
                    }

                    agentGO = agents.SpawnAgent(config);

                    if (agents.ActiveAgents.Count == 1)
                    {
                        agents.SetCurrentActiveAgent(agentGO);
                        var hdCamera = HDCamera.GetOrCreate(SimulatorManager.Instance.CameraManager.SimulatorCamera);
                        hdCamera.RequestExposureAdaptationLock();
                    }

                    var rb = agentGO.GetComponent <Rigidbody>();
                    if (rb != null)
                    {
                        rb.velocity        = velocity;
                        rb.angularVelocity = angular_velocity;
                    }

                    Debug.Assert(agentGO != null);
                    api.Agents.Add(uid, agentGO);
                    api.AgentUID.Add(agentGO, uid);

                    var sensors = agentGO.GetComponentsInChildren <SensorBase>(true);

                    foreach (var sensor in sensors)
                    {
                        var sensorUid = System.Guid.NewGuid().ToString();
                        if (SimulatorManager.InstanceAvailable)
                        {
                            SimulatorManager.Instance.Sensors.AppendUid(sensor, sensorUid);
                        }
                    }

                    api.SendResult(this, new JSONString(uid));
                }
                else if (type == (int)AgentType.Npc)
                {
                    var colorData = args["color"].ReadVector3();
                    var template  = sim.NPCManager.NPCVehicles.Find(obj => obj.Prefab.name == name);
                    if (template.Prefab == null)
                    {
                        throw new Exception($"Unknown '{name}' NPC name");
                    }

                    var spawnData = new NPCManager.NPCSpawnData
                    {
                        Active   = true,
                        GenId    = uid,
                        Template = template,
                        Position = position,
                        Rotation = Quaternion.Euler(rotation),
                        Color    = colorData == new Vector3(-1, -1, -1) ? sim.NPCManager.GetWeightedRandomColor(template.NPCType) : new Color(colorData.x, colorData.y, colorData.z),
                        Seed     = sim.NPCManager.NPCSeedGenerator.Next(),
                    };

                    var npcController = SimulatorManager.Instance.NPCManager.SpawnNPC(spawnData);
                    npcController.IsUserSpecified = true;
                    npcController.SetBehaviour <NPCManualBehaviour>();

                    var body = npcController.GetComponent <Rigidbody>();
                    body.velocity        = velocity;
                    body.angularVelocity = angular_velocity;

                    uid = npcController.name;
                    api.Agents.Add(uid, npcController.gameObject);
                    api.AgentUID.Add(npcController.gameObject, uid);
                    api.SendResult(this, new JSONString(uid));

                    // Override the color argument as NPCController may change the NPC color
                    if (Loader.Instance.Network.IsMaster)
                    {
                        var colorVector = new Vector3(npcController.NPCColor.r, npcController.NPCColor.g, npcController.NPCColor.b);
                        args["color"].WriteVector3(colorVector);
                    }
                }
                else if (type == (int)AgentType.Pedestrian)
                {
                    var pedManager = SimulatorManager.Instance.PedestrianManager;
                    if (!pedManager.gameObject.activeSelf)
                    {
                        var sceneName = SceneManager.GetActiveScene().name;
                        throw new Exception($"{sceneName} is missing Pedestrian NavMesh");
                    }

                    var model = sim.PedestrianManager.PedestrianData.Find(obj => obj.Name == name).Prefab;
                    if (model == null)
                    {
                        throw new Exception($"Unknown '{name}' pedestrian name");
                    }

                    var spawnData = new PedestrianManager.PedSpawnData
                    {
                        Active   = true,
                        API      = true,
                        GenId    = uid,
                        Model    = model,
                        Position = position,
                        Rotation = Quaternion.Euler(rotation),
                        Seed     = sim.PedestrianManager.PEDSeedGenerator.Next(),
                    };

                    var pedController = pedManager.SpawnPedestrian(spawnData);
                    if (pedController == null)
                    {
                        throw new Exception($"Pedestrian controller error for '{name}'");
                    }

                    api.Agents.Add(uid, pedController.gameObject);
                    api.AgentUID.Add(pedController.gameObject, uid);
                    api.SendResult(this, new JSONString(uid));
                }
                else
                {
                    throw new Exception($"Unsupported '{args["type"]}' type");
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
                api.SendError(this, e.Message);
            }
            finally
            {
                Executed?.Invoke(this);
            }
        }
コード例 #27
0
 protected override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResult)
 {
     CoreUtils.SetRenderTarget(cmd, targetTexture, ClearFlag.All);
     m_InstanceSegmentationCrossPipelinePass.Execute(renderContext, cmd, hdCamera.camera, cullingResult);
 }
コード例 #28
0
        protected override void Execute(ScriptableRenderContext renderContext, CommandBuffer cmd, HDCamera hdCamera, CullingResults cullingResults)
        {
            RTHandle cameraColor;
            RTHandle cameraDepth;

            GetCameraBuffers(out cameraColor, out cameraDepth);

            Profiler.BeginSample("NormalBufferBlurPass");
            ExecuteNormalBufferBlur(
                renderContext,
                cmd,
                hdCamera,
                cameraColor,
                cameraDepth,
                GetNormalBuffer(),
                cullingResults
                );
            Profiler.EndSample();
        }
コード例 #29
0
 /// <summary>Creates a new FrameProperties from an <see cref="HDCamera"/>.</summary>
 /// <param name="hdCamera">The camera to use.</param>
 public static RenderOutputProperties From(HDCamera hdCamera)
 => new RenderOutputProperties(
     new Vector2Int(hdCamera.actualWidth, hdCamera.actualHeight),
     hdCamera.camera.cameraToWorldMatrix,
     hdCamera.mainViewConstants.projMatrix
     );
コード例 #30
0
        public override void Render(CommandBuffer cmd, HDCamera camera, RTHandle srcRT, RTHandle destRT)
        {
            if (_material == null)
            {
                return;
            }

            // Update the time parameters.
            var time  = Time.time;
            var delta = time - _prevTime;

            _jumpTime += delta * jump.value * 11.3f;
            _prevTime  = time;

            // Block parameters
            var block3 = block.value * block.value * block.value;

            // Shuffle block parameters every 1/30 seconds.
            _blockTime += delta * 60;
            if (_blockTime > 1)
            {
                if (Random.value < 0.09f)
                {
                    _blockSeed1 += 251;
                }
                if (Random.value < 0.29f)
                {
                    _blockSeed2 += 373;
                }
                if (Random.value < 0.25f)
                {
                    _blockStride = Random.Range(1, 32);
                }
                _blockTime = 0;
            }

            // Drift parameters (time, displacement)
            var vdrift = new Vector2(
                time * 606.11f % (Mathf.PI * 2),
                drift.value * 0.04f
                );

            // Jitter parameters (threshold, displacement)
            var jv      = jitter.value;
            var vjitter = new Vector3(
                Mathf.Max(0, 1.001f - jv * 1.2f),
                0.002f + jv * jv * jv * 0.05f
                );

            // Jump parameters (scroll, displacement)
            var vjump = new Vector2(_jumpTime, jump.value);

            // Invoke the shader.
            _material.SetInt(ShaderIDs.Seed, (int)(time * 10000));
            _material.SetFloat(ShaderIDs.BlockStrength, block3);
            _material.SetInt(ShaderIDs.BlockStride, _blockStride);
            _material.SetInt(ShaderIDs.BlockSeed1, _blockSeed1);
            _material.SetInt(ShaderIDs.BlockSeed2, _blockSeed2);
            _material.SetVector(ShaderIDs.Drift, vdrift);
            _material.SetVector(ShaderIDs.Jitter, vjitter);
            _material.SetVector(ShaderIDs.Jump, vjump);
            _material.SetFloat(ShaderIDs.Shake, shake.value * 0.2f);
            _material.SetTexture(ShaderIDs.InputTexture, srcRT);

            // Shader pass number
            var pass = 0;

            if (drift.value > 0 || jitter.value > 0 || jump.value > 0 || shake.value > 0)
            {
                pass += 1;
            }
            if (block.value > 0)
            {
                pass += 2;
            }

            // Blit
            HDUtils.DrawFullScreen(cmd, _material, destRT, null, pass);
        }