示例#1
0
        /// <summary>
        /// Bind to a pixel shader for rendering.
        /// </summary>
        public void BindToMaterial(MaterialPropertyBlock mat)
        {
            //if (UseLuminance == LUMINANCE.NONE)
            //    mat.EnableKeyword("RADIANCE_API_ENABLED");
            //else
            //    mat.DisableKeyword("RADIANCE_API_ENABLED");

            //if (CombineScatteringTextures)
            //    mat.EnableKeyword("COMBINED_SCATTERING_TEXTURES");
            //else
            //    mat.DisableKeyword("COMBINED_SCATTERING_TEXTURES");

            mat.SetTexture("transmittance_texture", TransmittanceTexture);
            mat.SetTexture("scattering_texture", ScatteringTexture);
            mat.SetTexture("irradiance_texture", IrradianceTexture);

            if (CombineScatteringTextures)
            {
                mat.SetTexture("single_mie_scattering_texture", Texture2D.blackTexture);
            }
            else
            {
                mat.SetTexture("single_mie_scattering_texture", OptionalSingleMieScatteringTexture);
            }

            mat.SetInt("TRANSMITTANCE_TEXTURE_WIDTH", CONSTANTS.TRANSMITTANCE_WIDTH);
            mat.SetInt("TRANSMITTANCE_TEXTURE_HEIGHT", CONSTANTS.TRANSMITTANCE_HEIGHT);
            mat.SetInt("SCATTERING_TEXTURE_R_SIZE", CONSTANTS.SCATTERING_R);
            mat.SetInt("SCATTERING_TEXTURE_MU_SIZE", CONSTANTS.SCATTERING_MU);
            mat.SetInt("SCATTERING_TEXTURE_MU_S_SIZE", CONSTANTS.SCATTERING_MU_S);
            mat.SetInt("SCATTERING_TEXTURE_NU_SIZE", CONSTANTS.SCATTERING_NU);
            mat.SetInt("SCATTERING_TEXTURE_WIDTH", CONSTANTS.SCATTERING_WIDTH);
            mat.SetInt("SCATTERING_TEXTURE_HEIGHT", CONSTANTS.SCATTERING_HEIGHT);
            mat.SetInt("SCATTERING_TEXTURE_DEPTH", CONSTANTS.SCATTERING_DEPTH);
            mat.SetInt("IRRADIANCE_TEXTURE_WIDTH", CONSTANTS.IRRADIANCE_WIDTH);
            mat.SetInt("IRRADIANCE_TEXTURE_HEIGHT", CONSTANTS.IRRADIANCE_HEIGHT);

            mat.SetFloat("sun_angular_radius", (float)SunAngularRadius);
            mat.SetFloat("bottom_radius", (float)(BottomRadius / LengthUnitInMeters));
            mat.SetFloat("top_radius", (float)(TopRadius / LengthUnitInMeters));
            mat.SetFloat("mie_phase_function_g", (float)MiePhaseFunctionG);
            mat.SetFloat("mu_s_min", (float)Math.Cos(MaxSunZenithAngle));

            Vector3 skySpectralRadianceToLuminance, sunSpectralRadianceToLuminance;

            SkySunRadianceToLuminance(out skySpectralRadianceToLuminance, out sunSpectralRadianceToLuminance);

            mat.SetVector("SKY_SPECTRAL_RADIANCE_TO_LUMINANCE", skySpectralRadianceToLuminance);
            mat.SetVector("SUN_SPECTRAL_RADIANCE_TO_LUMINANCE", sunSpectralRadianceToLuminance);

            double[] lambdas = new double[] { kLambdaR, kLambdaG, kLambdaB };

            Vector3 solarIrradiance = ToVector(Wavelengths, SolarIrradiance, lambdas, 1.0);

            mat.SetVector("solar_irradiance", solarIrradiance);

            Vector3 rayleighScattering = ToVector(Wavelengths, RayleighScattering, lambdas, LengthUnitInMeters);

            mat.SetVector("rayleigh_scattering", rayleighScattering);

            Vector3 mieScattering = ToVector(Wavelengths, MieScattering, lambdas, LengthUnitInMeters);

            mat.SetVector("mie_scattering", mieScattering);
        }
示例#2
0
        public void RenderLightVolumes(CommandBuffer cmd, HDCamera hdCamera, CullingResults cullResults, LightingDebugSettings lightDebugSettings, RTHandleSystem.RTHandle finalRT)
        {
            using (new ProfilingSample(cmd, "Display Light Volumes"))
            {
                // Clear the buffers
                HDUtils.SetRenderTarget(cmd, hdCamera, m_ColorAccumulationBuffer, ClearFlag.Color, Color.black);
                HDUtils.SetRenderTarget(cmd, hdCamera, m_LightCountBuffer, ClearFlag.Color, Color.black);
                HDUtils.SetRenderTarget(cmd, hdCamera, m_DebugLightVolumesTexture, ClearFlag.Color, Color.black);

                // Set the render target array
                HDUtils.SetRenderTarget(cmd, hdCamera, m_RTIDs, m_DepthBuffer);

                // First of all let's do the regions for the light sources (we only support Punctual and Area)
                int numLights = cullResults.visibleLights.Length;
                for (int lightIdx = 0; lightIdx < numLights; ++lightIdx)
                {
                    // Let's build the light's bounding sphere matrix
                    Light currentLegacyLight = cullResults.visibleLights[lightIdx].light;
                    if (currentLegacyLight == null)
                    {
                        continue;
                    }
                    HDAdditionalLightData currentHDRLight = currentLegacyLight.GetComponent <HDAdditionalLightData>();
                    if (currentHDRLight == null)
                    {
                        continue;
                    }

                    Matrix4x4 positionMat = Matrix4x4.Translate(currentLegacyLight.transform.position);

                    if (currentLegacyLight.type == LightType.Point || currentLegacyLight.type == LightType.Area)
                    {
                        m_MaterialProperty.SetVector(_RangeShaderID, new Vector3(currentLegacyLight.range, currentLegacyLight.range, currentLegacyLight.range));
                        switch (currentHDRLight.lightTypeExtent)
                        {
                        case LightTypeExtent.Punctual:
                        {
                            m_MaterialProperty.SetColor(_ColorShaderID, new Color(0.0f, 0.5f, 0.0f, 1.0f));
                            m_MaterialProperty.SetVector(_OffsetShaderID, new Vector3(0, 0, 0));
                            cmd.DrawMesh(DebugShapes.instance.RequestSphereMesh(), positionMat, m_DebugLightVolumeMaterial, 0, 0, m_MaterialProperty);
                        }
                        break;

                        case LightTypeExtent.Rectangle:
                        {
                            m_MaterialProperty.SetColor(_ColorShaderID, new Color(0.0f, 1.0f, 1.0f, 1.0f));
                            m_MaterialProperty.SetVector(_OffsetShaderID, new Vector3(0, 0, 0));
                            cmd.DrawMesh(DebugShapes.instance.RequestSphereMesh(), positionMat, m_DebugLightVolumeMaterial, 0, 0, m_MaterialProperty);
                        }
                        break;

                        case LightTypeExtent.Tube:
                        {
                            m_MaterialProperty.SetColor(_ColorShaderID, new Color(1.0f, 0.0f, 0.5f, 1.0f));
                            m_MaterialProperty.SetVector(_OffsetShaderID, new Vector3(0, 0, 0));
                            cmd.DrawMesh(DebugShapes.instance.RequestSphereMesh(), positionMat, m_DebugLightVolumeMaterial, 0, 0, m_MaterialProperty);
                        }
                        break;

                        default:
                            break;
                        }
                    }
                    else if (currentLegacyLight.type == LightType.Spot)
                    {
                        if (currentHDRLight.spotLightShape == SpotLightShape.Cone)
                        {
                            float bottomRadius = Mathf.Tan(currentLegacyLight.spotAngle * Mathf.PI / 360.0f) * currentLegacyLight.range;
                            m_MaterialProperty.SetColor(_ColorShaderID, new Color(1.0f, 0.5f, 0.0f, 1.0f));
                            m_MaterialProperty.SetVector(_RangeShaderID, new Vector3(bottomRadius, bottomRadius, currentLegacyLight.range));
                            m_MaterialProperty.SetVector(_OffsetShaderID, new Vector3(0, 0, 0));
                            cmd.DrawMesh(DebugShapes.instance.RequestConeMesh(), currentLegacyLight.gameObject.transform.localToWorldMatrix, m_DebugLightVolumeMaterial, 0, 0, m_MaterialProperty);
                        }
                        else if (currentHDRLight.spotLightShape == SpotLightShape.Box)
                        {
                            m_MaterialProperty.SetColor(_ColorShaderID, new Color(1.0f, 0.5f, 0.0f, 1.0f));
                            m_MaterialProperty.SetVector(_RangeShaderID, new Vector3(currentHDRLight.shapeWidth, currentHDRLight.shapeHeight, currentLegacyLight.range));
                            m_MaterialProperty.SetVector(_OffsetShaderID, new Vector3(0, 0, currentLegacyLight.range / 2.0f));
                            cmd.DrawMesh(DebugShapes.instance.RequestBoxMesh(), currentLegacyLight.gameObject.transform.localToWorldMatrix, m_DebugLightVolumeMaterial, 0, 0, m_MaterialProperty);
                        }
                        else if (currentHDRLight.spotLightShape == SpotLightShape.Pyramid)
                        {
                            float bottomWidth = Mathf.Tan(currentLegacyLight.spotAngle * Mathf.PI / 360.0f) * currentLegacyLight.range;
                            m_MaterialProperty.SetColor(_ColorShaderID, new Color(1.0f, 0.5f, 0.0f, 1.0f));
                            m_MaterialProperty.SetVector(_RangeShaderID, new Vector3(currentHDRLight.aspectRatio * bottomWidth * 2, bottomWidth * 2, currentLegacyLight.range));
                            m_MaterialProperty.SetVector(_OffsetShaderID, new Vector3(0, 0, 0));
                            cmd.DrawMesh(DebugShapes.instance.RequestPyramidMesh(), currentLegacyLight.gameObject.transform.localToWorldMatrix, m_DebugLightVolumeMaterial, 0, 0, m_MaterialProperty);
                        }
                    }
                }

                // Now let's do the same but for reflection probes
                int numProbes = cullResults.visibleReflectionProbes.Length;
                for (int probeIdx = 0; probeIdx < numProbes; ++probeIdx)
                {
                    // Let's build the light's bounding sphere matrix
                    ReflectionProbe            currentLegacyProbe = cullResults.visibleReflectionProbes[probeIdx].reflectionProbe;
                    HDAdditionalReflectionData currentHDProbe     = currentLegacyProbe.GetComponent <HDAdditionalReflectionData>();

                    if (!currentHDProbe)
                    {
                        continue;
                    }

                    MaterialPropertyBlock m_MaterialProperty = new MaterialPropertyBlock();
                    Mesh targetMesh = null;
                    if (currentHDProbe.influenceVolume.shape == InfluenceShape.Sphere)
                    {
                        m_MaterialProperty.SetVector(_RangeShaderID, new Vector3(currentHDProbe.influenceVolume.sphereRadius, currentHDProbe.influenceVolume.sphereRadius, currentHDProbe.influenceVolume.sphereRadius));
                        targetMesh = DebugShapes.instance.RequestSphereMesh();
                    }
                    else
                    {
                        m_MaterialProperty.SetVector(_RangeShaderID, new Vector3(currentHDProbe.influenceVolume.boxSize.x, currentHDProbe.influenceVolume.boxSize.y, currentHDProbe.influenceVolume.boxSize.z));
                        targetMesh = DebugShapes.instance.RequestBoxMesh();
                    }

                    m_MaterialProperty.SetColor(_ColorShaderID, new Color(1.0f, 1.0f, 0.0f, 1.0f));
                    m_MaterialProperty.SetVector(_OffsetShaderID, new Vector3(0, 0, 0));
                    Matrix4x4 positionMat = Matrix4x4.Translate(currentLegacyProbe.transform.position);
                    cmd.DrawMesh(targetMesh, positionMat, m_DebugLightVolumeMaterial, 0, 0, m_MaterialProperty);
                }

                // Define which kernel to use based on the lightloop options
                int targetKernel = lightDebugSettings.lightVolumeDebugByCategory == LightLoop.LightVolumeDebug.ColorAndEdge ? m_DebugLightVolumeColorsKernel : m_DebugLightVolumeGradientKernel;

                // Set the input params for the compute
                cmd.SetComputeTextureParam(m_DebugLightVolumeCompute, targetKernel, _DebugLightCountBufferShaderID, m_LightCountBuffer);
                cmd.SetComputeTextureParam(m_DebugLightVolumeCompute, targetKernel, _DebugColorAccumulationBufferShaderID, m_ColorAccumulationBuffer);
                cmd.SetComputeTextureParam(m_DebugLightVolumeCompute, targetKernel, _DebugLightVolumesTextureShaderID, m_DebugLightVolumesTexture);
                cmd.SetComputeTextureParam(m_DebugLightVolumeCompute, targetKernel, _ColorGradientTextureShaderID, m_ColorGradientTexture);
                cmd.SetComputeIntParam(m_DebugLightVolumeCompute, _MaxDebugLightCountShaderID, (int)lightDebugSettings.maxDebugLightCount);

                // Texture dimensions
                int texWidth  = hdCamera.actualWidth;  // m_ColorAccumulationBuffer.rt.width;
                int texHeight = hdCamera.actualHeight; // m_ColorAccumulationBuffer.rt.width;


                // Dispatch the compute
                int lightVolumesTileSize = 8;
                int numTilesX            = (texWidth + (lightVolumesTileSize - 1)) / lightVolumesTileSize;
                int numTilesY            = (texHeight + (lightVolumesTileSize - 1)) / lightVolumesTileSize;
                cmd.DispatchCompute(m_DebugLightVolumeCompute, targetKernel, numTilesX, numTilesY, hdCamera.computePassCount);

                // Blit this into the camera target
                HDUtils.SetRenderTarget(cmd, hdCamera, finalRT);
                m_MaterialProperty.SetTexture(HDShaderIDs._BlitTexture, m_DebugLightVolumesTexture);
                cmd.DrawProcedural(Matrix4x4.identity, m_DebugLightVolumeMaterial, 1, MeshTopology.Triangles, 3, 1, m_MaterialProperty);
            }
        }
