Beispiel #1
0
    public void Start()
    {
        m_shadowmap     = BuiltinRenderTextureType.CurrentActive;
        m_ShadowmapCopy = new RenderTexture(1024, 1024, 0, RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear);

        m_lightShadowCommandBuffer = new CommandBuffer();

        // Change shadow sampling mode for m_Light's shadowmap.
        m_lightShadowCommandBuffer.SetShadowSamplingMode(m_shadowmap, ShadowSamplingMode.RawDepth);

        // The shadowmap values can now be sampled normally - copy it to a different render texture.
        m_lightShadowCommandBuffer.Blit(m_shadowmap, new RenderTargetIdentifier(m_ShadowmapCopy));

        // Execute after the shadowmap has been filled.
        light.AddCommandBuffer(LightEvent.AfterShadowMapPass, m_lightShadowCommandBuffer);

        // Sampling mode is restored automatically after this command buffer completes, so shadows will render normally.
    }
        void OnEnable()
        {
            m_Transform = GetComponent <Transform>();
            m_Light     = GetComponent <Light>();
            if (m_Light == null)
            {
                Debug.LogError("DeepSky::DS_HazeLightVolume: No Light component found on " + gameObject.name);
                enabled = false;
            }

            if (kLightVolumeShader == null)
            {
                kLightVolumeShader = Resources.Load <Shader>("DS_HazeLightVolume");
            }

            if (m_VolumeMaterial == null)
            {
                m_VolumeMaterial           = new Material(kLightVolumeShader);
                m_VolumeMaterial.hideFlags = HideFlags.HideAndDontSave;
            }

            if (m_RenderCmd == null)
            {
                m_RenderCmd      = new CommandBuffer();
                m_RenderCmd.name = gameObject.name + "_DS_Haze_RenderLightVolume";
                m_Light.AddCommandBuffer(LightEvent.AfterShadowMap, m_RenderCmd);
            }

            if (LightTypeChanged())
            {
                UpdateLightType();
            }
            else if (ProxyMeshRequiresRebuild())
            {
                RebuildProxyMesh();
            }

            if (ShadowModeChanged())
            {
                UpdateShadowMode();
            }

            Register();
        }
Beispiel #3
0
    public static int AddCommandBuffer(IntPtr l)
    {
        int result;

        try
        {
            int num = LuaDLL.lua_gettop(l);
            if (num == 3)
            {
                Light      light = (Light)LuaObject.checkSelf(l);
                LightEvent evt;
                LuaObject.checkEnum <LightEvent>(l, 2, out evt);
                CommandBuffer buffer;
                LuaObject.checkType <CommandBuffer>(l, 3, out buffer);
                light.AddCommandBuffer(evt, buffer);
                LuaObject.pushValue(l, true);
                result = 1;
            }
            else if (num == 4)
            {
                Light      light2 = (Light)LuaObject.checkSelf(l);
                LightEvent evt2;
                LuaObject.checkEnum <LightEvent>(l, 2, out evt2);
                CommandBuffer buffer2;
                LuaObject.checkType <CommandBuffer>(l, 3, out buffer2);
                ShadowMapPass shadowPassMask;
                LuaObject.checkEnum <ShadowMapPass>(l, 4, out shadowPassMask);
                light2.AddCommandBuffer(evt2, buffer2, shadowPassMask);
                LuaObject.pushValue(l, true);
                result = 1;
            }
            else
            {
                LuaObject.pushValue(l, false);
                LuaDLL.lua_pushstring(l, "No matched override function AddCommandBuffer to call");
                result = 2;
            }
        }
        catch (Exception e)
        {
            result = LuaObject.error(l, e);
        }
        return(result);
    }
Beispiel #4
0
        //might want to name this to InitShadowsCommandBuffers()
        private void InitCommandBuffers()
        {
            for (int i = 0; i < m_cachedNumLods; i++)
            {
                m_cachedLodShadowSettings[i] = m_LodSettings[i].shadowSetting;
            }

            m_shadowCasterCullingCommand      = new CommandBuffer();
            m_shadowCasterCullingCommand.name = "Shadow Caster Culling";
            m_shadowCasterCullingCommand.DispatchCompute(m_computeShader, m_cachedShadowComputeKernel, Mathf.CeilToInt(m_instanceCount / 256f), 1, 1);
            for (int i = 0; i < m_cachedNumLods; i++)
            {
                for (int j = 0; j < m_LodSettings[i].mesh.subMeshCount; j++)
                {
                    m_shadowCasterCullingCommand.CopyCounterValue(m_appendBuffers[i], m_argsBuffersArray[i][j], 1 * sizeof(uint));
                }
            }

            m_drawShadowCasterCommand      = new CommandBuffer();
            m_drawShadowCasterCommand.name = "Draw Instanced Shadow Casters";
            for (int i = 0; i < m_cachedNumLods; i++)
            {
                if (m_cachedLodShadowSettings[i] != ShadowCastingMode.Off)
                {
                    for (int j = 0; j < m_LodSettings[i].mesh.subMeshCount; j++)
                    {
                        int shadowCasterPass = m_materials[i][j].FindPass("SHADOWCASTER");
                        m_drawShadowCasterCommand.DrawMeshInstancedIndirect(m_LodSettings[i].mesh, j, m_materials[i][j], shadowCasterPass, m_argsBuffersArray[i][j], 0);
                    }
                }
            }

            //if lod0 doesnt draw shadows then no lod draw shadows for now
            if (m_cachedLodShadowSettings[0] != ShadowCastingMode.Off)
            {
                //the shadow caster culling pass finds shadow casters not visible to the camera, this lets us disable that at will
                if (m_castShadowIfCulled)
                {
                    m_mainCamera.AddCommandBuffer(CameraEvent.BeforeLighting, m_shadowCasterCullingCommand);
                }

                m_directionalLight.AddCommandBuffer(LightEvent.BeforeShadowMapPass, m_drawShadowCasterCommand);
            }
        }
Beispiel #5
0
        public CommandBuffer GetCommandBuffer()
        {
            if (m_cb == null)
            {
                RenderTargetIdentifier shadowmap = BuiltinRenderTextureType.CurrentActive;

                CreateShadowTexture();

                m_cb      = new CommandBuffer();
                m_cb.name = "Hair Shadow";

                m_cb.SetShadowSamplingMode(shadowmap, ShadowSamplingMode.RawDepth);

                m_cb.Blit(shadowmap, new RenderTargetIdentifier(m_ShadowmapCopy));

                m_Light.AddCommandBuffer(LightEvent.AfterShadowMap, m_cb);
            }
            return(m_cb);
        }
        public void OnEnable(Light light)
        {
            if (cb == null)
            {
                cb      = new CommandBuffer();
                cb.name = "Cache Shadowmap";
            }
            light.AddCommandBuffer(LightEvent.AfterShadowMap, cb);

            if (shadowMap == null)
            {
                int res = ShadowmapResolution(light.type);
                shadowMap = RenderUtils.GetRenderTexture(res, res, 0, RenderTextureFormat.RFloat, FilterMode.Point);
                if (light.type == LightType.Point)
                {
                    shadowMap.dimension = TextureDimension.Cube;
                }
            }
        }
Beispiel #7
0
    private static int AddCommandBuffer(IntPtr L)
    {
        int result;

        try
        {
            ToLua.CheckArgsCount(L, 3);
            Light         light         = (Light)ToLua.CheckObject(L, 1, typeof(Light));
            LightEvent    lightEvent    = (int)ToLua.CheckObject(L, 2, typeof(LightEvent));
            CommandBuffer commandBuffer = (CommandBuffer)ToLua.CheckObject(L, 3, typeof(CommandBuffer));
            light.AddCommandBuffer(lightEvent, commandBuffer);
            result = 0;
        }
        catch (Exception e)
        {
            result = LuaDLL.toluaL_exception(L, e, null);
        }
        return(result);
    }