示例#3
0
        private void DrawNextPaint()
        {
            if (P3dPaintMaterial.CachedInstances.Count > 0)
            {
                if (paintIndex >= P3dPaintMaterial.CachedInstances.Count)
                {
                    paintIndex = 0;
                }

                var paint = P3dPaintMaterial.CachedInstances[paintIndex++];

                DestroyImmediate(paint.Thumbnail);
                paint.Thumbnail = null;

                if (paint != null && paint.Thumbnail == null && paint.Material != null)
                {
                    var tempTextures = new List <RenderTexture>();

                    if (paintProperties == null)
                    {
                        paintProperties = new MaterialPropertyBlock();
                    }
                    else
                    {
                        paintProperties.Clear();
                    }

                    if (paint.Template != null)
                    {
                        foreach (var slot in paint.Template.Slots)
                        {
                            var slotR = paint.GetSlot(slot.WriteR.SourceGroup);
                            var slotG = paint.GetSlot(slot.WriteG.SourceGroup);
                            var slotB = paint.GetSlot(slot.WriteB.SourceGroup);
                            var slotA = paint.GetSlot(slot.WriteA.SourceGroup);

                            if (slotR != null || slotG != null || slotB != null || slotA != null)
                            {
                                var tempTexture = P3dHelper.GetRenderTexture(new RenderTextureDescriptor(1024, 1024, RenderTextureFormat.ARGB32, 0));

                                tempTextures.Add(tempTexture);

                                var textureR = P3dHelper.GetRenderTexture(tempTexture.descriptor);
                                var textureG = P3dHelper.GetRenderTexture(tempTexture.descriptor);
                                var textureB = P3dHelper.GetRenderTexture(tempTexture.descriptor);
                                var textureA = P3dHelper.GetRenderTexture(tempTexture.descriptor);

                                WriteThumbnailTex(textureR, slotR, slot.WriteR);
                                WriteThumbnailTex(textureG, slotG, slot.WriteG);
                                WriteThumbnailTex(textureB, slotB, slot.WriteB);
                                WriteThumbnailTex(textureA, slotA, slot.WriteA);

                                var channelR = P3dHelper.IndexToVector((int)slot.WriteR.SourceChannel);
                                var channelG = P3dHelper.IndexToVector((int)slot.WriteG.SourceChannel);
                                var channelB = P3dHelper.IndexToVector((int)slot.WriteB.SourceChannel);
                                var channelA = P3dHelper.IndexToVector((int)slot.WriteA.SourceChannel);

                                P3dPaintReplaceChannels.Blit(tempTexture, textureR, textureG, textureB, textureA, channelR, channelG, channelB, channelA);

                                P3dHelper.ReleaseRenderTexture(textureR);
                                P3dHelper.ReleaseRenderTexture(textureG);
                                P3dHelper.ReleaseRenderTexture(textureB);
                                P3dHelper.ReleaseRenderTexture(textureA);

                                paintProperties.SetTexture(slot.Name, tempTexture);
                            }
                        }
                    }

                    BeginPreview(thumbnailUtil, new Rect(0, 0, settings.ThumbnailSize, settings.ThumbnailSize));

                    var probeAnchor = default(Transform);
                    var probeExists = false;

                    if (settings.Environment != null)
                    {
                        probeAnchor = settings.Environment.transform;
                        probeExists = true;
                    }

                    switch (paint.Style)
                    {
                    case P3dPaintMaterial.StyleType.Seamless:
                    {
                        thumbnailUtil.DrawMesh(P3dHelper.GetSphereMesh(), Matrix4x4.identity, paint.Material, 0, paintProperties, probeAnchor, probeExists);
                    }
                    break;

                    case P3dPaintMaterial.StyleType.Decal:
                    {
                        thumbnailUtil.DrawMesh(P3dHelper.GetQuadMesh(), Matrix4x4.identity, paint.Material, 0, paintProperties, probeAnchor, probeExists);
                    }
                    break;
                    }

                    paint.Thumbnail = P3dHelper.GetReadableCopy(EndPreview(thumbnailUtil));

                    foreach (var tempTexture in tempTextures)
                    {
                        P3dHelper.ReleaseRenderTexture(tempTexture);
                    }
                }
            }
        }
示例#4
0
 public void GenerateMaterialProps(MaterialPropertyBlock props)
 {
     props.SetTexture("_MainTex", texture);
     props.SetVector("_MainTex_UV", uv);
 }
 // Token: 0x06002DFA RID: 11770 RVA: 0x000E180D File Offset: 0x000DFC0D
 public static MaterialPropertyBlock Property(this MaterialPropertyBlock m, string name, Texture texture)
 {
     m.SetTexture(name, texture);
     return(m);
 }
示例#6
0
 void Damage()
 {
     health--;
     propertyBlock.SetTexture("_Emission", emissionMaps[health - 1].texture);
     sr.SetPropertyBlock(propertyBlock);
 }
示例#7
0
 public void SetValueOnMaterialPropertyBlock(MaterialPropertyBlock mat)
 {
     if ((propType == PropertyType.Texture2D || propType == PropertyType.Texture2DArray || propType == PropertyType.Texture3D))
     {
         if (m_ClassData.textureValue == null)
         {
             // there's no way to set the texture back to NULL
             // and no way to delete the property either
             // so instead we set the value to what we know the default will be
             // (all textures in ShaderGraph default to white)
             mat.SetTexture(name, Texture2D.whiteTexture);
         }
         else
         {
             mat.SetTexture(name, m_ClassData.textureValue);
         }
     }
     else if (propType == PropertyType.Cubemap)
     {
         if (m_ClassData.cubemapValue == null)
         {
             // there's no way to set the texture back to NULL
             // and no way to delete the property either
             // so instead we set the value to what we know the default will be
             // (all textures in ShaderGraph default to white)
             // there's no Cubemap.whiteTexture, but this seems to work
             mat.SetTexture(name, Texture2D.whiteTexture);
         }
         else
         {
             mat.SetTexture(name, m_ClassData.cubemapValue);
         }
     }
     else if (propType == PropertyType.Color)
     {
         mat.SetColor(name, m_StructData.colorValue);
     }
     else if (propType == PropertyType.Vector2 || propType == PropertyType.Vector3 || propType == PropertyType.Vector4)
     {
         mat.SetVector(name, m_StructData.vector4Value);
     }
     else if (propType == PropertyType.Float)
     {
         mat.SetFloat(name, m_StructData.floatValue);
     }
     else if (propType == PropertyType.Boolean)
     {
         mat.SetFloat(name, m_StructData.booleanValue ? 1 : 0);
     }
     else if (propType == PropertyType.Matrix2 || propType == PropertyType.Matrix3 || propType == PropertyType.Matrix4)
     {
         mat.SetMatrix(name, m_StructData.matrixValue);
     }
     else if (propType == PropertyType.Gradient)
     {
         mat.SetFloat(string.Format("{0}_Type", name), (int)m_ClassData.gradientValue.mode);
         mat.SetFloat(string.Format("{0}_ColorsLength", name), m_ClassData.gradientValue.colorKeys.Length);
         mat.SetFloat(string.Format("{0}_AlphasLength", name), m_ClassData.gradientValue.alphaKeys.Length);
         for (int i = 0; i < 8; i++)
         {
             mat.SetVector(string.Format("{0}_ColorKey{1}", name, i), i < m_ClassData.gradientValue.colorKeys.Length ? GradientUtil.ColorKeyToVector(m_ClassData.gradientValue.colorKeys[i]) : Vector4.zero);
         }
         for (int i = 0; i < 8; i++)
         {
             mat.SetVector(string.Format("{0}_AlphaKey{1}", name, i), i < m_ClassData.gradientValue.alphaKeys.Length ? GradientUtil.AlphaKeyToVector(m_ClassData.gradientValue.alphaKeys[i]) : Vector2.zero);
         }
     }
     else if (propType == PropertyType.VirtualTexture)
     {
         // virtual texture assignments are not supported via the material property block, we must assign them to the materials
     }
 }
示例#8
0
        // Called when visible to a camera
        void OnWillRenderObject()
        {
            // Depth texture is used by ocean shader for transparency/depth fog, and for fading out foam at shoreline.
            Camera.current.depthTextureMode |= DepthTextureMode.Depth;

            // per instance data

            if (_mpb == null)
            {
                _mpb = new MaterialPropertyBlock();
            }
            _rend.GetPropertyBlock(_mpb);

            // blend LOD 0 shape in/out to avoid pop, if the ocean might scale up later (it is smaller than its maximum scale)
            bool  needToBlendOutShape = _lodIndex == 0 && OceanRenderer.Instance.ScaleCouldIncrease;
            float meshScaleLerp       = needToBlendOutShape ? OceanRenderer.Instance.ViewerAltitudeLevelAlpha : 0f;

            // blend furthest normals scale in/out to avoid pop, if scale could reduce
            bool  needToBlendOutNormals = _lodIndex == _totalLodCount - 1 && OceanRenderer.Instance.ScaleCouldDecrease;
            float farNormalsWeight      = needToBlendOutNormals ? OceanRenderer.Instance.ViewerAltitudeLevelAlpha : 1f;

            _mpb.SetVector("_InstanceData", new Vector4(meshScaleLerp, farNormalsWeight, _lodIndex));

            // geometry data
            // compute grid size of geometry. take the long way to get there - make sure we land exactly on a power of two
            // and not inherit any of the lossy-ness from lossyScale.
            float squareSize         = Mathf.Pow(2f, Mathf.Round(Mathf.Log(transform.lossyScale.x) / Mathf.Log(2f))) / _baseVertDensity;
            float mul                = 1.875f; // fudge 1
            float pow                = 1.4f;   // fudge 2
            float normalScrollSpeed0 = Mathf.Pow(Mathf.Log(1f + 2f * squareSize) * mul, pow);
            float normalScrollSpeed1 = Mathf.Pow(Mathf.Log(1f + 4f * squareSize) * mul, pow);

            _mpb.SetVector("_GeomData", new Vector3(squareSize, normalScrollSpeed0, normalScrollSpeed1));

            // assign lod data to ocean shader
            var ldaws     = OceanRenderer.Instance._lodDataAnimWaves;
            var ldsds     = OceanRenderer.Instance._lodDataSeaDepths;
            var ldfoam    = OceanRenderer.Instance._lodDataFoam;
            var ldflow    = OceanRenderer.Instance._lodDataFlow;
            var ldshadows = OceanRenderer.Instance._lodDataShadow;

            ldaws.BindResultData(_lodIndex, 0, _mpb);
            if (OceanRenderer.Instance._createFlowSim)
            {
                ldflow.BindResultData(_lodIndex, 0, _mpb);
            }
            if (OceanRenderer.Instance._createFoamSim)
            {
                ldfoam.BindResultData(_lodIndex, 0, _mpb);
            }
            if (OceanRenderer.Instance._createSeaFloorDepthData)
            {
                ldsds.BindResultData(_lodIndex, 0, _mpb);
            }
            if (OceanRenderer.Instance._createShadowData)
            {
                ldshadows.BindResultData(_lodIndex, 0, _mpb);
            }

            if (_lodIndex + 1 < OceanRenderer.Instance.CurrentLodCount)
            {
                ldaws.BindResultData(_lodIndex + 1, 1, _mpb);
                if (OceanRenderer.Instance._createFlowSim)
                {
                    ldflow.BindResultData(_lodIndex + 1, 1, _mpb);
                }
                if (OceanRenderer.Instance._createFoamSim)
                {
                    ldfoam.BindResultData(_lodIndex + 1, 1, _mpb);
                }
                if (OceanRenderer.Instance._createSeaFloorDepthData)
                {
                    ldsds.BindResultData(_lodIndex + 1, 1, _mpb);
                }
                if (OceanRenderer.Instance._createShadowData)
                {
                    ldshadows.BindResultData(_lodIndex + 1, 1, _mpb);
                }
            }

            if (OceanRenderer.Instance.PlanarReflection && OceanRenderer.Instance.PlanarReflection.ReflectionTexture)
            {
                _mpb.SetTexture(_reflectionTexId, OceanRenderer.Instance.PlanarReflection.ReflectionTexture);
            }
            else
            {
                _mpb.SetTexture(_reflectionTexId, Texture2D.blackTexture);
            }

            // Hack - due to SV_IsFrontFace occasionally coming through as true for backfaces,
            // add a param here that forces ocean to be in undrwater state. I think the root
            // cause here might be imprecision or numerical issues at ocean tile boundaries, although
            // i'm not sure why cracks are not visible in this case.
            float heightOffset = OceanRenderer.Instance.ViewerHeightAboveWater;

            _mpb.SetFloat("_ForceUnderwater", heightOffset < -2f ? 1f : 0f);

            _rend.SetPropertyBlock(_mpb);

            if (_drawRenderBounds)
            {
                DebugDrawRendererBounds(_rend);
            }
        }
示例#9
0
    void SetShaderPropertiesBlock(MaterialPropertyBlock propertyBlock)
    {
        propertyBlock.SetVector(_idNoiseOffset, _angle);
        propertyBlock.SetVector(_idMinBounds, _minBounds);
        propertyBlock.SetVector(_idMaxBounds, _maxBounds);
        propertyBlock.SetMatrix(_idProjection, _projectionMatrixCached);
        propertyBlock.SetMatrix(_idViewWorldLight, _viewWorldLight);
        propertyBlock.SetMatrix(_idLocalRotation, _localRotation);
        propertyBlock.SetMatrix(_idRotation, _rotation);
        propertyBlock.SetColor(_idColorTint, colorTint);
        propertyBlock.SetFloat(_idLightMultiplier, lightMultiplier);
        propertyBlock.SetVector("_WorldPos", (CachedTransform.position + CachedTransform.forward) * worldScrollAmount);

        var lightMaterial = LightMaterial;

        if (useSoftBlend)
        {
            lightMaterial.EnableKeyword("_SOFTBLEND_ON");
        }
        else
        {
            lightMaterial.DisableKeyword("_SOFTBLEND_ON");
        }

        if (useDithering)
        {
            propertyBlock.SetFloat(_idJitterAmount, ditherAmount);
            propertyBlock.SetTexture(_idDitherTex, DitherTexture);
            lightMaterial.EnableKeyword("_DITHER_ON");
        }
        else
        {
            lightMaterial.DisableKeyword("_DITHER_ON");
        }

        if (useCurves)
        {
            propertyBlock.SetTexture(_idFallOffTex, FallOffTexture);
            lightMaterial.EnableKeyword("_CURVE_ON");
        }
        else
        {
            lightMaterial.DisableKeyword("_CURVE_ON");
        }

        switch (lightType)
        {
        case LightTypes.Point:
        case LightTypes.Spot:
        case LightTypes.Orthographic:
            propertyBlock.SetFloat(_idSpotExponent, spotExponent);
            propertyBlock.SetFloat(_idConstantAttenuation, constantAttenuation);
            propertyBlock.SetFloat(_idLinearAttenuation, linearAttenuation);
            propertyBlock.SetFloat(_idQuadraticAttenuation, quadraticAttenuation);
            break;

        case LightTypes.Area:
            Vector4 p = volumeTextureOffset;
            p.w = volumeTextureScale;
            propertyBlock.SetVector(_idVolumeOffset, p);
            propertyBlock.SetFloat(_idVolumeParams, shapeValue);
            switch (volumeShape)
            {
            case VolumeShape.Cube:
                lightMaterial.EnableKeyword("_SHAPE_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_SPHERE");
                lightMaterial.DisableKeyword("_SHAPE_ROUNDED_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_CYLINDER");
                break;

            case VolumeShape.Sphere:
                lightMaterial.EnableKeyword("_SHAPE_SPHERE");
                lightMaterial.DisableKeyword("_SHAPE_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_ROUNDED_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_CYLINDER");
                break;

            case VolumeShape.RoundedCube:
                lightMaterial.EnableKeyword("_SHAPE_ROUNDED_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_SPHERE");
                lightMaterial.DisableKeyword("_SHAPE_CYLINDER");
                break;

            case VolumeShape.Cylinder:
                lightMaterial.EnableKeyword("_SHAPE_CYLINDER");
                lightMaterial.DisableKeyword("_SHAPE_CUBE");
                lightMaterial.DisableKeyword("_SHAPE_SPHERE");
                lightMaterial.DisableKeyword("_SHAPE_ROUNDED_CUBE");
                break;
            }
            break;
        }

        switch (lightType)
        {
        case LightTypes.Area:
            propertyBlock.SetTexture("_MainTex", areaVolume != null ? areaVolume : EmptyTexture3D);
            break;

        case LightTypes.Point:
            propertyBlock.SetTexture("_LightColorEmission", pointEmission != null ? pointEmission : EmptyCubemap);
            propertyBlock.SetTexture("_NoiseTex", pointNoise != null ? pointNoise : EmptyCubemap);
            propertyBlock.SetTexture("_ShadowTexture", pointShadow != null ? pointShadow : EmptyCubemap);
            break;

        case LightTypes.Spot:
        case LightTypes.Orthographic:
            propertyBlock.SetTexture("_LightColorEmission", spotEmission != null ? spotEmission : EmptyTexture2D);
            propertyBlock.SetTexture("_NoiseTex", spotNoise != null ? spotNoise : EmptyTexture2D);
            propertyBlock.SetTexture("_ShadowTexture", spotShadow != null ? spotShadow : EmptyTexture2D);
            break;
        }

        var shouldUseCustomShadowMap = false;

        cam.targetTexture = null;
        switch (shadowMode)
        {
        case ShadowMode.Realtime:
            if (_depthTexture == null)
            {
                CreateDepthTexture(lightType);
            }
            propertyBlock.SetTexture("_ShadowTexture", _depthTexture);
            lightMaterial.EnableKeyword("_SHADOW_ON");
            shouldUseCustomShadowMap = renderFullShadows;
            break;

        case ShadowMode.Baked:
            lightMaterial.EnableKeyword("_SHADOW_ON");
            shouldUseCustomShadowMap = false;
            break;

        case ShadowMode.None:
            lightMaterial.DisableKeyword("_SHADOW_ON");
            shouldUseCustomShadowMap = false;
            break;
        }

        if (shouldUseCustomShadowMap)
        {
            lightMaterial.EnableKeyword("_SHADOW_EXP");
        }
        else
        {
            lightMaterial.DisableKeyword("_SHADOW_EXP");
        }

        float far  = cam.farClipPlane;
        float near = cam.nearClipPlane;
        float fov  = cam.fieldOfView;

        far  = spotRange;
        near = Mathf.Max(0.01f, spotNear);
        fov  = spotAngle;

        cam.farClipPlane = far;

        if (lightType == LightTypes.Point || lightType == LightTypes.Area)
        {
            near = -pointLightRadius;
            far  = pointLightRadius;
        }

        switch ((lightType))
        {
        case LightTypes.Point:
        case LightTypes.Area:
            propertyBlock.SetVector(_idLightParams, new Vector4(near, far, aspect, pointLightRadius));
            break;

        case LightTypes.Orthographic:
            propertyBlock.SetVector(_idLightParams, new Vector4(near, far, aspect, orthoSize));
            break;

        default:
            propertyBlock.SetVector(_idLightParams, new Vector4(near, far, aspect, fov * 0.5f * Mathf.Deg2Rad));
            break;
        }
    }
示例#10
0
 public override void SetSprite(Sprite sprite)
 {
     _renderer.GetPropertyBlock(_propBlock);
     _propBlock.SetTexture("_ItemTex", sprite.texture);
     _renderer.SetPropertyBlock(_propBlock);
 }