Beispiel #8
0
        public ShadowMapCopyCommandBuffer()
        {
            // after light's shadow map is computed, copy it
            RenderTargetIdentifier shadowmap = BuiltinRenderTextureType.CurrentActive;

            m_Buffer      = new CommandBuffer();
            m_Buffer.name = "ScattererShadowMapCopy";

            // Change shadow sampling mode for shadowmap.
            m_Buffer.SetShadowSamplingMode(shadowmap, ShadowSamplingMode.RawDepth);

            //copy shadowmap
//			m_Buffer.Blit (shadowmap, Scatterer.Instance.bufferRenderingManager.occlusionTexture); //change to shadowmap texture

            m_Light = GetComponent <Light>();
            m_Light.AddCommandBuffer(LightEvent.AfterShadowMap, m_Buffer);

            // Sampling mode is restored automatically after this command buffer completes, so shadows will render normally.
        }
Beispiel #9
0
    private void Start()
    {
        mmMat       = new Material(mmShader);
        rayTraceMat = new Material(raytraceShader);
        cam         = Camera.main;

        cb_sm      = new CommandBuffer();
        cb_sm.name = "MZ Sample ShadowMap";
        mainLight.AddCommandBuffer(LightEvent.AfterShadowMap, cb_sm);

        RenderTargetIdentifier shadowmap = BuiltinRenderTextureType.CurrentActive;

        cb_sm.SetShadowSamplingMode(shadowmap, ShadowSamplingMode.RawDepth);
        cb_sm.Blit(shadowmap, new RenderTargetIdentifier(shadowMapCopy));

        int[] mip_id = new int[10];
        int   size   = 1024;
        RenderTargetIdentifier sourceId = new RenderTargetIdentifier(shadowMapCopy);

        for (int i = 0; i < 10; i++)
        {
            mip_id[i] = Shader.PropertyToID("minmax_" + i.ToString());
            size      = size >> 1;
            if (size == 0)
            {
                size = 1;
            }

            RenderTexture temp = RenderTexture.GetTemporary(size, 1024, 0, RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear);
            temp.filterMode = FilterMode.Point;
            temp.useMipMap  = false;
            if (i == 0)
            {
                cb_sm.Blit(sourceId, temp, mmMat, 0);
            }
            else
            {
                cb_sm.Blit(sourceId, temp, mmMat, 1);
            }
            rayTraceMat.SetTexture("sm_mip_" + i.ToString(), temp);
            temp.Release();
        }
    }
Beispiel #10
0
    /**********************************************************************************************
    *  Function:        AddShadowMapToCommandBuffer()
    *  Parameters:      None
    *  Return:          None
    *  Description:     Adds a copy of the current shadow map to the command buffer, making it
    *                   available for use in additional rendering steps.
    *
    *  References:      https://interplayoflight.wordpress.com/2015/07/03/adventures-in-postprocessing-with-unity/
    **********************************************************************************************/
    void AddShadowMapToCommandBuffer()
    {
        // Create a new CommandBuffer to store the shadow map
        MyShadowMap = new CommandBuffer {
            name = "Volumetric Fog Shadow Map"
        };

        // Set a global texture target to gather the shadow map to on each pass
        MyShadowMap.SetGlobalTexture("ShadowMap", new RenderTargetIdentifier(BuiltinRenderTextureType.CurrentActive));

        // Get a handle to this light component
        Light thisLight = transform.GetComponent <Light>();

        if (thisLight)
        {
            // Connect the light source's output to the CommandBuffer
            thisLight.AddCommandBuffer(LightEvent.AfterShadowMap, MyShadowMap);
        }
    }
    void AddCommandBuffers()
    {
        computeShadowsCB = new CommandBuffer {
            name = "NGSS ContactShadows: Compute"
        };
        blendShadowsCB = new CommandBuffer {
            name = "NGSS ContactShadows: Mix"
        };

        if (mCamera)
        {
            bool canAddBuff = true;
            foreach (CommandBuffer cb in mCamera.GetCommandBuffers(mCamera.actualRenderingPath == RenderingPath.Forward ? CameraEvent.AfterDepthTexture : CameraEvent.BeforeLighting))
            {
                if (cb.name == computeShadowsCB.name)
                {
                    canAddBuff = false;
                }
            }
            if (canAddBuff)
            {
                mCamera.AddCommandBuffer(mCamera.actualRenderingPath == RenderingPath.Forward ? CameraEvent.AfterDepthTexture : CameraEvent.BeforeLighting, computeShadowsCB);
            }
        }

        //uncomment me if using the screen space blit | comment me if sampling directly from internal NGSS libraries
        if (contactShadowsLight)
        {
            bool canAddBuff = true;
            foreach (CommandBuffer cb in contactShadowsLight.GetCommandBuffers(LightEvent.AfterScreenspaceMask))
            {
                if (cb.name == blendShadowsCB.name)
                {
                    canAddBuff = false;
                }
            }
            if (canAddBuff)
            {
                contactShadowsLight.AddCommandBuffer(LightEvent.AfterScreenspaceMask, blendShadowsCB);
            }
        }
    }
Beispiel #12
0
    public void Setup()
    {
        _light = GetComponent <Light>();
        if (!_light)
        {
            return;
        }

        resolution = Mathf.ClosestPowerOfTwo(resolution);
        if (customShadowResolution)
        {
            _light.shadowCustomResolution = resolution;
        }
        else
        {
            _light.shadowCustomResolution = 0;
        }

        shader          = Shader.Find(shaderName);
        shadowmapPropID = Shader.PropertyToID("_ShadowMap");

        copyShadowBuffer      = new CommandBuffer();
        copyShadowBuffer.name = "PCSS Shadows";

        var buffers = _light.GetCommandBuffers(lightEvent);

        for (int i = 0; i < buffers.Length; i++)
        {
            if (buffers[i].name == "PCSS Shadows")
            {
                _light.RemoveCommandBuffer(lightEvent, buffers[i]);
            }
        }

        _light.AddCommandBuffer(lightEvent, copyShadowBuffer);
        GraphicsSettings.SetCustomShader(BuiltinShaderType.ScreenSpaceShadows, shader);
        GraphicsSettings.SetShaderMode(BuiltinShaderType.ScreenSpaceShadows, BuiltinShaderMode.UseCustom);

        CreateShadowRenderTexture();
        UpdateShaderValues();
        UpdateCommandBuffer();
    }
Beispiel #13
0
    void Start()
    {
        _commandBuffer      = new CommandBuffer();
        _commandBuffer.name = "Light Command Buffer";

        _cascadeShadowCommandBuffer      = new CommandBuffer();
        _cascadeShadowCommandBuffer.name = "Dir Light Command Buffer";
        _cascadeShadowCommandBuffer.SetGlobalTexture("_CascadeShadowMapTexture", new UnityEngine.Rendering.RenderTargetIdentifier(UnityEngine.Rendering.BuiltinRenderTextureType.CurrentActive));

        _light = GetComponent <Light>();

        _light.AddCommandBuffer(LightEvent.AfterShadowMap, _commandBuffer);

        Shader shader = Shader.Find("Sandbox/VolumetricLight");

        if (shader == null)
        {
            throw new Exception("Critical Error: \"Sandbox/VolumetricLight\" shader is missing. Make sure it is included in \"Always Included Shaders\" in ProjectSettings/Graphics.");
        }
        _material = new Material(shader);
    }
    private void Start()
    {
        mmMat = new Material(mmShader);
        cam   = Camera.main;

        cb_sm      = new CommandBuffer();
        cb_sm.name = "MZ Sample ShadowMap";
        mainLight.AddCommandBuffer(LightEvent.AfterShadowMap, cb_sm);

        RenderTargetIdentifier shadowmap = BuiltinRenderTextureType.CurrentActive;

        cb_sm.SetShadowSamplingMode(shadowmap, ShadowSamplingMode.RawDepth);
        cb_sm.Blit(shadowmap, new RenderTargetIdentifier(shadowMapCopy));


        int kernel = InitCS();

        cb_sm.DispatchCompute(cs_light, kernel, 1024, 1, 1);

        //cb_sm.Blit(null, target, mmMat);
    }
Beispiel #15
0
    // Sets up a command buffer to copy the shadow map of this light.
    void Setup()
    {
        // Clean up any previously set command buffers.
        // (Maybe residual from executing in editor)?
        Cleanup();

        // Create and name new command buffer.
        cb      = new CommandBuffer();
        cb.name = textureName + " (Shadow Map Copy)";

        // Set the global texture to be the just rendered shadow map.
        cb.SetGlobalTexture(textureName, new RenderTargetIdentifier(BuiltinRenderTextureType.CurrentActive));

        // Add the command buffer (right after shadows have been rendered) to this light.
        Light light = GetComponent <Light>();

        if (light != null)
        {
            light.AddCommandBuffer(LightEvent.AfterShadowMap, cb);
        }
    }
Beispiel #16
0
 // Update is called once per frame
 void Update()
 {
     if (!isInit)
     {
         return;
     }
     if (useCustomLightDepthMap)
     {
         lightCam.fieldOfView  = _light.spotAngle;
         lightCam.farClipPlane = _light.range;
     }
     else
     {
         if (lightCam != null && lightCam.enabled)
         {
             lightCam.enabled = false;
         }
     }
     if (useCustomLightDepthMap != oldCustomDepthFlag)
     {
         DestroyImmediate(_material);
         _material           = new Material(volumeLightShader);
         _material.hideFlags = HideFlags.HideAndDontSave;
         if (useCustomLightDepthMap)
         {
             _light.shadows = LightShadows.None;
             _light.RemoveAllCommandBuffers();
             _shadowCommandBuffer.Clear();
             VolumeLightMgr.Instance._camera.AddCommandBuffer(CameraEvent.AfterForwardOpaque, _shadowCommandBuffer);
         }
         else
         {
             _light.shadows = LightShadows.Soft;
             VolumeLightMgr.Instance._camera.RemoveCommandBuffer(CameraEvent.AfterForwardOpaque, _shadowCommandBuffer);
             _shadowCommandBuffer.Clear();
             _light.AddCommandBuffer(LightEvent.AfterShadowMap, _shadowCommandBuffer);
         }
     }
     oldCustomDepthFlag = useCustomLightDepthMap;
 }
 void Start()
 {
     camera_command_buffer      = new CommandBuffer();
     camera_command_buffer.name = "PointCloudGeometry";
     light_command_buffer       = new CommandBuffer();
     light_command_buffer.name  = "PointCloudLighting";
     compute_buffer             = new ComputeBuffer(number, sizeof(float) * 3, ComputeBufferType.Default);
     Vector3[] cloud = new Vector3[number];
     for (uint i = 0; i < number; ++i)
     {
         cloud[i]   = new Vector3();
         cloud[i].x = Random.Range(-10.0f, 10.0f);
         cloud[i].y = Random.Range(-10.0f, 10.0f);
         cloud[i].z = Random.Range(-10.0f, 10.0f);
     }
     compute_buffer.SetData(cloud);
     material.SetBuffer("cloud", compute_buffer);
     camera_command_buffer.DrawProcedural(Matrix4x4.identity, material, 0, MeshTopology.Points, number);
     camera_source.AddCommandBuffer(CameraEvent.AfterGBuffer, camera_command_buffer);
     light_command_buffer.DrawProcedural(Matrix4x4.identity, material, 0, MeshTopology.Points, number);
     light_source.AddCommandBuffer(LightEvent.BeforeShadowMapPass, light_command_buffer);
 }
    void AddCommandBuffers()
    {
        computeShadowsCB = new CommandBuffer {
            name = "NGSS ContactShadows: Compute"
        };
        blendShadowsCB = new CommandBuffer {
            name = "NGSS ContactShadows: Mix"
        };

        bool forward = mCamera.renderingPath == RenderingPath.Forward;

        if (mCamera)
        {
            foreach (CommandBuffer cb in mCamera.GetCommandBuffers(forward? CameraEvent.AfterDepthTexture : CameraEvent.BeforeLighting))
            {
                if (cb.name == computeShadowsCB.name)
                {
                    return;
                }
            }
            mCamera.AddCommandBuffer(forward ? CameraEvent.AfterDepthTexture : CameraEvent.BeforeLighting, computeShadowsCB);
        }

        if (mainDirectionalLight)
        {
            foreach (CommandBuffer cb in mainDirectionalLight.GetCommandBuffers(LightEvent.AfterScreenspaceMask))
            {
                if (cb.name == blendShadowsCB.name)
                {
                    return;
                }
            }
            mainDirectionalLight.AddCommandBuffer(LightEvent.AfterScreenspaceMask, blendShadowsCB);
        }
        //else { Debug.LogWarning("NGSS Error: No directional light set. Disabling the component, please provide one and re-enable the component again.", this); enabled = false; }
    }
    void Start()
    {
#if UNITY_5_5_OR_NEWER
        if (SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D11 || SystemInfo.graphicsDeviceType == GraphicsDeviceType.Direct3D12 ||
            SystemInfo.graphicsDeviceType == GraphicsDeviceType.Metal || SystemInfo.graphicsDeviceType == GraphicsDeviceType.PlayStation4 ||
            SystemInfo.graphicsDeviceType == GraphicsDeviceType.Vulkan || SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOne)
        {
            _reversedZ = true;
        }
#endif

        _commandBuffer      = new CommandBuffer();
        _commandBuffer.name = "Light Command Buffer";

        _light = GetComponent <Light>();
        _light.AddCommandBuffer(LightEvent.AfterShadowMap, _commandBuffer);

        Shader shader = Shader.Find("Sandbox/VolumetricLight");
        if (shader == null)
        {
            throw new Exception("Critical Error: \"Sandbox/VolumetricLight\" shader is missing. Make sure it is included in \"Always Included Shaders\" in ProjectSettings/Graphics.");
        }
        _material = new Material(shader); // new Material(VolumetricLightRenderer.GetLightMaterial());
    }