示例#11
0
        private void RenderMasks(Camera camera, WaterCamera waterCamera, MaterialPropertyBlock propertyBlock)
        {
            List <WaterVolumeSubtract> subtractiveVolumesDirect = this._Water.Volume.GetSubtractiveVolumesDirect();
            List <WaterVolumeAdd>      volumesDirect            = this._Water.Volume.GetVolumesDirect();

            if (waterCamera == null || !waterCamera.RenderVolumes || (subtractiveVolumesDirect.Count == 0 && volumesDirect.Count == 0 && this._Masks.Count == 0))
            {
                this.ReleaseTemporaryBuffers();
                return;
            }
            int    waterTempLayer      = WaterProjectSettings.Instance.WaterTempLayer;
            int    waterCollidersLayer = WaterProjectSettings.Instance.WaterCollidersLayer;
            Camera effectsCamera       = waterCamera.EffectsCamera;

            if (effectsCamera == null)
            {
                this.ReleaseTemporaryBuffers();
                return;
            }
            bool flag  = false;
            bool flag2 = false;
            bool flag3 = false;

            this.OnSharedSubtractiveMaskRender(ref flag, ref flag2, ref flag3);
            effectsCamera.CopyFrom(camera);
            effectsCamera.enabled = false;
            effectsCamera.GetComponent <WaterCamera>().enabled = false;
            effectsCamera.renderingPath    = RenderingPath.Forward;
            effectsCamera.depthTextureMode = DepthTextureMode.None;
            effectsCamera.cullingMask      = 1 << waterTempLayer;
            if (subtractiveVolumesDirect.Count != 0)
            {
                if (this._SubtractiveMaskTexture == null)
                {
                    this._SubtractiveMaskTexture = RenderTexture.GetTemporary(camera.pixelWidth, camera.pixelHeight, 24, (!SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBFloat)) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear, 1);
                }
                Graphics.SetRenderTarget(this._SubtractiveMaskTexture);
                int count = subtractiveVolumesDirect.Count;
                for (int i = 0; i < count; i++)
                {
                    subtractiveVolumesDirect[i].SetLayer(waterTempLayer);
                }
                TemporaryRenderTexture temporary = RenderTexturesCache.GetTemporary(camera.pixelWidth, camera.pixelHeight, 24, (!SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBFloat)) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGBFloat, true, false, false);
                effectsCamera.clearFlags      = CameraClearFlags.Color;
                effectsCamera.backgroundColor = new Color(0f, 0f, 0.5f, 0f);
                effectsCamera.targetTexture   = temporary;
                effectsCamera.RenderWithShader(this._VolumeFrontShader, "CustomType");
                GL.Clear(true, true, new Color(0f, 0f, 0f, 0f), 0f);
                Shader.SetGlobalTexture("_VolumesFrontDepth", temporary);
                effectsCamera.clearFlags    = CameraClearFlags.Nothing;
                effectsCamera.targetTexture = this._SubtractiveMaskTexture;
                effectsCamera.RenderWithShader(this._VolumeBackShader, "CustomType");
                temporary.Dispose();
                for (int j = 0; j < count; j++)
                {
                    subtractiveVolumesDirect[j].SetLayer(waterCollidersLayer);
                }
                propertyBlock.SetTexture(ShaderVariables.SubtractiveMask, this._SubtractiveMaskTexture);
            }
            if (volumesDirect.Count != 0)
            {
                this.OnSharedMaskAdditiveRender();
                if (this._AdditiveMaskTexture == null)
                {
                    this._AdditiveMaskTexture = RenderTexture.GetTemporary(camera.pixelWidth, camera.pixelHeight, 16, (!SystemInfo.SupportsRenderTextureFormat(RenderTextureFormat.ARGBFloat)) ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear, 1);
                }
                Graphics.SetRenderTarget(this._AdditiveMaskTexture);
                GL.Clear(true, true, new Color(0f, 0f, 0f, 0f));
                int count2 = volumesDirect.Count;
                for (int k = 0; k < count2; k++)
                {
                    volumesDirect[k].SetLayer(waterTempLayer);
                    volumesDirect[k].EnableRenderers(false);
                }
                effectsCamera.clearFlags    = CameraClearFlags.Nothing;
                effectsCamera.targetTexture = this._AdditiveMaskTexture;
                effectsCamera.RenderWithShader((!waterCamera.IsInsideAdditiveVolume) ? this._VolumeFrontFastShader : this._VolumeFrontShader, "CustomType");
                effectsCamera.clearFlags    = CameraClearFlags.Nothing;
                effectsCamera.targetTexture = this._AdditiveMaskTexture;
                effectsCamera.RenderWithShader(this._VolumeBackShader, "CustomType");
                for (int l = 0; l < count2; l++)
                {
                    volumesDirect[l].SetLayer(waterCollidersLayer);
                }
                propertyBlock.SetTexture(ShaderVariables.AdditiveMask, this._AdditiveMaskTexture);
            }
            this.OnSharedMaskPostRender();
            effectsCamera.targetTexture = null;
        }
示例#12
0
 public override void SetOn(MaterialPropertyBlock block) => block.SetTexture(id, latestValue);
 public override void SetValue(InteractableThemeProperty property, int index, float percentage)
 {
     propertyBlock.SetTexture("_MainTex", property.Values[index].Texture);
     renderer.SetPropertyBlock(propertyBlock);
 }
        private void CreateRenderTextures(Camera sourceCamera)
        {
            RenderTextureFormat textureFormat = RenderTextureFormat.DefaultHDR;
            int size = Math.Max(32, RenderTextureSize);

            if (WeatherMakerScript.Instance != null)
            {
                size = WeatherMakerScript.Instance.PerformanceProfile.ReflectionTextureSize;
            }

            // cleanup
            if (LeftEyeTexture != null && LeftEyeTexture.width != size)
            {
                LeftEyeTexture.Release();
                DestroyImmediate(LeftEyeTexture);
            }
            if (RightEyeTexture != null && RightEyeTexture.width != size)
            {
                RightEyeTexture.Release();
                DestroyImmediate(RightEyeTexture);
            }

            if (LeftEyeTexture == null || !LeftEyeTexture.IsCreated())
            {
                LeftEyeTexture = new RenderTexture(size, size, 16, textureFormat)
                {
                    name = "WeatherMakerPlanaReflectionLeftEyeTexture"
                };
                LeftEyeTexture.wrapMode   = TextureWrapMode.Clamp;
                LeftEyeTexture.filterMode = FilterMode.Bilinear;
            }

            MaterialPropertyBlock reflectBlock = null;

            if (ReflectRenderer == null)
            {
                ReflectMaterial.SetTexture(ReflectionSamplerName, LeftEyeTexture);
            }
            else
            {
                reflectBlock = reflectPropertyBlock;
                ReflectRenderer.GetPropertyBlock(reflectPropertyBlock);
                reflectBlock.SetTexture(ReflectionSamplerName, LeftEyeTexture);
            }

            if (sourceCamera.stereoEnabled)
            {
                if (RightEyeTexture == null || !RightEyeTexture.IsCreated())
                {
                    RightEyeTexture = new RenderTexture(size, size, 16, textureFormat)
                    {
                        name = "WeatherMakerPlanaReflectionRightEyeTexture"
                    };
                    RightEyeTexture.wrapMode   = TextureWrapMode.Clamp;
                    RightEyeTexture.filterMode = FilterMode.Bilinear;
                }

                if (reflectBlock == null)
                {
                    ReflectMaterial.SetTexture(ReflectionSamplerName2, RightEyeTexture);
                }
                else
                {
                    reflectBlock.SetTexture(ReflectionSamplerName2, RightEyeTexture);
                }
            }

            if (reflectBlock != null)
            {
                ReflectRenderer.SetPropertyBlock(reflectBlock);
            }
        }