Beispiel #20
0
    /// <summary>
    /// Update the lights information and send them to the shader
    /// </summary>
    void UpdateLights()
    {
        bool hasShadows = false;

        int pointLightIndex = 0;
        int spotLighIndex   = 0;

        bounds.center = transform.position;

        foreach (ZEDLight zed_light in ZEDLight.s_lights)
        {
            Light light = zed_light.cachedLight;

            if (light.type == LightType.Directional || Vector3.Distance(bounds.center, light.transform.position) < (light.range + bounds.extents.x))
            {
                //Desactivate all shadows from point light and spot light, they are not currently supported
                if (light.type != LightType.Directional)
                {
                    light.shadows = LightShadows.None;
                }
                if (zed_light.IsEnabled() && ((pointLightIndex + spotLighIndex) < NUMBER_LIGHTS_MAX || light.type == LightType.Directional))
                {
                    if (light.type == LightType.Point)
                    {
                        if (pointLightIndex < NUMBER_POINT_LIGHT_MAX)
                        {
                            pointLights[pointLightIndex].color    = light.color * light.intensity;
                            pointLights[pointLightIndex].position = light.gameObject.transform.position;
                            pointLights[pointLightIndex].range    = light.range;

                            pointLightIndex++;
                        }
                    }

                    else if (light.type == LightType.Spot)
                    {
                        if (spotLighIndex < NUMBER_SPOT_LIGHT_MAX)
                        {
                            spotLights[spotLighIndex].color      = light.color * light.intensity;
                            spotLights[spotLighIndex].position   = light.gameObject.transform.position;
                            spotLights[spotLighIndex].direction  = new Vector4(light.gameObject.transform.forward.normalized.x, light.gameObject.transform.forward.normalized.y, light.gameObject.transform.forward.normalized.z, Mathf.Cos((light.spotAngle / 2.0f) * Mathf.Deg2Rad));
                            spotLights[spotLighIndex].parameters = new Vector4(light.spotAngle, light.intensity, 1.0f / light.range, zed_light.interiorCone);
                            spotLighIndex++;
                        }
                    }
                    else if (light.type == LightType.Directional)
                    {
                        hasShadows = light.shadows != LightShadows.None && QualitySettings.shadows != ShadowQuality.Disable;
                        directionalLightData[0] = new Vector4(light.gameObject.transform.forward.normalized.x, light.gameObject.transform.forward.normalized.y, light.gameObject.transform.forward.normalized.z, 0);
                        directionalLightData[1] = light.color * light.intensity;
                        // Copy the shadows from the directional light, If not no shadows in transparent mode
                        if (light.commandBufferCount == 0)
                        {
                            forwardMat.SetInt("_HasShadows", System.Convert.ToInt32(light.shadows != LightShadows.None));

                            // Copy the shadows from the directional light, If not no shadows in transparent mode
                            if (light.commandBufferCount == 0)
                            {
                                CommandBuffer lightBuffer = new CommandBuffer();
                                lightBuffer.name = "ZED_Copy_ShadowMap";
                                lightBuffer.SetGlobalTexture("_DirectionalShadowMap", BuiltinRenderTextureType.CurrentActive);

                                light.AddCommandBuffer(LightEvent.AfterScreenspaceMask, lightBuffer);
                            }
                        }
                    }
                }
            }
        }
        //Upload the new Data
        if (computeBuffePointLight != null)
        {
            computeBuffePointLight.SetData(pointLights);
        }
        if (computeBufferSpotLight != null)
        {
            computeBufferSpotLight.SetData(spotLights);
        }

        numberPointLights = pointLightIndex;
        numberSpotLights  = spotLighIndex;

        if (matRGB != null)
        {
            //Add the command buffer to get shadows only if a directional light creates shadows
            if (hasShadows != ghasShadows)
            {
                ghasShadows = hasShadows;
                Shader.SetGlobalInt("_HasShadows", System.Convert.ToInt32(ghasShadows));
                mainCamera.RemoveCommandBuffer(CameraEvent.BeforeDepthTexture, buffer[(int)ZED_RENDERING_MODE.FORWARD]);
                if (hasShadows)
                {
                    mainCamera.AddCommandBuffer(CameraEvent.BeforeDepthTexture, buffer[(int)ZED_RENDERING_MODE.FORWARD]);
                }
            }
            //Send the number of pointLights/SpotLights to the shader
            matRGB.SetInt(numberPointLightsID, pointLightIndex);
            matRGB.SetInt(numberSpotLightsID, spotLighIndex);
        }
        matRGB.SetVectorArray("ZED_directionalLight", directionalLightData);
    }
Beispiel #21
0
        public override void UpdateLodData()
        {
            base.UpdateLodData();

            if (_mainLight != OceanRenderer.Instance._primaryLight)
            {
                if (_mainLight)
                {
                    _mainLight.RemoveCommandBuffer(LightEvent.BeforeScreenspaceMask, _bufCopyShadowMap);
                    _bufCopyShadowMap = null;
                    TextureArrayHelpers.ClearToBlack(_sources);
                    TextureArrayHelpers.ClearToBlack(_targets);
                }
                _mainLight = null;
            }

            if (!OceanRenderer.Instance._primaryLight)
            {
                if (!Settings._allowNullLight)
                {
                    Debug.LogWarning("Primary light must be specified on OceanRenderer script to enable shadows.", this);
                }
                return;
            }

            if (!_mainLight)
            {
                if (!StartInitLight())
                {
                    enabled = false;
                    return;
                }
            }

            if (_bufCopyShadowMap == null && s_processData)
            {
                _bufCopyShadowMap      = new CommandBuffer();
                _bufCopyShadowMap.name = "Shadow data";
                _mainLight.AddCommandBuffer(LightEvent.BeforeScreenspaceMask, _bufCopyShadowMap);
            }
            else if (!s_processData && _bufCopyShadowMap != null)
            {
                _mainLight.RemoveCommandBuffer(LightEvent.BeforeScreenspaceMask, _bufCopyShadowMap);
                _bufCopyShadowMap = null;
            }

            if (!s_processData)
            {
                return;
            }


            var lodCount = OceanRenderer.Instance.CurrentLodCount;

            SwapRTs(ref _sources, ref _targets);

            _bufCopyShadowMap.Clear();

            var lt = OceanRenderer.Instance._lodTransform;

            ValidateSourceData();
            // clear the shadow collection. it will be overwritten with shadow values IF the shadows render,
            // which only happens if there are (nontransparent) shadow receivers around
            TextureArrayHelpers.ClearToBlack(_targets);
            for (var lodIdx = OceanRenderer.Instance.CurrentLodCount - 1; lodIdx >= 0; lodIdx--)
            {
                _renderProperties.Initialise(_bufCopyShadowMap, _updateShadowShader, krnl_UpdateShadow);


                lt._renderData[lodIdx].Validate(0, this);
                _renderProperties.SetVector(sp_CenterPos, lt._renderData[lodIdx]._posSnapped);
                _renderProperties.SetVector(sp_Scale, lt.GetLodTransform(lodIdx).lossyScale);
                _renderProperties.SetVector(sp_CamPos, OceanRenderer.Instance.Viewpoint.position);
                _renderProperties.SetVector(sp_CamForward, OceanRenderer.Instance.Viewpoint.forward);
                _renderProperties.SetVector(sp_JitterDiameters_CurrentFrameWeights, new Vector4(Settings._jitterDiameterSoft, Settings._jitterDiameterHard, Settings._currentFrameWeightSoft, Settings._currentFrameWeightHard));
                _renderProperties.SetMatrix(sp_MainCameraProjectionMatrix, _cameraMain.projectionMatrix * _cameraMain.worldToCameraMatrix);
                _renderProperties.SetFloat(sp_SimDeltaTime, Time.deltaTime);

                // compute which lod data we are sampling previous frame shadows from. if a scale change has happened this can be any lod up or down the chain.
                var srcDataIdx = lodIdx + ScaleDifferencePow2;
                srcDataIdx = Mathf.Clamp(srcDataIdx, 0, lt.LodCount - 1);
                _renderProperties.SetFloat(OceanRenderer.sp_LD_SliceIndex, lodIdx);
                _renderProperties.SetFloat(sp_LD_SliceIndex_Source, srcDataIdx);
                BindSourceData(_renderProperties, false);
                _renderProperties.SetTexture(
                    sp_LD_TexArray_Target,
                    _targets
                    );
                _renderProperties.DispatchShader();
            }
        }