示例#15
0
    public static void RefreshScene(Scene scene, ftLightmapsStorage storage = null, bool updateNonBaked = false)
    {
        var sceneCount = SceneManager.sceneCount;

        if (globalMapsAdditional == null)
        {
            globalMapsAdditional = new List <LightmapAdditionalData>();
        }

        var lmaps                   = new List <LightmapData>();
        var lmapsAdditional         = new List <LightmapAdditionalData>();
        var existingLmaps           = LightmapSettings.lightmaps;
        var existingLmapsAdditional = globalMapsAdditional;

        // Acquire storage
        if (storage == null)
        {
            if (!scene.isLoaded)
            {
                //Debug.LogError("dbg: Scene not loaded");
                return;
            }
            SceneManager.SetActiveScene(scene);

            var go = FindInScene("!ftraceLightmaps", scene);
            if (go == null)
            {
                //Debug.LogError("dbg: no storage");
                return;
            }

            storage = go.GetComponent <ftLightmapsStorage>();
            if (storage == null)
            {
                //Debug.LogError("dbg: no storage 2");
                return;
            }
        }
        if (storage.idremap == null || storage.idremap.Length != storage.maps.Count)
        {
            storage.idremap = new int[storage.maps.Count];
        }

        // Decide which global engine lightmapping mode to use
        // TODO: allow mixing different modes
        directionalMode = storage.dirMaps.Count != 0 ? 1 : 0;
        bool patchedDirection = false;

        SetDirectionalMode();

        // Set dummy directional tex for non-directional lightmaps in directional mode
        if (directionalMode == 1)
        {
            for (int i = 0; i < existingLmaps.Length; i++)
            {
                if (existingLmaps[i].lightmapDir == null)
                {
                    var lm = existingLmaps[i];
                    lm.lightmapDir   = GetEmptyDirectionTex(storage);
                    existingLmaps[i] = lm;
                    patchedDirection = true;
                }
            }
        }

        // Detect if changes to lightmap array are necessary
        bool sameArray = false;

        if (existingLmaps.Length == storage.maps.Count)
        {
            sameArray = true;
            for (int i = 0; i < storage.maps.Count; i++)
            {
                if (existingLmaps[i].lightmapColor != storage.maps[i])
                {
                    sameArray = false;
                    break;
                }
                if (storage.rnmMaps0.Count > i && (existingLmapsAdditional.Count <= i || existingLmapsAdditional[i].rnm0 != storage.rnmMaps0[i]))
                {
                    sameArray = false;
                    break;
                }
            }
        }

        if (!sameArray) // create new lightmap array
        {
            if (sceneCount >= 1)
            {
                // first add old
                for (int i = 0; i < existingLmaps.Length; i++)
                {
                    // skip empty lightmaps (can be created by 5.6 ldata asset or vertex color)
                    // ... unless there are valid lightmaps around them
                    bool lightmapIsEmpty      = existingLmaps[i] == null || (existingLmaps[i].lightmapColor == null && existingLmaps[i].shadowMask == null);
                    bool lightmapCanBeSkipped = lightmapIsEmpty && (i == 0 || i == existingLmaps.Length - 1);
                    if (!lightmapCanBeSkipped)
                    {
                        lmaps.Add(existingLmaps[i]);
                        if (existingLmapsAdditional.Count > i)
                        {
                            lmapsAdditional.Add(existingLmapsAdditional[i]);
                        }
                    }
                }
            }

            for (int i = 0; i < storage.maps.Count; i++)
            {
                var       texlm   = storage.maps[i];
                Texture2D texmask = null;
                Texture2D texdir  = null;
                Texture2D texrnm0 = null;
                Texture2D texrnm1 = null;
                Texture2D texrnm2 = null;
                int       mapMode = 0;
                if (storage.masks.Count > i)
                {
                    texmask = storage.masks[i];
                }
                if (storage.dirMaps.Count > i)
                {
                    texdir = storage.dirMaps[i];
                }
                if (storage.rnmMaps0.Count > i)
                {
                    texrnm0 = storage.rnmMaps0[i];
                    texrnm1 = storage.rnmMaps1[i];
                    texrnm2 = storage.rnmMaps2[i];
                    mapMode = storage.mapsMode[i];
                }

                bool found      = false;
                int  firstEmpty = -1;
                for (int j = 0; j < lmaps.Count; j++)
                {
                    if (lmaps[j].lightmapColor == texlm && lmaps[j].shadowMask == texmask)
                    {
                        // lightmap already added - reuse
                        storage.idremap[i] = j;
                        found = true;

                        //Debug.LogError("reused "+j);

                        // additional maps array could be flushed due to script recompilation - recover
                        if (texrnm0 != null && (lmapsAdditional.Count <= j || lmapsAdditional[j].rnm0 == null))
                        {
                            while (lmapsAdditional.Count <= j)
                            {
                                lmapsAdditional.Add(new LightmapAdditionalData());
                            }
                            var l = new LightmapAdditionalData();
                            l.rnm0             = texrnm0;
                            l.rnm1             = texrnm1;
                            l.rnm2             = texrnm2;
                            l.mode             = mapMode;
                            lmapsAdditional[j] = l;
                        }

                        break;
                    }
                    else if (firstEmpty < 0 && lmaps[j].lightmapColor == null && lmaps[j].shadowMask == null)
                    {
                        // free (deleted) entry in existing lightmap list - possibly reuse
                        storage.idremap[i] = j;
                        firstEmpty         = j;
                    }
                }

                if (!found)
                {
                    LightmapData lm;
                    if (firstEmpty >= 0)
                    {
                        lm = lmaps[firstEmpty];
                    }
                    else
                    {
                        lm = new LightmapData();
                    }

                    lm.lightmapColor = texlm;
                    if (storage.masks.Count > i)
                    {
                        lm.shadowMask = texmask;
                    }
                    if (storage.dirMaps.Count > i && texdir != null)
                    {
                        lm.lightmapDir = texdir;
                    }
                    else if (directionalMode == 1)
                    {
                        lm.lightmapDir = GetEmptyDirectionTex(storage);
                    }

                    if (firstEmpty < 0)
                    {
                        lmaps.Add(lm);
                        storage.idremap[i] = lmaps.Count - 1;
                    }
                    else
                    {
                        lmaps[firstEmpty] = lm;
                    }

                    if (storage.rnmMaps0.Count > i)
                    {
                        var l = new LightmapAdditionalData();
                        l.rnm0 = texrnm0;
                        l.rnm1 = texrnm1;
                        l.rnm2 = texrnm2;
                        l.mode = mapMode;

                        if (firstEmpty < 0)
                        {
                            //Debug.LogError("added "+(lmaps.Count-1));
                            while (lmapsAdditional.Count < lmaps.Count - 1)
                            {
                                lmapsAdditional.Add(new LightmapAdditionalData());
                            }
                            lmapsAdditional.Add(l);
                        }
                        else
                        {
                            //Debug.LogError("set " + firstEmpty);
                            while (lmapsAdditional.Count < firstEmpty + 1)
                            {
                                lmapsAdditional.Add(new LightmapAdditionalData());
                            }
                            lmapsAdditional[firstEmpty] = l;
                        }
                    }
                }
            }
        }
        else // reuse existing lightmap array, only remap IDs
        {
            for (int i = 0; i < storage.maps.Count; i++)
            {
                storage.idremap[i] = i;

                //Debug.LogError("full reuse");

                /*if (storage.rnmMaps0.Count > i)
                 * {
                 *  var l = new LightmapAdditionalData();
                 *  l.rnm0 = storage.rnmMaps0[i];
                 *  l.rnm1 = storage.rnmMaps1[i];
                 *  l.rnm2 = storage.rnmMaps2[i];
                 *  l.mode = storage.mapsMode[i];
                 *  lmapsAdditional.Add(l);
                 * }*/
            }
        }

#if UNITY_EDITOR
        // Set editor lighting mode
        Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.OnDemand;
        Lightmapping.realtimeGI     = storage.usesRealtimeGI;
        //Lightmapping.bakedGI = true; // ? only used for enlighten ? makes editor laggy ?
#endif

        // Replace the lightmap array if needed
        if (sameArray && patchedDirection)
        {
            LightmapSettings.lightmaps = existingLmaps;
        }
        if (!sameArray)
        {
            LightmapSettings.lightmaps = lmaps.ToArray();
            globalMapsAdditional       = lmapsAdditional;
        }

        /*
         * // Debug
         * var lms = LightmapSettings.lightmaps;
         * for(int i=0; i<lms.Length; i++)
         * {
         *  var name1 = ((lms[i]==null || lms[i].lightmapColor==null) ? "-" : lms[i].lightmapColor.name);
         *  var name2 = (globalMapsAdditional.Count > i ?(globalMapsAdditional[i].rnm0==null?"x":globalMapsAdditional[i].rnm0.name) : "-");
         *  Debug.LogError(i+" "+name1+" "+name2);
         * }
         */

        // Attempt to update skybox probe
        if (RenderSettings.ambientMode == UnityEngine.Rendering.AmbientMode.Skybox)// && Lightmapping.lightingDataAsset == null)
        {
            var probe   = RenderSettings.ambientProbe;
            int isEmpty = -1;
            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 9; j++)
                {
                    // default bugged probes are [almost] black or 1302?
                    float a = Mathf.Abs(probe[i, j]);
                    if (a > 1000.0f || a < 0.000001f)
                    {
                        isEmpty = 1;
                        break;
                    }
                    if (probe[i, j] != 0)
                    {
                        isEmpty = 0;
                        break;
                    }
                }
                if (isEmpty >= 0)
                {
                    break;
                }
            }
            if (isEmpty != 0)
            {
                DynamicGI.UpdateEnvironment();
            }
        }

        // Set lightmap data on mesh renderers
        var emptyVec4 = new Vector4(1, 1, 0, 0);
        for (int i = 0; i < storage.bakedRenderers.Count; i++)
        {
            var r = storage.bakedRenderers[i];
            if (r == null)
            {
                continue;
            }
            //if (r.isPartOfStaticBatch) continue;
            var  id    = storage.bakedIDs[i];
            Mesh vmesh = null;
            if (i < storage.bakedVertexColorMesh.Count)
            {
                vmesh = storage.bakedVertexColorMesh[i];
            }

            if (vmesh != null)
            {
                var r2 = r as MeshRenderer;
                if (r2 == null)
                {
                    Debug.LogError("Unity cannot use additionalVertexStreams on non-MeshRenderer");
                }
                else
                {
                    r2.additionalVertexStreams = vmesh;
                    r2.lightmapIndex           = 0xFFFF;
                    var prop = new MaterialPropertyBlock();
                    prop.SetFloat("bakeryLightmapMode", 1);
                    r2.SetPropertyBlock(prop);
                }
                continue;
            }

            int globalID = (id < 0 || id >= storage.idremap.Length) ? id : storage.idremap[id];
            r.lightmapIndex = globalID;

            if (!r.isPartOfStaticBatch)
            {
                // scaleOffset is baked on static batches already
                var scaleOffset = id < 0 ? emptyVec4 : storage.bakedScaleOffset[i];
                r.lightmapScaleOffset = scaleOffset;
            }

            if (r.lightmapIndex >= 0 && globalID < globalMapsAdditional.Count)
            {
                var lmap = globalMapsAdditional[globalID];
                if (lmap.rnm0 != null)
                {
                    var prop = new MaterialPropertyBlock();
                    prop.SetTexture("_RNM0", lmap.rnm0);
                    prop.SetTexture("_RNM1", lmap.rnm1);
                    prop.SetTexture("_RNM2", lmap.rnm2);
                    prop.SetFloat("bakeryLightmapMode", lmap.mode);
                    r.SetPropertyBlock(prop);
                }
            }
        }

        // Set lightmap data on definitely-not-baked mesh renderers (can be possibly avoided)
        if (updateNonBaked)
        {
            for (int i = 0; i < storage.nonBakedRenderers.Count; i++)
            {
                var r = storage.nonBakedRenderers[i];
                if (r == null)
                {
                    continue;
                }
                if (r.isPartOfStaticBatch)
                {
                    continue;
                }
                r.lightmapIndex = 0xFFFE;
            }
        }

        // Set lightmap data on terrains
        for (int i = 0; i < storage.bakedRenderersTerrain.Count; i++)
        {
            var r = storage.bakedRenderersTerrain[i];
            if (r == null)
            {
                continue;
            }
            var id = storage.bakedIDsTerrain[i];
            r.lightmapIndex = (id < 0 || id >= storage.idremap.Length) ? id : storage.idremap[id];

            var scaleOffset = id < 0 ? emptyVec4 : storage.bakedScaleOffsetTerrain[i];
            r.lightmapScaleOffset = scaleOffset;
        }

        // Set shadowmask parameters on lights
        for (int i = 0; i < storage.bakedLights.Count; i++)
        {
#if UNITY_2017_3_OR_NEWER
            if (storage.bakedLights[i] == null)
            {
                continue;
            }

            int channel = storage.bakedLightChannels[i];
            var output  = new LightBakingOutput();
            output.isBaked = true;
            if (channel < 0)
            {
                output.lightmapBakeType = LightmapBakeType.Baked;
            }
            else
            {
                output.lightmapBakeType         = LightmapBakeType.Mixed;
                output.mixedLightingMode        = channel > 100 ? MixedLightingMode.Subtractive : MixedLightingMode.Shadowmask;
                output.occlusionMaskChannel     = channel > 100 ? -1 : channel;
                output.probeOcclusionLightIndex = storage.bakedLights[i].bakingOutput.probeOcclusionLightIndex;
            }
            storage.bakedLights[i].bakingOutput = output;
#endif
        }

        // Increment lightmap refcounts
        if (lightmapRefCount == null)
        {
            lightmapRefCount = new List <int>();
        }
        for (int i = 0; i < storage.idremap.Length; i++)
        {
            int currentID = storage.idremap[i];
            while (lightmapRefCount.Count <= currentID)
            {
                lightmapRefCount.Add(0);
            }
            if (lightmapRefCount[currentID] < 0)
            {
                lightmapRefCount[currentID] = 0;
            }
            lightmapRefCount[currentID]++;
        }
        //if (loadedStorages == null) loadedStorages = new List<ftLightmapsStorage>();
        //if (loadedStorages.Contains(storage)) loadedStorages.Add(storage);

        //return appendOffset;
    }
    public void Sync()
    {
#if UNITY_EDITOR
        // If we have a terrain, we might be moved over another terrain. So lets see if we're in the bounds of our current terrain
        // and if not, clear it and try to get a new one..

        bool testForNewTerrain = false;



        // check bounds of existing terrain
        if (msObject != null && testForNewTerrain)
        {
            var tbounds = TransformBounds(msObject.GetBounds());

            Renderer rend = GetComponent <Renderer>();
            if (!tbounds.Intersects(rend.bounds))
            {
                testForNewTerrain = true;
            }
        }

        // see if we have override, if we do, skip terrain testing
        if (msOverrideObject != null)
        {
            if (msOverrideObject is MicroSplatTerrain
#if __MICROSPLAT_MESHTERRAIN__
                || msOverrideObject is MicroSplatMeshTerrain
#endif
                )
            {
                msObject          = msOverrideObject;
                testForNewTerrain = false;
            }
        }

        if (testForNewTerrain)
        {
            RaycastHit[] hits = Physics.RaycastAll(this.transform.position + Vector3.up * 100, Vector3.down, 500);
            for (int i = 0; i < hits.Length; ++i)
            {
                var h = hits[i];
                var t = h.collider.GetComponent <Terrain>();
                if (t != null)
                {
                    var nt = t.GetComponent <MicroSplatTerrain>();
                    if (nt != null)
                    {
                        msObject = nt;
                        break;
                    }
                }
            }
#if __MICROSPLAT_MESHTERRAIN__
            if (msObject == null)
            {
                for (int i = 0; i < hits.Length; ++i)
                {
                    var h = hits [i];
                    var m = h.collider.GetComponent <MicroSplatMeshTerrain> ();
                    if (m != null)
                    {
                        msObject = m;
                        break;
                    }
                    if (h.collider.transform.parent != null)
                    {
                        m = h.collider.transform.parent.GetComponent <MicroSplatMeshTerrain> ();
                        if (m != null)
                        {
                            msObject = m;
                            break;
                        }
                    }
                }
            }
#endif //__MICROSPLAT_MESHTERRAIN__
        }
#endif //UNITY_EDITOR
        if (msObject == null)
        {
            Debug.LogWarning("Terrain Blending: No Terrain Found");
            return;
        }
        Material bmInstance = msObject.GetBlendMatInstance();
        if (bmInstance == null)
        {
            Debug.LogWarning("Terrain Blending: No blend instance found from " + msObject.name);
            return;
        }

        Renderer r           = GetComponent <Renderer>();
        var      materials   = r.sharedMaterials;
        bool     hasBlendMat = false;
        for (int i = 0; i < materials.Length; ++i)
        {
            if (materials[i] == bmInstance && bmInstance != null)
            {
                hasBlendMat = true;
            }
            else if (materials[i] == null || materials[i].shader == null || materials[i].shader.name.Contains("_TerrainObjectBlend"))
            {
                hasBlendMat       = true;
                materials[i]      = bmInstance;
                r.sharedMaterials = materials;
            }
        }
        if (!hasBlendMat)
        {
            System.Array.Resize <Material>(ref materials, materials.Length + 1);
            materials[materials.Length - 1] = bmInstance;
            r.sharedMaterials = materials;
        }

        if (props == null)
        {
            props = new MaterialPropertyBlock();
        }


        props.Clear();

        props.SetVector("_TerrainBlendParams", new Vector4(blendDistance, blendContrast, msObject.transform.position.y, blendCurve));
        props.SetVector("_SlopeBlendParams", new Vector4(slopeFilter, slopeContrast, slopeNoise, normalBlendDistance));
        props.SetVector("_SnowBlendParams", new Vector4(snowWidth, 0, 0, 0));
        props.SetFloat("_TBNoiseScale", noiseScale);
        props.SetVector("_FeatureFilters", new Vector4(doTerrainBlend ? 0.0f : 1.0f, doSnow ? 0.0f : 1.0f, 0, 0));

        if (normalFromObject != null)
        {
            props.SetTexture("_NormalOriginal", normalFromObject);
        }
        r.SetPropertyBlock(props);
    }