Beispiel #22
0
        public override void UpdateLodData()
        {
            if (!enabled)
            {
                return;
            }

            base.UpdateLodData();

            if (_mainLight != OceanRenderer.Instance._primaryLight)
            {
                if (_mainLight)
                {
                    _mainLight.RemoveCommandBuffer(LightEvent.BeforeScreenspaceMask, BufCopyShadowMap);
                    BufCopyShadowMap = null;
                    TextureArrayHelpers.ClearToBlack(_sources);
                    TextureArrayHelpers.ClearToBlack(_targets);
                }
                _mainLight = null;
            }

            if (!OceanRenderer.Instance._primaryLight)
            {
                if (!Settings._allowNullLight)
                {
                    Debug.LogWarning("Primary light must be specified on OceanRenderer script to enable shadows.", OceanRenderer.Instance);
                }
                return;
            }

            if (!_mainLight)
            {
                if (!StartInitLight())
                {
                    enabled = false;
                    return;
                }
            }

            if (BufCopyShadowMap == null && s_processData)
            {
                BufCopyShadowMap      = new CommandBuffer();
                BufCopyShadowMap.name = "Shadow data";
                _mainLight.AddCommandBuffer(LightEvent.BeforeScreenspaceMask, BufCopyShadowMap);
            }
            else if (!s_processData && BufCopyShadowMap != null)
            {
                _mainLight.RemoveCommandBuffer(LightEvent.BeforeScreenspaceMask, BufCopyShadowMap);
                BufCopyShadowMap = null;
            }

            if (!s_processData)
            {
                return;
            }

            // Update the camera if it has changed.
            if (_cameraMain.transform != OceanRenderer.Instance.Viewpoint)
            {
                UpdateCameraMain();
            }

            Swap(ref _sources, ref _targets);

            BufCopyShadowMap.Clear();

            ValidateSourceData();

            // clear the shadow collection. it will be overwritten with shadow values IF the shadows render,
            // which only happens if there are (nontransparent) shadow receivers around. this is only reliable
            // in play mode, so don't do it in edit mode.
#if UNITY_EDITOR
            if (UnityEditor.EditorApplication.isPlaying)
#endif
            {
                TextureArrayHelpers.ClearToBlack(_targets);
            }

            var lt = OceanRenderer.Instance._lodTransform;
            for (var lodIdx = lt.LodCount - 1; lodIdx >= 0; lodIdx--)
            {
                _renderProperties.Initialise(BufCopyShadowMap, _updateShadowShader, krnl_UpdateShadow);

                lt._renderData[lodIdx].Validate(0, SimName);
                _renderProperties.SetVector(sp_CenterPos, lt._renderData[lodIdx]._posSnapped);
                var scale = OceanRenderer.Instance.CalcLodScale(lodIdx);
                _renderProperties.SetVector(sp_Scale, new Vector3(scale, 1f, scale));

                if (OceanRenderer.Instance.Viewpoint != null)
                {
                    _renderProperties.SetVector(sp_CamPos, OceanRenderer.Instance.Viewpoint.position);
                    _renderProperties.SetVector(sp_CamForward, OceanRenderer.Instance.Viewpoint.forward);
                }

                _renderProperties.SetVector(sp_JitterDiameters_CurrentFrameWeights, new Vector4(Settings._jitterDiameterSoft, Settings._jitterDiameterHard, Settings._currentFrameWeightSoft, Settings._currentFrameWeightHard));
                _renderProperties.SetMatrix(sp_MainCameraProjectionMatrix, _cameraMain.projectionMatrix * _cameraMain.worldToCameraMatrix);
                _renderProperties.SetFloat(sp_SimDeltaTime, OceanRenderer.Instance.DeltaTimeDynamics);

                // compute which lod data we are sampling previous frame shadows from. if a scale change has happened this can be any lod up or down the chain.
                var srcDataIdx = lodIdx + ScaleDifferencePow2;
                srcDataIdx = Mathf.Clamp(srcDataIdx, 0, lt.LodCount - 1);
                _renderProperties.SetInt(sp_LD_SliceIndex, lodIdx);
                _renderProperties.SetInt(sp_LD_SliceIndex_Source, srcDataIdx);
                BindSourceData(_renderProperties, false);
                _renderProperties.SetTexture(sp_LD_TexArray_Target, _targets);

                BufCopyShadowMap.DispatchCompute(_updateShadowShader, krnl_UpdateShadow,
                                                 OceanRenderer.Instance.LodDataResolution / THREAD_GROUP_SIZE_X,
                                                 OceanRenderer.Instance.LodDataResolution / THREAD_GROUP_SIZE_Y,
                                                 1);
            }
        }
Beispiel #23
0
    private void Init()
    {
        objOutlineMat   = new Material(objOutlineShader);
        blurGrassMat    = new Material(blurGrassShader);
        objBlurGlassMat = new Material(objBlurGlassShader);
        uberMat         = new Material(uberShader);


        var camera = GetComponent <Camera>();

        //Shadow
        //---------------------
        CommandBuffer shadowCB = new CommandBuffer();

        shadowCB.name = "ShadowMapTex";
        //int shadowID = Shader.PropertyToID("_ShadowMapTex");
        shadowCB.SetShadowSamplingMode(BuiltinRenderTextureType.CurrentActive, ShadowSamplingMode.RawDepth);
        foreach (var renderer in shadowRenderers)
        {
            renderer.enabled = false;
            //如果不指定Pass 会绘制很多个跟shadow_caster无关的pass
            shadowCB.DrawRenderer(renderer, renderer.sharedMaterial, 0, 2);
        }

        //shadowCB.Blit(BuiltinRenderTextureType.CurrentActive, shadowID);
        mainLight.AddCommandBuffer(LightEvent.AfterShadowMap, shadowCB);

        //Outline
        //---------------------
        CommandBuffer outlineCB = new CommandBuffer();

        outlineCB.name = "Outline";

        outlineRT      = new RenderTexture(1920, 1080, 0, RenderTextureFormat.ARGB32);
        outlineRT.name = "outlineRT";
        outlineCB.SetRenderTarget(outlineRT);
        outlineCB.ClearRenderTarget(true, true, Color.clear);

        if (outlineRenderers != null && outlineRenderers.Length > 0)
        {
            foreach (var item in outlineRenderers)
            {
                outlineCB.DrawRenderer(item, objOutlineMat);
            }
        }

        camera.AddCommandBuffer(CameraEvent.BeforeImageEffects, outlineCB);


        //BlurGrass
        //---------------------
        CommandBuffer blurGrassCB = new CommandBuffer();

        blurGrassCB.name = "BlurGrass";

        blurRT      = new RenderTexture(1920, 1080, 0, RenderTextureFormat.ARGB32);
        blurRT.name = "blurRT";
        int blurTex0ID = Shader.PropertyToID("_BlurTex_0");
        int blurTex1ID = Shader.PropertyToID("_BlurTex_1");
        int blurTex2ID = Shader.PropertyToID("_BlurTex_2");
        int blurTex3ID = Shader.PropertyToID("_BlurTex_3");


        blurGrassCB.GetTemporaryRT(blurTex0ID, 1920 >> 1, 1080 >> 1);
        blurGrassCB.GetTemporaryRT(blurTex1ID, 1920 >> 2, 1080 >> 2);
        blurGrassCB.GetTemporaryRT(blurTex2ID, 1920 >> 2, 1080 >> 2);
        blurGrassCB.GetTemporaryRT(blurTex3ID, 1920, 1080);


        blurGrassCB.Blit(BuiltinRenderTextureType.CurrentActive, blurTex3ID);
        //降采样
        blurGrassCB.Blit(blurTex3ID, blurTex0ID, blurGrassMat, 0);
        blurGrassCB.Blit(blurTex0ID, blurTex1ID, blurGrassMat, 0);
        //高斯模糊
        blurGrassCB.Blit(blurTex1ID, blurTex2ID, blurGrassMat, 2);
        blurGrassCB.Blit(blurTex2ID, blurTex1ID, blurGrassMat, 3);
        //升采样
        blurGrassCB.Blit(blurTex1ID, blurTex0ID, blurGrassMat, 1);
        blurGrassCB.Blit(blurTex0ID, blurTex3ID, blurGrassMat, 1);

        blurGrassCB.SetGlobalTexture("_BlurTempTex", blurTex3ID);

        blurGrassCB.SetRenderTarget(blurRT);
        blurGrassCB.ClearRenderTarget(true, true, Color.clear);
        if (blurRenderers != null && blurRenderers.Length > 0)
        {
            foreach (var item in blurRenderers)
            {
                item.enabled = false;
                blurGrassCB.DrawRenderer(item, objBlurGlassMat);
            }
        }

        camera.AddCommandBuffer(CameraEvent.BeforeImageEffects, blurGrassCB);

        //uber
        //---------------------
        CommandBuffer uberCB = new CommandBuffer();

        uberCB.name = "Uber";
        uberCB.Blit(BuiltinRenderTextureType.CameraTarget, BuiltinRenderTextureType.CurrentActive, uberMat);
        uberCB.SetGlobalTexture(outlineCopyID, outlineRT);
        uberCB.SetGlobalTexture(blurCopyID, blurRT);
        camera.AddCommandBuffer(CameraEvent.BeforeImageEffects, uberCB);
    }