示例#17
0
 public static void DrawFullScreen(this CommandBuffer CmdBuffer, RTHandle Source, RenderTargetIdentifier Desc, MaterialPropertyBlock MaterialPropertyBlock = null)
 {
     CmdBuffer.SetRenderTarget(Desc);
     MaterialPropertyBlock.SetTexture(InfinityShaderIDs.RT_MainTexture, Source);
     CmdBuffer.DrawMesh(FullScreenMesh, Matrix4x4.identity, BlitMaterial, 0, 1, MaterialPropertyBlock);
 }
示例#18
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        if (!initialized)
        {
            Initialize();
        }

        if (!initialized)
        {
            return(inputDeps);
        }

        if (m_CurriculumQuery.CalculateEntityCount() != 1)
        {
            return(inputDeps);
        }

        using (s_ResetBackgroundObjects.Auto())
        {
            objectCache.ResetAllObjects();
        }

        var entity          = m_CurriculumQuery.GetSingletonEntity();
        var curriculumState = EntityManager.GetComponentData <CurriculumState>(entity);
        var statics         = EntityManager.GetComponentObject <PlacementStatics>(entity);

        if (curriculumState.ScaleIndex >= statics.ScaleFactors.Length)
        {
            return(inputDeps);
        }

        var meshInfos = new NativeArray <MeshInfo>(statics.BackgroundPrefabs.Length, Allocator.TempJob);

        for (int i = 0; i < statics.BackgroundPrefabs.Length; i++)
        {
            // ReSharper disable once UnusedVariable
            ObjectPlacementUtilities.GetMeshAndMaterial(statics.BackgroundPrefabs[i], out var material, out var meshToDraw);
            meshInfos[i] = new MeshInfo()
            {
                Bounds = meshToDraw.bounds
            };
        }

        var foregroundObject   = statics.ForegroundPrefabs[curriculumState.PrefabIndex];
        var foregroundBounds   = ObjectPlacementUtilities.ComputeBounds(foregroundObject);
        var foregroundRotation =
            ObjectPlacementUtilities.ComposeForegroundRotation(curriculumState, statics.OutOfPlaneRotations, statics.InPlaneRotations);
        var foregroundScale = ObjectPlacementUtilities.ComputeForegroundScaling(
            foregroundBounds, statics.ScaleFactors[curriculumState.ScaleIndex]);
        var transformer = new WorldToScreenTransformer(camera);
        // NOTE: For perspective projection, size will depend on position within the viewport, but we're approximating
        //       by computing size for the center
        var foregroundSizePixels = ObjectPlacementUtilities.ComputeProjectedArea(
            transformer, m_ForegroundCenter, foregroundRotation, foregroundBounds, foregroundScale);

        var placementRegion     = ObjectPlacementUtilities.ComputePlacementRegion(camera, k_PlacementDistance);
        var areaPlacementRegion = placementRegion.width * placementRegion.height;
        var cameraSquarePixels  = camera.pixelHeight * camera.pixelWidth;
        var foregroundSizeUnits = foregroundSizePixels * areaPlacementRegion / cameraSquarePixels;
        // Lazy approximation of how many subdivisions we need to achieve the target density
        var numCellsSqrt       = math.sqrt(m_objectDensity * areaPlacementRegion / foregroundSizeUnits);
        var numCellsHorizontal = (int)math.round(numCellsSqrt * m_aspectRatio);
        var numCellsVertical   = (int)math.round(numCellsSqrt / m_aspectRatio);
        var verticalStep       = placementRegion.height / numCellsVertical;
        var horizontalStep     = placementRegion.width / numCellsHorizontal;
        var scale0             = m_Rand.NextFloat(0.9f, 1.5f);
        var scale1             = m_Rand.NextFloat(0.9f, 1.5f);
        var scaleMin           = math.min(scale0, scale1);
        var scaleMax           = math.max(scale0, scale1);
        var cameraTf           = camera.transform;
        var placementOrigin    = new Vector3(placementRegion.x, placementRegion.y,
                                             k_PlacementDistance + cameraTf.position.z);

        SimulationManager.ReportMetric(m_ScaleRangeMetric, $@"[ {{ ""scaleMin"": {scaleMin}, ""scaleMax"": {scaleMax} }}]");

        var meshesToDraw = new NativeArray <MeshDrawInfo>(numCellsHorizontal * numCellsVertical * numFillPasses, Allocator.TempJob);

        using (s_PlaceBackgroundObjects.Auto())
        {
            // XXX: Rather than placing a large collection and then looking for gaps, we simply assume that a sufficiently
            //      dense background will not have gaps - rendering way more objects than necessary is still substantially
            //      faster than trying to read the render texture multiple times per frame
            new PlaceBackgroundObjectsJob()
            {
                PlacementOrigin    = placementOrigin,
                Transformer        = new WorldToScreenTransformer(camera),
                NumCellsHorizontal = numCellsHorizontal,
                NumCellsVertical   = numCellsVertical,
                HorizontalStep     = horizontalStep,
                VerticalStep       = verticalStep,
                ForegroundSize     = foregroundSizePixels,
                MeshInfos          = meshInfos,
                MeshDrawInfos      = meshesToDraw,
                TextureCount       = statics.BackgroundImages.Length,
                Seed     = m_Rand.NextUInt(),
                MinScale = scaleMin,
                MaxScale = scaleMax
            }.Schedule(numFillPasses, 1, inputDeps).Complete();
        }

        using (s_DrawMeshes.Auto())
        {
            var properties = new MaterialPropertyBlock();
            foreach (var meshDrawInfo in meshesToDraw)
            {
                var prefab      = statics.BackgroundPrefabs[meshDrawInfo.MeshIndex];
                var sceneObject = objectCache.GetOrInstantiate(prefab);
                ObjectPlacementUtilities.CreateRandomizedHue(properties, backgroundHueMaxOffset, ref m_Rand);
                // ReSharper disable once Unity.PreferAddressByIdToGraphicsParams
                properties.SetTexture("_BaseMap", statics.BackgroundImages[meshDrawInfo.TextureIndex]);
                sceneObject.GetComponentInChildren <MeshRenderer>().SetPropertyBlock(properties);
                sceneObject.transform.SetPositionAndRotation(meshDrawInfo.Position, meshDrawInfo.Rotation);
                sceneObject.transform.localScale = meshDrawInfo.Scale;
            }
        }

        // We have finished drawing the meshes in the camera view, but the engine itself will call Render()
        // at the end of the frame
        meshInfos.Dispose();
        meshesToDraw.Dispose();

        var numObjectsExpected = numCellsHorizontal * numCellsVertical * numFillPasses;

        if (numObjectsExpected != objectCache.NumObjectsActive)
        {
            Debug.LogWarning($"BackgroundGenerator should have placed {numObjectsExpected} but is only using " +
                             $"{objectCache.NumObjectsActive} from the cache.");
        }

        return(inputDeps);
    }
示例#19
0
        void Update()
        {
            if (!PluginEntry.IsAvailable)
            {
                return;
            }

            _dataTime = 1.0f / _FPS;

            // Plugin lazy initialization
            if (_plugin == System.IntPtr.Zero)
            {
                _plugin = PluginEntry.CreateReceiver(_sourceName);
                if (_plugin == System.IntPtr.Zero)
                {
                    return;                                // No receiver support
                }
            }

            // Texture update event invocation with lazy initialization
            if (_callback == System.IntPtr.Zero)
            {
                _callback = PluginEntry.GetTextureUpdateCallback();
            }

            if (_sourceTexture == null)
            {
                _sourceTexture           = new Texture2D(8, 8); // Placeholder
                _sourceTexture.hideFlags = HideFlags.DontSave;
            }

            Util.IssueTextureUpdateEvent
                (_callback, _sourceTexture, PluginEntry.GetReceiverID(_plugin));

            // Texture information retrieval
            var width  = PluginEntry.GetFrameWidth(_plugin);
            var height = PluginEntry.GetFrameHeight(_plugin);

            if (width == 0 || height == 0)
            {
                return;                            // Not yet ready
            }
            // Source data dimensions
            var alpha = PluginEntry.GetFrameFourCC(_plugin) == FourCC.UYVA;
            var sw    = width / 2;
            var sh    = height * (alpha ? 3 : 2) / 2;

            // Renew the textures when the dimensions are changed.
            if (_sourceTexture.width != sw || _sourceTexture.height != sh)
            {
                Util.Destroy(_sourceTexture);
                Util.Destroy(_receivedTexture);
                _sourceTexture            = new Texture2D(sw, sh, TextureFormat.RGBA32, false, true);
                _sourceTexture.hideFlags  = HideFlags.DontSave;
                _sourceTexture.filterMode = FilterMode.Point;
            }

            // Receiver texture lazy initialization
            if (_targetTextureOne == null && _receivedTexture == null)
            {
                _receivedTexture           = new RenderTexture(width, height, 0);
                _receivedTexture.hideFlags = HideFlags.DontSave;
            }

            if (_backTexture == null)
            {
                _backTexture           = new RenderTexture(width, height, 0);
                _backTexture.hideFlags = HideFlags.DontSave;
            }
            if (_frontTexture == null)
            {
                _frontTexture           = new RenderTexture(width, height, 0);
                _frontTexture.hideFlags = HideFlags.DontSave;
            }
            if (_blendMaterial == null)
            {
                _blendMaterial           = new Material(Shader.Find("Hidden/Marrow/BlendReceiver"));
                _blendMaterial.hideFlags = HideFlags.DontSave;
                _blendMaterial.SetTexture("_BackTex", _backTexture);
            }

            _timer += Time.deltaTime;
            if (_timer > _dataTime)
            {
                _showBack = !_showBack;
                _timer    = 0.0f;

                if (_showBack)
                {
                    Graphics.Blit(_sourceTexture, _frontTexture, _blendMaterial, 0);
                }
                else
                {
                    Graphics.Blit(_sourceTexture, _backTexture, _blendMaterial, 0);
                }
            }

            if (!_showBack)
            {
                _blendFactor = _timer / _dataTime;
            }
            else
            {
                _blendFactor = 1 - (_timer / _dataTime);
            }
            _blendMaterial.SetFloat("_BlendFactor", _blendFactor);
            Graphics.Blit(_frontTexture, _targetTextureOne, _blendMaterial, 1);
            Graphics.Blit(_frontTexture, _targetTextureTwo, _blendMaterial, 2);
            // Texture format conversion using the blit shader
            _targetTextureOne.IncrementUpdateCount();

            // Renderer override
            if (_targetRenderer != null)
            {
                // Material property block lazy initialization
                if (_propertyBlock == null)
                {
                    _propertyBlock = new MaterialPropertyBlock();
                }

                // Read-modify-write
                _targetRenderer.GetPropertyBlock(_propertyBlock);
                _propertyBlock.SetTexture(_targetMaterialProperty, _targetTextureOne);
                _propertyBlock.SetTexture(_targetMaterialProperty, _targetTextureTwo);
                _targetRenderer.SetPropertyBlock(_propertyBlock);
            }
        }