Beispiel #24
0
        public override void UpdateLodData()
        {
            if (!enabled)
            {
                return;
            }

            base.UpdateLodData();

            if (_mainLight != OceanRenderer.Instance._primaryLight)
            {
                if (_mainLight)
                {
                    _mainLight.RemoveCommandBuffer(LightEvent.BeforeScreenspaceMask, BufCopyShadowMap);
                    BufCopyShadowMap = null;
                    TextureArrayHelpers.ClearToBlack(_sources);
                    TextureArrayHelpers.ClearToBlack(_targets);
                }
                _mainLight = null;
            }

            if (!OceanRenderer.Instance._primaryLight)
            {
                if (!Settings._allowNullLight)
                {
                    Debug.LogWarning("Primary light must be specified on OceanRenderer script to enable shadows.", OceanRenderer.Instance);
                }
                return;
            }

            if (!_mainLight)
            {
                if (!StartInitLight())
                {
                    enabled = false;
                    return;
                }
            }

            if (BufCopyShadowMap == null && s_processData)
            {
                BufCopyShadowMap      = new CommandBuffer();
                BufCopyShadowMap.name = "Shadow data";
                _mainLight.AddCommandBuffer(LightEvent.BeforeScreenspaceMask, BufCopyShadowMap);
            }
            else if (!s_processData && BufCopyShadowMap != null)
            {
                _mainLight.RemoveCommandBuffer(LightEvent.BeforeScreenspaceMask, BufCopyShadowMap);
                BufCopyShadowMap = null;
            }

            if (!s_processData)
            {
                return;
            }

            Swap(ref _sources, ref _targets);

            BufCopyShadowMap.Clear();

            ValidateSourceData();

            // clear the shadow collection. it will be overwritten with shadow values IF the shadows render,
            // which only happens if there are (nontransparent) shadow receivers around. this is only reliable
            // in play mode, so don't do it in edit mode.
#if UNITY_EDITOR
            if (UnityEditor.EditorApplication.isPlaying)
#endif
            {
                TextureArrayHelpers.ClearToBlack(_targets);
            }

            // Cache the camera for further down.
            var camera = OceanRenderer.Instance.ViewCamera;
            if (camera == null)
            {
                // We want to return early after clear.
                return;
            }

            {
                // Run shadow update

                // It feels like quite a lot could be optimized out of the below. I think the same params are written repeatedly, and probably
                // a bunch of them are already available in existing ocean globals.

                _renderProperties.Initialise(BufCopyShadowMap, _updateShadowShader, krnl_UpdateShadow);

                _renderProperties.SetVector(sp_CamPos, camera.transform.position);
                _renderProperties.SetVector(sp_CamForward, camera.transform.forward);

                _renderProperties.SetVector(sp_JitterDiameters_CurrentFrameWeights, new Vector4(Settings._jitterDiameterSoft, Settings._jitterDiameterHard, Settings._currentFrameWeightSoft, Settings._currentFrameWeightHard));
                _renderProperties.SetMatrix(sp_MainCameraProjectionMatrix, camera.projectionMatrix * camera.worldToCameraMatrix);
                _renderProperties.SetFloat(sp_SimDeltaTime, OceanRenderer.Instance.DeltaTimeDynamics);

                _renderProperties.SetTexture(GetParamIdSampler(true), (Texture)_sources);

                _renderProperties.SetTexture(sp_LD_TexArray_Target, _targets);

                _renderProperties.SetBuffer(sp_cascadeDataSrc, OceanRenderer.Instance._bufCascadeDataSrc);

                var lt = OceanRenderer.Instance._lodTransform;
                for (var lodIdx = lt.LodCount - 1; lodIdx >= 0; lodIdx--)
                {
#if UNITY_EDITOR
                    lt._renderData[lodIdx].Validate(0, SimName);
#endif

                    _renderProperties.SetVector(sp_CenterPos, lt._renderData[lodIdx]._posSnapped);
                    var scale = OceanRenderer.Instance.CalcLodScale(lodIdx);
                    _renderProperties.SetVector(sp_Scale, new Vector3(scale, 1f, scale));

                    // compute which lod data we are sampling previous frame shadows from. if a scale change has happened this can be any lod up or down the chain.
                    var srcDataIdx = lodIdx + ScaleDifferencePow2;
                    srcDataIdx = Mathf.Clamp(srcDataIdx, 0, lt.LodCount - 1);
                    _renderProperties.SetInt(sp_LD_SliceIndex, lodIdx);
                    _renderProperties.SetInt(sp_LD_SliceIndex_Source, srcDataIdx);

                    BufCopyShadowMap.DispatchCompute(_updateShadowShader, krnl_UpdateShadow,
                                                     OceanRenderer.Instance.LodDataResolution / THREAD_GROUP_SIZE_X,
                                                     OceanRenderer.Instance.LodDataResolution / THREAD_GROUP_SIZE_Y,
                                                     1);
                }

#if ENABLE_VR && ENABLE_VR_MODULE
                // Disable for XR SPI otherwise input will not have correct world position.
                if (XRSettings.enabled && XRSettings.stereoRenderingMode == XRSettings.StereoRenderingMode.SinglePassInstanced)
                {
                    BufCopyShadowMap.DisableShaderKeyword("STEREO_INSTANCING_ON");
                }
#endif

                // Process registered inputs.
                for (var lodIdx = lt.LodCount - 1; lodIdx >= 0; lodIdx--)
                {
                    BufCopyShadowMap.SetRenderTarget(_targets, _targets.depthBuffer, 0, CubemapFace.Unknown, lodIdx);
                    SubmitDraws(lodIdx, BufCopyShadowMap);
                }

#if ENABLE_VR && ENABLE_VR_MODULE
                // Restore XR SPI as we cannot rely on remaining pipeline to do it for us.
                if (XRSettings.enabled && XRSettings.stereoRenderingMode == XRSettings.StereoRenderingMode.SinglePassInstanced)
                {
                    BufCopyShadowMap.EnableShaderKeyword("STEREO_INSTANCING_ON");
                }
#endif
            }

            // Set the target texture as to make sure we catch the 'pong' each frame
            Shader.SetGlobalTexture(GetParamIdSampler(), _targets);
        }