示例#20
0
    void LateUpdate()
    {
        last_start = stopwatch.Elapsed.TotalSeconds;
        if (drawDebugWindow)
        {
            DrawDebugWindow();
        }
        ImGui.EndFrame();

        if (queue_font_rebuild)
        {
            RebuildFonts();
            queue_font_rebuild = false;
        }

        // custom cursors
        if (enableCustomCursors)
        {
            ImGuiMouseCursor cursor    = ImGui.GetMouseCursor();
            Texture2D        cursorTex = null;
            Vector2          hotspot   = cursorHotspot;
            switch (cursor)
            {
            case ImGuiMouseCursor.Arrow:
                cursorTex = customCursorArrow;
                break;

            case ImGuiMouseCursor.TextInput:
                cursorTex = customCursorTextInput;
                break;

            case ImGuiMouseCursor.ResizeEW:
                cursorTex = customCursorResizeEW;
                break;

            case ImGuiMouseCursor.ResizeNESW:
                cursorTex  = customCursorResizeNESW;
                hotspot.x += 5; hotspot.y += 5;
                break;

            case ImGuiMouseCursor.ResizeNS:
                cursorTex = customCursorResizeNS;
                break;

            case ImGuiMouseCursor.ResizeNWSE:
                cursorTex  = customCursorResizeNWSE;
                hotspot.x += 5; hotspot.y += 5;
                break;

            default:
                break;
            }
            // Don't set cursor if it has not actually changed
            if (currentCursorTex != cursorTex)
            {
                if (cursorTex != null)
                {
                    Cursor.SetCursor(cursorTex, hotspot, CursorMode.Auto);
                }
                else
                {
                    Cursor.SetCursor(null, cursorHotspot, CursorMode.Auto);
                }
                currentCursorTex = cursorTex;
            }
        }

        ImGui.Render();

        // render ImGui
        ImDrawDataPtr data = ImGui.GetDrawData();

        if (commandBuffer != null)
        {
            // Clear buffer regardless of whether we have something to render or not
            commandBuffer.Clear();
        }

        // Don't update meshes and Command Buffers if there is nothing to render
        if (data.CmdListsCount > 0)
        {
            // resize meshes array
            int numDrawCommands = 0;
            for (int i = 0; i < data.CmdListsCount; i++)
            {
                ImDrawListPtr cmdList   = data.getDrawListPtr(i);
                var           cmdBuffer = cmdList.CmdBuffer;
                numDrawCommands += cmdBuffer.Size;
            }

            if (meshes == null)
            {
                meshes = new List <ImGuiMesh>();
            }

            if (meshes.Count != numDrawCommands)
            {
                // add new meshes to list if needed
                for (int i = meshes.Count; i < numDrawCommands; i++)
                {
                    ImGuiMesh mesh = new ImGuiMesh();
                    meshes.Add(mesh);
                }
                // delete extra meshes if needed
                for (int i = meshes.Count - 1; i >= numDrawCommands; i--)
                {
                    Destroy(meshes[i].mesh);
                    meshes.RemoveAt(i);
                }
            }

            if (commandBuffer == null)
            {
                commandBuffer      = new CommandBuffer();
                commandBuffer.name = "ImGui Renderer";
                commandBuffer.SetRenderTarget(BuiltinRenderTextureType.CameraTarget);
                guiCamera.AddCommandBuffer(CameraEvent.AfterEverything, commandBuffer);
            }

            commandBuffer.SetRenderTarget(BuiltinRenderTextureType.CameraTarget);
            // orthogonal projection of GUI mesh to camera space
            Matrix4x4 matrix = Matrix4x4.Ortho(0, Screen.width, 0, Screen.height, 0, 0.1f);
            // negate world to camera transform and projection which Unity applies itself
            matrix = guiCamera.cameraToWorldMatrix * guiCamera.projectionMatrix.inverse * matrix;

            // update Command Buffers
            int count = 0;
            for (int i = 0; i < data.CmdListsCount; i++)
            {
                ImDrawListPtr cmdList   = data.getDrawListPtr(i);
                var           cmdBuffer = cmdList.CmdBuffer;

                uint startElement = 0;
                for (int j = 0; j < cmdBuffer.Size; j++)
                {
                    ImDrawCmd cmd  = cmdBuffer[j];
                    Rect      rect = new Rect
                    {
                        min = new Vector2(cmd.ClipRect.x, Screen.height - cmd.ClipRect.y),
                        max = new Vector2(cmd.ClipRect.z, Screen.height - cmd.ClipRect.w)
                    };
                    commandBuffer.EnableScissorRect(rect);

                    meshes[count].UpdateMesh(cmd, cmdList.IdxBuffer, cmdList.VtxBuffer, (int)startElement);
                    if (cmd.TextureId == fontTexturePtr)
                    {
                        mpb.SetTexture(main_tex_id, fontTexture);
                        commandBuffer.DrawMesh(meshes[count].mesh, matrix, material, 0, 0, mpb);
                    }
                    else if (textures.ContainsKey(cmd.TextureId))
                    {
                        mpb.SetTexture(main_tex_id, textures[cmd.TextureId]);
                        commandBuffer.DrawMesh(meshes[count].mesh, matrix, material, 0, 0, mpb);
                    }
                    else
                    {
                        Debug.LogWarning("Image texture missing!");
                    }

                    startElement += cmd.ElemCount;
                    count++;
                }
            }
        }
        else if (commandBuffer != null)
        {
            // Remove Command Buffer if there is nothing to render
            guiCamera.RemoveCommandBuffer(CameraEvent.AfterEverything, commandBuffer);
            commandBuffer = null;
        }

        textures.Clear();
        last_end = stopwatch.Elapsed.TotalSeconds;
    }
示例#21
0
        // 描画キックを行う
        public void UpdateMesh()
        {
            // ■だけは常に入れておく。他は文字描画要求の都度投げる
            font.RequestCharactersInTexture(whiteString);
            // 描画キック
            mesh.Clear();
            if (subMeshCount > 0)
            {
                subMeshes[subMeshCount - 1].FixIndexCount(indexCount);
                // 使用量が半分以下の場合、テンポラリにコピーしてから渡す
                if (vertexCount < (capacity / 2)) // 閾値は研究が必要だが、とりあえず。
                {
                    UnityEngine.Profiling.Profiler.BeginSample("DebugPrimitiveRenderer.UpdateMesh.FillTemporary");

                    temporaryVertices.Clear();
                    temporaryUv.Clear();
                    temporaryColors.Clear();

                    var tmpV  = new System.ArraySegment <Vector3>(vertices, 0, vertexCount);
                    var tmpUv = new System.ArraySegment <Vector2>(uv, 0, vertexCount);
                    var tmpC  = new System.ArraySegment <Color32>(colors, 0, vertexCount);

                    temporaryVertices.AddRange(tmpV);
                    temporaryUv.AddRange(tmpUv);
                    temporaryColors.AddRange(tmpC);

                    mesh.SetVertices(temporaryVertices);
                    mesh.SetUVs(0, temporaryUv);
                    mesh.SetColors(temporaryColors);

                    UnityEngine.Profiling.Profiler.EndSample();
                }
                else // 半分以上使っている場合、そのまま渡す。
                {
                    UnityEngine.Profiling.Profiler.BeginSample("DebugPrimitiveRenderer.UpdateMesh.CopyAll");
                    mesh.vertices = vertices;
                    mesh.uv       = uv;
                    mesh.colors32 = colors;
                    UnityEngine.Profiling.Profiler.EndSample();
                }
                mesh.subMeshCount = subMeshCount;

                Material[] materials = new Material[subMeshCount];
                for (int i = 0; i < subMeshCount; i++)
                {
                    materials[i] = subMeshes[i].material;
                }
                meshRenderer.sharedMaterials = materials;

                for (int i = 0; i < subMeshCount; i++)
                {
                    UnityEngine.Profiling.Profiler.BeginSample("DebugPrimitiveRenderer.UpdateMesh.FillIndices");
                    var subMesh = subMeshes[i];
                    temporaryIndices.Clear();
                    var tmpI = new System.ArraySegment <int>(indices, subMesh.indexStart, subMesh.indexCount);
                    temporaryIndices.AddRange(tmpI);
                    mesh.SetTriangles(temporaryIndices, i, true);
                    materialPropertyBlock.SetTexture(
                        textureShaderPropertyId,
                        subMesh.texture);
                    meshRenderer.SetPropertyBlock(materialPropertyBlock, i);
                    UnityEngine.Profiling.Profiler.EndSample();
                }
            }
            meshFilter.sharedMesh = mesh;
            vertexCount           = 0;
            indexCount            = 0;
            texture = null;
            // 毎フレーム白にリセット
            Color        = new Color32(255, 255, 255, 255);
            subMeshCount = 0;

            // どうもおかしいので毎フレーム取ってみる。
            CharacterInfo ch;

            font.GetCharacterInfo(whiteChar, out ch);
            whiteUv  = ch.uvTopLeft;
            whiteUv += ch.uvTopRight;
            whiteUv += ch.uvBottomLeft;
            whiteUv += ch.uvBottomRight;
            whiteUv *= 0.25f;
        }
示例#22
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);
            }
        }
    }
示例#23
0
 public void GenerateChannelsMaterialProps(MaterialPropertyBlock props)
 {
     props.SetTexture("_ChannelsTex", texture);
     props.SetVector("_ChannelsTex_UV", uv);
 }
示例#24
0
        void DisplayProbeVolumeAtlas(CommandBuffer cmd, Material debugMaterial, float screenX, float screenY, float screenSizeX, float screenSizeY, float minValue, float maxValue, int sliceMode)
        {
            if (ShaderConfig.s_ProbeVolumesEvaluationMode == ProbeVolumesEvaluationModes.Disabled)
            {
                return;
            }

            if (!m_SupportProbeVolume)
            {
                return;
            }

            Vector4 validRange            = new Vector4(minValue, 1.0f / (maxValue - minValue));
            Vector3 textureViewScale      = new Vector3(1.0f, 1.0f, 1.0f);
            Vector3 textureViewBias       = new Vector3(0.0f, 0.0f, 0.0f);
            Vector3 textureViewResolution = new Vector3(s_ProbeVolumeAtlasWidth, s_ProbeVolumeAtlasHeight, s_ProbeVolumeAtlasDepth);
            Vector4 atlasTextureOctahedralDepthScaleBias = new Vector4(1.0f, 1.0f, 0.0f, 0.0f);

        #if UNITY_EDITOR
            if (UnityEditor.Selection.activeGameObject != null)
            {
                var selectedProbeVolume = UnityEditor.Selection.activeGameObject.GetComponent <ProbeVolume>();
                if (selectedProbeVolume != null)
                {
                    // User currently has a probe volume selected.
                    // Compute a scaleBias term so that atlas view automatically zooms into selected probe volume.
                    int selectedProbeVolumeKey = selectedProbeVolume.GetID();
                    if (probeVolumeAtlas.TryGetScaleBias(out Vector3 selectedProbeVolumeScale, out Vector3 selectedProbeVolumeBias, selectedProbeVolumeKey))
                    {
                        textureViewScale      = selectedProbeVolumeScale;
                        textureViewBias       = selectedProbeVolumeBias;
                        textureViewResolution = new Vector3(
                            selectedProbeVolume.parameters.resolutionX,
                            selectedProbeVolume.parameters.resolutionY,
                            selectedProbeVolume.parameters.resolutionZ
                            );
                    }
                    if (probeVolumeAtlasOctahedralDepth.TryGetScaleBias(out Vector4 selectedProbeVolumeOctahedralDepthScaleBias, selectedProbeVolumeKey))
                    {
                        atlasTextureOctahedralDepthScaleBias = selectedProbeVolumeOctahedralDepthScaleBias;
                    }
                }
            }
        #endif

            // Note: The system is not aware of slice packing in Z.
            // Need to modify scale and bias terms just before uploading to GPU.
            // TODO: Should we make it aware earlier up the chain?
            textureViewScale.z = textureViewScale.z / (float)m_ProbeVolumeAtlasSHRTDepthSliceCount;
            textureViewBias.z  = textureViewBias.z / (float)m_ProbeVolumeAtlasSHRTDepthSliceCount;

            MaterialPropertyBlock propertyBlock = new MaterialPropertyBlock();
            propertyBlock.SetTexture(HDShaderIDs._AtlasTextureSH, m_ProbeVolumeAtlasSHRTHandle.rt);
            propertyBlock.SetVector(HDShaderIDs._TextureViewScale, textureViewScale);
            propertyBlock.SetVector(HDShaderIDs._TextureViewBias, textureViewBias);
            propertyBlock.SetVector(HDShaderIDs._TextureViewResolution, textureViewResolution);
            cmd.SetGlobalVector(HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCount, new Vector4(
                                    s_ProbeVolumeAtlasWidth,
                                    s_ProbeVolumeAtlasHeight,
                                    s_ProbeVolumeAtlasDepth,
                                    m_ProbeVolumeAtlasSHRTDepthSliceCount
                                    ));
            cmd.SetGlobalVector(HDShaderIDs._ProbeVolumeAtlasResolutionAndSliceCountInverse, new Vector4(
                                    1.0f / (float)s_ProbeVolumeAtlasWidth,
                                    1.0f / (float)s_ProbeVolumeAtlasHeight,
                                    1.0f / (float)s_ProbeVolumeAtlasDepth,
                                    1.0f / (float)m_ProbeVolumeAtlasSHRTDepthSliceCount
                                    ));
            propertyBlock.SetTexture(HDShaderIDs._AtlasTextureOctahedralDepth, m_ProbeVolumeAtlasOctahedralDepthRTHandle.rt);
            propertyBlock.SetVector(HDShaderIDs._AtlasTextureOctahedralDepthScaleBias, atlasTextureOctahedralDepthScaleBias);
            propertyBlock.SetVector(HDShaderIDs._ValidRange, validRange);
            propertyBlock.SetInt(HDShaderIDs._ProbeVolumeAtlasSliceMode, sliceMode);
            cmd.SetViewport(new Rect(screenX, screenY, screenSizeX, screenSizeY));
            cmd.DrawProcedural(Matrix4x4.identity, debugMaterial, debugMaterial.FindPass("ProbeVolume"), MeshTopology.Triangles, 3, 1, propertyBlock);
        }