Beispiel #25
0
        /// <summary>
        /// Initializes the component (command buffers, registrations, events, managed members ...)
        /// </summary>
        private void Initialize()
        {
            _lightComponent    = GetComponent <Light>();
            _previousLightType = Type;

            if (CastsShadows)
            {
                Vector2Int shadowMapSize = new Vector2Int(0, 0);
                switch (Type)
                {
                case LightType.Directional:
                {
                    shadowMapSize = DirectionalLightsManager.ShadowMapSize;
                }
                break;

                case LightType.Spot:
                {
                    shadowMapSize = SpotLightsManager.shadowMapSize;
                }
                break;

                case LightType.Point:
                {
                    shadowMapSize = PointLightsManager.shadowMapSize;
                }
                break;
                }

                shadowMapRenderTexture = new RenderTexture(shadowMapSize.x, shadowMapSize.y, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
                shadowMapRenderTexture.Create();
                RenderTargetIdentifier shadowMapRenderTextureIdentifier = BuiltinRenderTextureType.CurrentActive;
                _copyShadowmapCommandBuffer = new CommandBuffer
                {
                    name = "Aura : Copy light's shadowmap"
                };
                _copyShadowmapCommandBuffer.SetShadowSamplingMode(shadowMapRenderTextureIdentifier, ShadowSamplingMode.RawDepth);
                _copyShadowmapCommandBuffer.Blit(shadowMapRenderTextureIdentifier, new RenderTargetIdentifier(shadowMapRenderTexture));
                _lightComponent.AddCommandBuffer(LightEvent.AfterShadowMap, _copyShadowmapCommandBuffer);

                switch (Type)
                {
                case LightType.Point:
                {
                    _storePointLightShadowMapMaterial = new Material(storePointLightShadowMapShader);
                }
                break;

                case LightType.Directional:
                {
                    if (shadowDataRenderTexture == null)
                    {
                        shadowDataRenderTexture = new RenderTexture(32, 1, 0, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear);
                    }

                    _storeShadowDataCommandBuffer = new CommandBuffer
                    {
                        name = "Aura : Store directional light's shadow data"
                    };

                    _storeShadowDataMaterial = new Material(storeShadowDataShader);

                    _lightComponent.AddCommandBuffer(LightEvent.BeforeScreenspaceMask, _storeShadowDataCommandBuffer);

                    _storeShadowDataCommandBuffer.Blit(null, new RenderTargetIdentifier(shadowDataRenderTexture), _storeShadowDataMaterial);

                    Aura.LightsManager.DirectionalLightsManager.OnCascadesCountChanged += DirectionalLightsManager_onCascadesCountChanged;
                }
                break;
                }
            }

            _previousUseShadow = CastsShadows;

            if (CastsCookie)
            {
                Vector2Int cookieMapSize = Vector2Int.zero;
                switch (Type)
                {
                case LightType.Directional:
                {
                    cookieMapSize = DirectionalLightsManager.cookieMapSize;
                }
                break;

                case LightType.Spot:
                {
                    cookieMapSize = SpotLightsManager.cookieMapSize;
                }
                break;

                case LightType.Point:
                {
                    cookieMapSize = PointLightsManager.cookieMapSize;
                }
                break;
                }

                cookieMapRenderTexture = new RenderTexture(cookieMapSize.x, cookieMapSize.y, 0, RenderTextureFormat.R8);

                switch (Type)
                {
                case LightType.Point:
                {
                    _storeCookieMapMaterial = new Material(storePointLightCookieMapShader);
                }
                break;

                default:
                {
                    _storeCookieMapMaterial = new Material(storeDirectionalSpotLightCookieMapShader);
                }
                break;
                }
            }

            _previousUseCookie = CastsCookie;

            Aura.LightsManager.Register(this, CastsShadows, CastsCookie);
            _isRegistered = true;

            Aura.OnPreCullEvent   += Aura_onPreCullEvent;
            Aura.OnPreRenderEvent += Aura_onPreRenderEvent;

            _isInitialized = true;
        }
        public override void UpdateLodData()
        {
            base.UpdateLodData();

            if (_mainLight != OceanRenderer.Instance._primaryLight)
            {
                if (_mainLight)
                {
                    _mainLight.RemoveCommandBuffer(LightEvent.BeforeScreenspaceMask, _bufCopyShadowMap);
                    _bufCopyShadowMap = null;
                    foreach (var source in _sources)
                    {
                        Graphics.Blit(Texture2D.blackTexture, source);
                    }
                    foreach (var target in _targets)
                    {
                        Graphics.Blit(Texture2D.blackTexture, target);
                    }
                }
                _mainLight = null;
            }

            if (!OceanRenderer.Instance._primaryLight)
            {
                if (!Settings._allowNullLight)
                {
                    Debug.LogWarning("Primary light must be specified on OceanRenderer script to enable shadows.", this);
                }
                return;
            }

            if (!_mainLight)
            {
                if (!StartInitLight())
                {
                    enabled = false;
                    return;
                }
            }

            if (_bufCopyShadowMap == null && s_processData)
            {
                _bufCopyShadowMap      = new CommandBuffer();
                _bufCopyShadowMap.name = "Shadow data";
                _mainLight.AddCommandBuffer(LightEvent.BeforeScreenspaceMask, _bufCopyShadowMap);
            }
            else if (!s_processData && _bufCopyShadowMap != null)
            {
                _mainLight.RemoveCommandBuffer(LightEvent.BeforeScreenspaceMask, _bufCopyShadowMap);
                _bufCopyShadowMap = null;
            }

            if (!s_processData)
            {
                return;
            }


            var lodCount = OceanRenderer.Instance.CurrentLodCount;

            for (var lodIdx = lodCount - 1; lodIdx >= 0; lodIdx--)
            {
                SwapRTs(ref _sources[lodIdx], ref _targets[lodIdx]);
            }

            _bufCopyShadowMap.Clear();

            for (var lodIdx = OceanRenderer.Instance.CurrentLodCount - 1; lodIdx >= 0; lodIdx--)
            {
                // clear the shadow collection. it will be overwritten with shadow values IF the shadows render,
                // which only happens if there are (nontransparent) shadow receivers around
                Graphics.Blit(Texture2D.blackTexture, _targets[lodIdx]);

                var lt = OceanRenderer.Instance._lods[lodIdx];

                lt._renderData.Validate(0, this);
                _renderMaterial[lodIdx].SetVector("_CenterPos", lt._renderData._posSnapped);
                _renderMaterial[lodIdx].SetVector("_Scale", lt.transform.lossyScale);
                _renderMaterial[lodIdx].SetVector("_CamPos", OceanRenderer.Instance.Viewpoint.position);
                _renderMaterial[lodIdx].SetVector("_CamForward", OceanRenderer.Instance.Viewpoint.forward);
                _renderMaterial[lodIdx].SetVector("_JitterDiameters_CurrentFrameWeights", new Vector4(Settings._jitterDiameterSoft, Settings._jitterDiameterHard, Settings._currentFrameWeightSoft, Settings._currentFrameWeightHard));
                _renderMaterial[lodIdx].SetMatrix("_MainCameraProjectionMatrix", _cameraMain.projectionMatrix * _cameraMain.worldToCameraMatrix);
                _renderMaterial[lodIdx].SetFloat("_SimDeltaTime", Time.deltaTime);

                // compute which lod data we are sampling previous frame shadows from. if a scale change has happened this can be any lod up or down the chain.
                var srcDataIdx = lt.LodIndex + ScaleDifferencePow2;
                srcDataIdx = Mathf.Clamp(srcDataIdx, 0, lt.LodCount - 1);
                // bind data to slot 0 - previous frame data
                BindSourceData(srcDataIdx, 0, _renderMaterial[lodIdx], false);
                _bufCopyShadowMap.Blit(Texture2D.blackTexture, _targets[lodIdx], _renderMaterial[lodIdx]);
            }
        }
Beispiel #27
0
        protected override void LateUpdate()
        {
            base.LateUpdate();

            if (_mainLight != OceanRenderer.Instance._primaryLight)
            {
                if (_mainLight)
                {
                    _mainLight.RemoveCommandBuffer(LightEvent.BeforeScreenspaceMask, _bufCopyShadowMap);
                    _bufCopyShadowMap = null;
                    for (int i = 0; i < _shadowData.Length; i++)
                    {
                        Graphics.Blit(Texture2D.blackTexture, _shadowData[i]);
                    }
                }
                _mainLight = null;
            }

            if (!OceanRenderer.Instance._primaryLight)
            {
                if (!Settings._allowNullLight)
                {
                    Debug.LogWarning("Primary light must be specified on OceanRenderer script to enable shadows.", this);
                }
                return;
            }

            if (!_mainLight)
            {
                if (!StartInitLight())
                {
                    enabled = false;
                    return;
                }
            }

            if (_bufCopyShadowMap == null && s_processData)
            {
                _bufCopyShadowMap      = new CommandBuffer();
                _bufCopyShadowMap.name = "Shadow data " + LodTransform.LodIndex;
                _mainLight.AddCommandBuffer(LightEvent.BeforeScreenspaceMask, _bufCopyShadowMap);
            }
            else if (!s_processData && _bufCopyShadowMap != null)
            {
                _mainLight.RemoveCommandBuffer(LightEvent.BeforeScreenspaceMask, _bufCopyShadowMap);
                _bufCopyShadowMap = null;
            }

            if (!s_processData)
            {
                return;
            }

            // clear the shadow collection. it will be overwritten with shadow values IF the shadows render,
            // which only happens if there are (nontransparent) shadow receivers around
            Graphics.Blit(Texture2D.blackTexture, _shadowData[_rtIndex]);

            _bufCopyShadowMap.Clear();

            LodTransform._renderData.Validate(0, this);
            _renderMaterial.SetVector("_CenterPos", LodTransform._renderData._posSnapped);
            _renderMaterial.SetVector("_Scale", transform.lossyScale);
            _renderMaterial.SetVector("_CamPos", OceanRenderer.Instance.Viewpoint.position);
            _renderMaterial.SetVector("_CamForward", OceanRenderer.Instance.Viewpoint.forward);
            _renderMaterial.SetVector("_JitterDiameters_CurrentFrameWeights",
                                      new Vector4(Settings._jitterDiameterSoft, Settings._jitterDiameterHard, Settings._currentFrameWeightSoft, Settings._currentFrameWeightHard));
            _renderMaterial.SetMatrix("_MainCameraProjectionMatrix", _cameraMain.projectionMatrix * _cameraMain.worldToCameraMatrix);
            _renderMaterial.SetFloat("_SimDeltaTime", Time.deltaTime);

            // compute which lod data we are sampling previous frame shadows from. if a scale change has happened this can be any lod up or down the chain.
            int srcDataIdx = LodTransform.LodIndex + _scaleDifferencePow2;

            srcDataIdx = Mathf.Clamp(srcDataIdx, 0, LodTransform.LodCount - 1);
            var lds = OceanRenderer.Instance._lodDataAnimWaves;

            // bind data to slot 0 - previous frame data
            lds[srcDataIdx].LDShadow.BindSourceData(0, _renderMaterial, false);
            _bufCopyShadowMap.Blit(Texture2D.blackTexture, _shadowData[_rtIndex], _renderMaterial);
        }
 public void AddCommandBuffer()
 {
     sunLight.AddCommandBuffer(LightEvent.AfterScreenspaceMask, m_Buffer);
     commandBufferAdded = true;
 }
 public void AddBuffers(Light lightSource)
 {
     lightSource.AddCommandBuffer(UnityEngine.Rendering.LightEvent.AfterShadowMap, m_occlusionCmdAfterShadows);
     lightSource.AddCommandBuffer(UnityEngine.Rendering.LightEvent.BeforeScreenspaceMask, m_occlusionCmdBeforeScreen);
 }
Beispiel #30
0
    void Start()
    {
        mipMat     = new Material(mipShader);
        samplerMat = new Material(samplerShader);
        cam        = Camera.main;

        cb_sm      = new CommandBuffer();
        cb_sm.name = "MZ Sample ShadowMap";
        mainLight.AddCommandBuffer(LightEvent.AfterShadowMap, cb_sm);

        RenderTargetIdentifier shadowmap = BuiltinRenderTextureType.CurrentActive;

        cb_sm.SetShadowSamplingMode(shadowmap, ShadowSamplingMode.RawDepth);
        cb_sm.Blit(shadowmap, new RenderTargetIdentifier(shadowMapCopy));
        cb_sm.Blit(shadowMapCopy, target, samplerMat);

        //cb_mip = new CommandBuffer();
        //cb_mip.name = "MZ Write Mip";
        //cam.AddCommandBuffer(CameraEvent.BeforeImageEffects, cb_mip);

        //hard coded for temp version
        //int[] temp_mip = new int[10];
        //int size = 1024;
        //test = new RenderTexture(size, size, 0, RenderTextureFormat.RGHalf);
        //test.filterMode = FilterMode.Point;
        //test.useMipMap = true;
        //test.autoGenerateMips = false;
        //test.Create();

        //RenderTargetIdentifier sourceID = new RenderTargetIdentifier(test);

        //for (int i = 0; i < 10; i++)
        //{
        //    temp_mip[i] = Shader.PropertyToID("Temp_target " + i.ToString());


        //    if (size == 0)
        //        size = 1;

        //    cb_mip.GetTemporaryRT(temp_mip[i], size, size, 0, FilterMode.Point,
        //        RenderTextureFormat.RGHalf, RenderTextureReadWrite.Linear);

        //    if (i == 0)
        //        cb_mip.Blit(shadowMapCopy, temp_mip[0], mipMat, 0);
        //    else
        //        cb_mip.Blit(temp_mip[i - 1], temp_mip[i], mipMat, 0);

        //    cb_mip.CopyTexture(temp_mip[i], 0, 0, sourceID, 0, i);
        //    size >>= 1;
        //    if (i >= 1)
        //        cb_mip.ReleaseTemporaryRT(temp_mip[i - 1]);
        //}

        //cb_mip.ReleaseTemporaryRT(temp_mip[9]);

        //cb_mip = new CommandBuffer();
        //cb_mip.name = "MZ Write Mip";
        //cam.AddCommandBuffer(CameraEvent.BeforeImageEffects, cb_mip);
        //cb_mip.Blit(sourceTex, minmaxmip);

        //for (int i = 1; i < 11; i++)
        //{
        //    cb_mip.SetRenderTarget(minmaxmip, i);
        //    mipMat.SetInt("_miplvl", i);
        //    cb_mip.Blit(sourceTex, BuiltinRenderTextureType.CurrentActive, mipMat, 0);
        //}
    }