示例#25
0
        public void SetUniforms(MaterialPropertyBlock block, Material mat, bool full = true, bool forQuad = false)
        {
            if (artb == null)
            {
                Debug.Log("Atmosphere: ARTB is null!"); return;
            }

            if (mat != null)
            {
                Helper.SetKeywords(mat, Keywords, false);
            }

            if (full)
            {
                if (block == null)
                {
                    return;
                }

                SetEclipses(block);
                SetShine(block);

                if (!forQuad)
                {
                    if (planetoid != null)
                    {
                        if (planetoid.Ring != null)
                        {
                            planetoid.Ring.SetShadows(block, planetoid.Shadows);
                        }
                    }
                }

                block.SetFloat("fade", Fade);
                block.SetFloat("density", Density);
                block.SetFloat("scale", atmosphereParameters.SCALE);
                block.SetFloat("Rg", atmosphereParameters.Rg);
                block.SetFloat("Rt", atmosphereParameters.Rt);
                block.SetFloat("RL", atmosphereParameters.Rl);
                block.SetVector("betaR", atmosphereParameters.BETA_R / 1000);
                block.SetVector("betaMSca", atmosphereParameters.BETA_MSca / 1000);
                block.SetVector("betaMEx", atmosphereParameters.BETA_MEx / 1000);
                block.SetFloat("mieG", Mathf.Clamp(atmosphereParameters.MIE_G, 0.0f, 0.99f));

                block.SetFloat("_Aerial_Perspective_Offset", AerialPerspectiveOffset);
                block.SetFloat("_ExtinctionGroundFade", ExtinctionGroundFade);

                block.SetFloat("_Sun_Glare_Scale", 0.1f);

                if (artb.transmittanceT != null)
                {
                    block.SetTexture("_Sky_Transmittance", artb.transmittanceT);
                }
                if (artb.inscatterT_Read != null)
                {
                    block.SetTexture("_Sky_Inscatter", artb.inscatterT_Read);
                }
                if (artb.irradianceT_Read != null)
                {
                    block.SetTexture("_Sky_Irradiance", artb.irradianceT_Read);
                }

                var WCP = forQuad == true ? worldCameraPos - Origin : worldCameraPos;

                block.SetMatrix("_Globals_WorldToCamera", worldToCamera);
                block.SetMatrix("_Globals_CameraToWorld", cameraToWorld);
                block.SetMatrix("_Globals_CameraToScreen", cameraToScreen);
                block.SetMatrix("_Globals_ScreenToCamera", screenToCamera);
                block.SetVector("_Globals_WorldCameraPos", forQuad == true ? worldCameraPos - Origin : worldCameraPos);

                block.SetVector("_Globals_Origin", -Origin);

                block.SetVector("WCPG", WCP + (-Origin));

                block.SetFloat("_Exposure", HDRExposure);
                block.SetFloat("_HDRMode", (int)HDRMode);

                SetSunUniforms(block);
            }
        }
示例#26
0
        // 'renderSunDisk' parameter is not supported.
        // Users should instead create an emissive (or lit) mesh for every relevant light source
        // (to support multiple stars in space, moons with moon phases, etc).
        public override void RenderSky(BuiltinSkyParameters builtinParams, bool renderForCubemap, bool renderSunDisk)
        {
            var pbrSky = builtinParams.skySettings as PhysicallyBasedSky;

            // TODO: the following expression is somewhat inefficient, but good enough for now.
            Vector3 cameraPos    = builtinParams.worldSpaceCameraPos;
            Vector3 planetCenter = pbrSky.GetPlanetCenterPosition(cameraPos);
            float   R            = pbrSky.GetPlanetaryRadius();

            Vector3 cameraToPlanetCenter = planetCenter - cameraPos;
            float   r = cameraToPlanetCenter.magnitude;

            cameraPos = planetCenter - Mathf.Max(R, r) * cameraToPlanetCenter.normalized;

            bool simpleEarthMode = pbrSky.type.value == PhysicallyBasedSkyModel.EarthSimple;

            CommandBuffer cmd = builtinParams.commandBuffer;

            // Precomputation is done, shading is next.
            Quaternion planetRotation = Quaternion.Euler(pbrSky.planetRotation.value.x,
                                                         pbrSky.planetRotation.value.y,
                                                         pbrSky.planetRotation.value.z);

            Quaternion spaceRotation = Quaternion.Euler(pbrSky.spaceRotation.value.x,
                                                        pbrSky.spaceRotation.value.y,
                                                        pbrSky.spaceRotation.value.z);

            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._PixelCoordToViewDirWS, builtinParams.pixelCoordToViewDirMatrix);
            s_PbrSkyMaterialProperties.SetVector(HDShaderIDs._WorldSpaceCameraPos1, cameraPos);
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._ViewMatrix1, builtinParams.viewMatrix);
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._PlanetRotation, Matrix4x4.Rotate(planetRotation));
            s_PbrSkyMaterialProperties.SetMatrix(HDShaderIDs._SpaceRotation, Matrix4x4.Rotate(spaceRotation));

            m_PrecomputedData.BindBuffers(cmd, s_PbrSkyMaterialProperties);

            int hasGroundAlbedoTexture = 0;

            if (pbrSky.groundColorTexture.value != null && !simpleEarthMode)
            {
                hasGroundAlbedoTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundAlbedoTexture, pbrSky.groundColorTexture.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasGroundAlbedoTexture, hasGroundAlbedoTexture);

            int hasGroundEmissionTexture = 0;

            if (pbrSky.groundEmissionTexture.value != null && !simpleEarthMode)
            {
                hasGroundEmissionTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._GroundEmissionTexture, pbrSky.groundEmissionTexture.value);
                s_PbrSkyMaterialProperties.SetFloat(HDShaderIDs._GroundEmissionMultiplier, pbrSky.groundEmissionMultiplier.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasGroundEmissionTexture, hasGroundEmissionTexture);

            int hasSpaceEmissionTexture = 0;

            if (pbrSky.spaceEmissionTexture.value != null && !simpleEarthMode)
            {
                hasSpaceEmissionTexture = 1;
                s_PbrSkyMaterialProperties.SetTexture(HDShaderIDs._SpaceEmissionTexture, pbrSky.spaceEmissionTexture.value);
                s_PbrSkyMaterialProperties.SetFloat(HDShaderIDs._SpaceEmissionMultiplier, pbrSky.spaceEmissionMultiplier.value);
            }
            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._HasSpaceEmissionTexture, hasSpaceEmissionTexture);

            s_PbrSkyMaterialProperties.SetInt(HDShaderIDs._RenderSunDisk, renderSunDisk ? 1 : 0);

            int pass = (renderForCubemap ? 0 : 2);

            CoreUtils.DrawFullScreen(builtinParams.commandBuffer, m_PbrSkyMaterial, s_PbrSkyMaterialProperties, pass);
        }
示例#27
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
            }
        }
    }
        void Update()
        {
            // Release the plugin instance when the previously established
            // connection is now invalid.
            if (_plugin != System.IntPtr.Zero && !PluginEntry.CheckValid(_plugin))
            {
                Util.IssuePluginEvent(PluginEntry.Event.Dispose, _plugin);
                _plugin = System.IntPtr.Zero;
            }

            // Plugin lazy initialization
            if (_plugin == System.IntPtr.Zero)
            {
                _plugin = PluginEntry.CreateReceiver(_sourceName);
                if (_plugin == System.IntPtr.Zero)
                {
                    return;                                // Spout may not be ready.
                }
            }

            Util.IssuePluginEvent(PluginEntry.Event.Update, _plugin);

            // Texture information retrieval
            var ptr    = PluginEntry.GetTexturePointer(_plugin);
            var width  = PluginEntry.GetTextureWidth(_plugin);
            var height = PluginEntry.GetTextureHeight(_plugin);

            // Resource validity check
            if (_sharedTexture != null)
            {
                if (ptr != _sharedTexture.GetNativeTexturePtr() ||
                    width != _sharedTexture.width ||
                    height != _sharedTexture.height)
                {
                    // Not match: Destroy to get refreshed.
                    Util.Destroy(_sharedTexture);
                }
            }

            // Shared texture lazy (re)initialization
            if (_sharedTexture == null && ptr != System.IntPtr.Zero)
            {
                _sharedTexture = Texture2D.CreateExternalTexture(
                    width, height, TextureFormat.ARGB32, false, false, ptr
                    );
                _sharedTexture.hideFlags = HideFlags.DontSave;

                // Destroy the previously allocated receiver texture to
                // refresh specifications.
                Util.Destroy(_receivedTexture);
            }

            // Texture format conversion with the blit shader
            if (_sharedTexture != null)
            {
                // Blit shader lazy initialization
                if (_blitMaterial == null)
                {
                    _blitMaterial           = new Material(Shader.Find("Hidden/Spout/Blit"));
                    _blitMaterial.hideFlags = HideFlags.DontSave;
                }

                if (_targetTexture != null)
                {
                    // Blit the shared texture to the target texture.
                    Graphics.Blit(_sharedTexture, _targetTexture, _blitMaterial, 1);
                }
                else
                {
                    // Receiver texture lazy initialization
                    if (_receivedTexture == null)
                    {
                        _receivedTexture = new RenderTexture
                                               (_sharedTexture.width, _sharedTexture.height, 0);
                        _receivedTexture.hideFlags = HideFlags.DontSave;
                    }

                    // Blit the shared texture to the receiver texture.
                    Graphics.Blit(_sharedTexture, _receivedTexture, _blitMaterial, 1);
                }
            }

            // Renderer override
            if (_targetRenderer != null && receivedTexture != null)
            {
                // Material property block lazy initialization
                if (_propertyBlock == null)
                {
                    _propertyBlock = new MaterialPropertyBlock();
                }

                // Read-modify-write
                _targetRenderer.GetPropertyBlock(_propertyBlock);
                _propertyBlock.SetTexture(_targetMaterialProperty, receivedTexture);
                _targetRenderer.SetPropertyBlock(_propertyBlock);
            }
        }
 public static void BindNull(int shapeSlot, MaterialPropertyBlock properties)
 {
     properties.SetTexture(ParamIdSampler(shapeSlot), Texture2D.blackTexture);
 }
    }//Use This

    public static void BlitSRT(this CommandBuffer buffer, MaterialPropertyBlock block, RenderTexture source, RenderTexture destination, Material mat, int pass)
    {
        block.SetTexture(ShaderIDs._MainTex, source);
        buffer.SetRenderTarget(destination);
        buffer.DrawMesh(mesh, Matrix4x4.identity, mat, 0, pass, block);
    }//Use This