public static void HDSpeedTree8MaterialFinalizer(Material mat)
        {
            SetHDSpeedTree8Defaults(mat);

            // Need to call this again after reconfiguring keyword toggles
            HDShaderUtils.ResetMaterialKeywords(mat);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Renders the properties in the block.
        /// </summary>
        protected override void OnGUIOpen()
        {
            // Filter out properties we don't want to draw:
            if ((m_Features & Features.ExposedProperties) != 0)
            {
                PropertiesDefaultGUI(properties);
            }

            // If we change a property in a shadergraph, we trigger a material keyword reset
            if (CheckPropertyChanged(properties))
            {
                foreach (var material in materials)
                {
                    HDShaderUtils.ResetMaterialKeywords(material);
                }
            }

            if ((m_Features & Features.DiffusionProfileAsset) != 0)
            {
                DrawDiffusionProfileUI();
            }

            if ((m_Features & Features.ShadowMatte) != 0 && materials.All(m => m.HasProperty(kShadowMatteFilter)))
            {
                DrawShadowMatteToggle();
            }
        }
Ejemplo n.º 3
0
        static void MetallicRemapping(Material material, HDShaderUtils.ShaderID id)
        {
            const string kMetallicRemapMax = "_MetallicRemapMax";

            // Lit shaders now have metallic remapping for the mask map
            if (id == HDShaderUtils.ShaderID.Lit || id == HDShaderUtils.ShaderID.LitTesselation ||
                id == HDShaderUtils.ShaderID.LayeredLit || id == HDShaderUtils.ShaderID.LayeredLitTesselation)
            {
                const string kMetallic = "_Metallic";
                if (material.HasProperty(kMetallic) && material.HasProperty(kMetallicRemapMax))
                {
                    var metallic = material.GetFloat(kMetallic);
                    material.SetFloat(kMetallicRemapMax, metallic);
                }
            }
            else if (id == HDShaderUtils.ShaderID.Decal)
            {
                HDShaderUtils.ResetMaterialKeywords(material);
                var serializedMaterial = new SerializedObject(material);

                const string kMetallicScale = "_MetallicScale";
                float        metallicScale  = 1.0f;
                if (TryFindProperty(serializedMaterial, kMetallicScale, SerializedType.Float, out var propertyMetallicScale, out _, out _))
                {
                    metallicScale = propertyMetallicScale.floatValue;
                    RemoveSerializedFloat(serializedMaterial, kMetallicScale);
                }

                serializedMaterial.ApplyModifiedProperties();

                material.SetFloat(kMetallicRemapMax, metallicScale);
            }
        }
Ejemplo n.º 4
0
        // Not used currently:
        // TODO: Script like this must also work with embed material in scene (i.e we need to catch
        // .unity scene and load material and patch in memory. And it must work with perforce
        // i.e automatically checkout all those files).
        static void SpecularOcclusionMode(Material material, HDShaderUtils.ShaderID id)
        {
            switch (id)
            {
            case HDShaderUtils.ShaderID.Lit:
            case HDShaderUtils.ShaderID.LayeredLit:
            case HDShaderUtils.ShaderID.LitTesselation:
            case HDShaderUtils.ShaderID.LayeredLitTesselation:
                var serializedObject  = new SerializedObject(material);
                var specOcclusionMode = 1;
                if (FindProperty(serializedObject, "_EnableSpecularOcclusion", SerializedType.Boolean).property != null)
                {
                    var enableSpecOcclusion = GetSerializedBoolean(serializedObject, "_EnableSpecularOcclusion");
                    if (enableSpecOcclusion)
                    {
                        specOcclusionMode = 2;
                    }
                    RemoveSerializedBoolean(serializedObject, "_EnableSpecularOcclusion");
                    serializedObject.ApplyModifiedProperties();
                }
                material.SetInt("_SpecularOcclusionMode", specOcclusionMode);

                HDShaderUtils.ResetMaterialKeywords(material);
                break;
            }
        }
        // This upgrade functioncopy all the keywords needed for the BlendStates
        // to be synced with their master node values, then it calls the HDRP material keyword reset function and finally
        // it set the render queue of the material to match the one on the shader graph.
        // It's required to sync the shader default properties with the material because when you create a new material,
        // by default the Lit shader is assigned to it and so write all his properties into the material. It's a problem
        // because now that the shader graphs uses these properties, the material properties don't match the shader settings.
        // This function basically fix this.
        static bool UpdateMaterial_ShaderGraphRenderStates(string path, Material mat)
        {
            // We only need to upgrade shadergraphs materials
            if (GraphUtil.IsShaderGraph(mat.shader))
            {
                var defaultProperties = new Material(mat.shader);

                foreach (var floatToReset in floatPropertiesToReset)
                {
                    if (mat.HasProperty(floatToReset))
                    {
                        mat.SetFloat(floatToReset, defaultProperties.GetFloat(floatToReset));
                    }
                }
                foreach (var vectorToReset in vectorPropertiesToReset)
                {
                    if (mat.HasProperty(vectorToReset))
                    {
                        mat.SetVector(vectorToReset, defaultProperties.GetVector(vectorToReset));
                    }
                }

                HDShaderUtils.ResetMaterialKeywords(mat);

                mat.renderQueue = mat.shader.renderQueue;

                defaultProperties = null;

                return(true);
            }

            return(false);
        }
Ejemplo n.º 6
0
        static bool ResetAllLoadedMaterialKeywords(string descriptionPrefix, float progressScale, float progressOffset)
        {
            var materials = Resources.FindObjectsOfTypeAll <Material>();

            bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);

            bool anyMaterialDirty = false; // Will be true if any material is dirty.

            for (int i = 0, length = materials.Length; i < length; i++)
            {
                EditorUtility.DisplayProgressBar(
                    "Setup materials Keywords...",
                    string.Format("{0}{1} / {2} materials cleaned.", descriptionPrefix, i, length),
                    (i / (float)(length - 1)) * progressScale + progressOffset);

                CoreEditorUtils.CheckOutFile(VCSEnabled, materials[i]);

                if (HDShaderUtils.ResetMaterialKeywords(materials[i]))
                {
                    anyMaterialDirty = true;
                }
            }

            return(anyMaterialDirty);
        }
        static void OnShaderGraphSaved(Shader shader)
        {
            // Iterate all Materials
            string[] materialGuids = AssetDatabase.FindAssets(kMaterialFilter);
            try
            {
                for (int i = 0, length = materialGuids.Length; i < length; i++)
                {
                    // Only update progress bar every 10 materials
                    if (i % 10 == 9)
                    {
                        EditorUtility.DisplayProgressBar(
                            "Updating dependent materials...",
                            string.Format("{0} / {1} materials updated.", i, length),
                            i / (float)(length - 1));
                    }

                    // Get Material object
                    string   materialPath = AssetDatabase.GUIDToAssetPath(materialGuids[i]);
                    Material material     = AssetDatabase.LoadAssetAtPath <Material>(materialPath);

                    // Reset keywords
                    if (material.shader.name == shader.name)
                    {
                        HDShaderUtils.ResetMaterialKeywords(material);
                    }
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
        }
Ejemplo n.º 8
0
        static void MoreMaterialSurfaceOptionFromShaderGraph(Material material, HDShaderUtils.ShaderID id)
        {
            if (material.shader.IsShaderGraph())
            {
                // Synchronize properties we exposed from SG to the material
                ResetFloatProperty(kReceivesSSR);
                ResetFloatProperty(kReceivesSSRTransparent);
                ResetFloatProperty(kEnableDecals);
                ResetFloatProperty(kEnableBlendModePreserveSpecularLighting);
                ResetFloatProperty(kTransparentWritingMotionVec);
                ResetFloatProperty(kAddPrecomputedVelocity);
                ResetFloatProperty(kDepthOffsetEnable);
            }

            void ResetFloatProperty(string propName)
            {
                int propIndex = material.shader.FindPropertyIndex(propName);

                if (propIndex == -1)
                {
                    return;
                }
                float defaultValue = material.shader.GetPropertyDefaultFloatValue(propIndex);

                material.SetFloat(propName, defaultValue);
            }

            HDShaderUtils.ResetMaterialKeywords(material);
        }
Ejemplo n.º 9
0
        static void MigrateDecalRenderQueue(Material material, HDShaderUtils.ShaderID id)
        {
            const string kSupportDecals = "_SupportDecals";

            // Take the opportunity to remove _SupportDecals from Unlit as it is not suppose to be here
            if (HDShaderUtils.IsUnlitHDRPShader(material.shader))
            {
                var serializedMaterial = new SerializedObject(material);
                if (TryFindProperty(serializedMaterial, kSupportDecals, SerializedType.Integer, out var property, out _, out _))
                {
                    RemoveSerializedInt(serializedMaterial, kSupportDecals);
                    serializedMaterial.ApplyModifiedProperties();
                }
            }

            if (material.HasProperty(kSupportDecals))
            {
                bool supportDecal = material.GetFloat(kSupportDecals) > 0.0f;

                if (supportDecal)
                {
                    // Update material render queue to be in Decal render queue based on the value of decal property (see HDRenderQueue.cs)
                    if (material.renderQueue == ((int)UnityEngine.Rendering.RenderQueue.Geometry))
                    {
                        material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Geometry + 225;
                    }
                    else if (material.renderQueue == ((int)UnityEngine.Rendering.RenderQueue.AlphaTest))
                    {
                        material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest + 25;
                    }
                }
            }

            HDShaderUtils.ResetMaterialKeywords(material);
        }
Ejemplo n.º 10
0
 static void AlphaToMaskUIFix(Material material, HDShaderUtils.ShaderID id)
 {
     if (material.HasProperty(kAlphaToMask) && material.HasProperty(kAlphaToMaskInspector))
     {
         material.SetFloat(kAlphaToMaskInspector, material.GetFloat(kAlphaToMask));
         HDShaderUtils.ResetMaterialKeywords(material);
     }
 }
        public override void Convert(Material srcMaterial, Material dstMaterial)
        {
            //dstMaterial.hideFlags = HideFlags.DontUnloadUnusedAsset;

            base.Convert(srcMaterial, dstMaterial);

            HDShaderUtils.ResetMaterialKeywords(dstMaterial);
        }
Ejemplo n.º 12
0
        void OnPostprocessMaterial(Material material)
        {
            if (!HDShaderUtils.IsHDRPShader(material.shader, upgradable: true))
            {
                return;
            }

            HDShaderUtils.ResetMaterialKeywords(material);
        }
Ejemplo n.º 13
0
 static void ForceForwardEmissiveForDeferred(Material material, HDShaderUtils.ShaderID id)
 {
     // Force Forward emissive for deferred pass is only setup for Lit shader
     if (id == HDShaderUtils.ShaderID.SG_Lit || id == HDShaderUtils.ShaderID.Lit || id == HDShaderUtils.ShaderID.LitTesselation ||
         id == HDShaderUtils.ShaderID.LayeredLit || id == HDShaderUtils.ShaderID.LayeredLitTesselation)
     {
         HDShaderUtils.ResetMaterialKeywords(material);
     }
 }
Ejemplo n.º 14
0
        //example migration method, remove it after first real migration
        //static void EmissiveIntensityToColor(Material material, ShaderID id)
        //{
        //    switch(id)
        //    {
        //        case ShaderID.Lit:
        //        case ShaderID.LitTesselation:
        //            var emissiveIntensity = material.GetFloat("_EmissiveIntensity");
        //            var emissiveColor = Color.black;
        //            if (material.HasProperty("_EmissiveColor"))
        //                emissiveColor = material.GetColor("_EmissiveColor");
        //            emissiveColor *= emissiveIntensity;
        //            emissiveColor.a = 1.0f;
        //            material.SetColor("_EmissiveColor", emissiveColor);
        //            material.SetColor("_EmissionColor", Color.white);
        //            break;
        //    }
        //}
        //
        //static void Serialization_API_Usage(Material material, ShaderID id)
        //{
        //    switch(id)
        //    {
        //        case ShaderID.Unlit:
        //            var serializedObject = new SerializedObject(material);
        //            AddSerializedInt(serializedObject, "former", 42);
        //            RenameSerializedScalar(serializedObject, "former", "new");
        //            Debug.Log(GetSerializedInt(serializedObject, "new"));
        //            RemoveSerializedInt(serializedObject, "new");
        //            serializedObject.ApplyModifiedProperties();
        //            break;
        //    }
        //}

        static void ZWriteForTransparent(Material material, HDShaderUtils.ShaderID id)
        {
            // For transparent materials, the ZWrite property that is now used is _TransparentZWrite.
            if (material.GetSurfaceType() == SurfaceType.Transparent)
            {
                material.SetFloat(kTransparentZWrite, material.GetZWrite() ? 1.0f : 0.0f);
            }

            HDShaderUtils.ResetMaterialKeywords(material);
        }
Ejemplo n.º 15
0
        static void OnShaderGraphSaved(Shader shader, object saveContext)
        {
            // In case the shader is not HDRP
            if (!(saveContext is HDSaveContext hdSaveContext))
            {
                return;
            }

            HDRenderPipeline.currentPipeline.ResetPathTracing();

            if (!hdSaveContext.updateMaterials)
            {
                return;
            }

            // Iterate all Materials
            string[] materialGuids = AssetDatabase.FindAssets(kMaterialFilter);
            try
            {
                for (int i = 0, length = materialGuids.Length; i < length; i++)
                {
                    // Only update progress bar every 10 materials
                    if (i % 10 == 9)
                    {
                        EditorUtility.DisplayProgressBar(
                            "Checking material dependencies...",
                            $"{i} / {length} materials.",
                            i / (float)(length - 1));
                    }

                    // Get Material object
                    string   materialPath = AssetDatabase.GUIDToAssetPath(materialGuids[i]);
                    Material material     = AssetDatabase.LoadAssetAtPath <Material>(materialPath);

                    // Reset keywords
                    if (material.shader.name == shader.name)
                    {
                        HDShaderUtils.ResetMaterialKeywords(material);
                    }

                    material = null;

                    // Free the materials every 200 iterations, on big project loading all materials in memory can lead to a crash
                    if ((i % 200 == 0) && i != 0)
                    {
                        EditorUtility.UnloadUnusedAssetsImmediate(true);
                    }
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
                EditorUtility.UnloadUnusedAssetsImmediate(true);
            }
        }
        void DrawShaderGraphGUI()
        {
            // Filter out properties we don't want to draw:
            PropertiesDefaultGUI(properties);

            // If we change a property in a shadergraph, we trigger a material keyword reset
            if (CheckPropertyChanged(properties))
            {
                foreach (var material in materials)
                {
                    HDShaderUtils.ResetMaterialKeywords(material);
                }
            }

            if (properties.Length > 0)
            {
                EditorGUILayout.Space();
            }

            if ((m_Features & Features.DiffusionProfileAsset) != 0)
            {
                DrawDiffusionProfileUI();
            }

            if ((m_Features & Features.EnableInstancing) != 0)
            {
                materialEditor.EnableInstancingField();
            }

            if ((m_Features & Features.DoubleSidedGI) != 0)
            {
                // If the shader graph have a double sided flag, then we don't display this field.
                // The double sided GI value will be synced with the double sided property during the SetupBaseUnlitKeywords()
                if (!materials[0].HasProperty(kDoubleSidedEnable))
                {
                    materialEditor.DoubleSidedGIField();
                }
            }

            if ((m_Features & Features.EmissionGI) != 0)
            {
                DrawEmissionGI();
            }

            if ((m_Features & Features.MotionVector) != 0)
            {
                DrawMotionVectorToggle();
            }

            if ((m_Features & Features.ShadowMatte) != 0 && materials[0].HasProperty(kShadowMatteFilter))
            {
                DrawShadowMatteToggle();
            }
        }
        internal static void ForceForwardEmissiveOnMaterialDisableInScene()
        {
            var materials = Resources.FindObjectsOfTypeAll <Material>();

            foreach (var material in materials)
            {
                if (material.HasProperty(HDMaterialProperties.kForceForwardEmissive))
                {
                    material.SetInt(HDMaterialProperties.kForceForwardEmissive, 0);
                    HDShaderUtils.ResetMaterialKeywords(material);
                }
            }
        }
Ejemplo n.º 18
0
 static void ExposeRefraction(Material material, HDShaderUtils.ShaderID id)
 {
     // Lit SG now have a shader feature for refraction instead of an hardcoded material
     if (id == HDShaderUtils.ShaderID.SG_Lit)
     {
         // Sync the default refraction model from the shader graph to the shader
         // We need to do this because the material may already have a refraction model information (from the Lit)
         // In order to not break the rendering of the material, we patch the refraction model:
         if (material.HasProperty(kRefractionModel))
         {
             var refractionModel = material.shader.GetPropertyDefaultFloatValue(material.shader.FindPropertyIndex(kRefractionModel));
             material.SetFloat(kRefractionModel, refractionModel);
         }
         HDShaderUtils.ResetMaterialKeywords(material);
     }
 }
        internal static void ForceForwardEmissiveOnMaterialEnableInSelection()
        {
            var selection = UnityEditor.Selection.objects;

            foreach (var obj in selection)
            {
                if (obj is Material material)
                {
                    if (material.HasProperty(HDMaterialProperties.kForceForwardEmissive))
                    {
                        material.SetInt(HDMaterialProperties.kForceForwardEmissive, 1);
                        HDShaderUtils.ResetMaterialKeywords(material);
                    }
                }
            }
        }
        static void OnShaderGraphSaved(Shader shader, object saveContext)
        {
            // In case the shader is not HDRP
            if (!(saveContext is HDSaveContext hdSaveContext))
            {
                return;
            }

            HDRenderPipeline.currentPipeline?.ResetPathTracing();

            if (!hdSaveContext.updateMaterials)
            {
                return;
            }

            // Iterate over all loaded Materials
            Material[] materials = Resources.FindObjectsOfTypeAll <Material>();
            try
            {
                for (int i = 0, length = materials.Length; i < length; i++)
                {
                    // Only update progress bar every 10 materials
                    if (i % 10 == 9)
                    {
                        EditorUtility.DisplayProgressBar(
                            "Checking material dependencies...",
                            $"{i} / {length} materials.",
                            i / (float)(length - 1));
                    }

                    // Reset keywords
                    if (materials[i].shader.name == shader.name)
                    {
                        HDShaderUtils.ResetMaterialKeywords(materials[i]);
                    }
                }
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
        }
Ejemplo n.º 21
0
        static void ShaderGraphStack(Material material, HDShaderUtils.ShaderID id)
        {
            Shader shader = material.shader;

            if (shader.IsShaderGraph())
            {
                if (shader.TryGetMetadataOfType <HDMetadata>(out var obj))
                {
                    // Material coming from old cross pipeline shader (Unlit and PBR) are not synchronize correctly with their
                    // shader graph. This code below ensure it is
                    if (obj.migrateFromOldCrossPipelineSG) // come from PBR or Unlit cross pipeline SG?
                    {
                        var defaultProperties = new Material(material.shader);

                        foreach (var floatToSync in s_ShadergraphStackFloatPropertiesToSynchronize)
                        {
                            if (material.HasProperty(floatToSync))
                            {
                                material.SetFloat(floatToSync, defaultProperties.GetFloat(floatToSync));
                            }
                        }

                        defaultProperties = null;

                        // Postprocess now that material is correctly sync
                        bool isTransparent = material.HasProperty("_SurfaceType") && material.GetFloat("_SurfaceType") > 0.0f;
                        bool alphaTest     = material.HasProperty("_AlphaCutoffEnable") && material.GetFloat("_AlphaCutoffEnable") > 0.0f;

                        material.renderQueue = isTransparent ? (int)HDRenderQueue.Priority.Transparent :
                                               alphaTest ? (int)HDRenderQueue.Priority.OpaqueAlphaTest : (int)HDRenderQueue.Priority.Opaque;

                        material.SetFloat("_RenderQueueType", isTransparent ? (float)HDRenderQueue.RenderQueueType.Transparent : (float)HDRenderQueue.RenderQueueType.Opaque);
                    }
                }
            }

            HDShaderUtils.ResetMaterialKeywords(material);
        }
Ejemplo n.º 22
0
        static void ResetAllMaterialAssetsKeywords(float progressScale, float progressOffset)
        {
            var matIds = AssetDatabase.FindAssets("t:Material", new string[] { "Assets" }); // do not include packages

            bool VCSEnabled = (UnityEditor.VersionControl.Provider.enabled && UnityEditor.VersionControl.Provider.isActive);

            for (int i = 0, length = matIds.Length; i < length; i++)
            {
                var path = AssetDatabase.GUIDToAssetPath(matIds[i]);
                var mat  = AssetDatabase.LoadAssetAtPath <Material>(path);

                EditorUtility.DisplayProgressBar(
                    "Setup material asset's Keywords...",
                    string.Format("{0} / {1} materials cleaned.", i, length),
                    (i / (float)(length - 1)) * progressScale + progressOffset);

                CoreEditorUtils.CheckOutFile(VCSEnabled, mat);
                var h = Debug.unityLogger.logHandler;
                Debug.unityLogger.logHandler = new UnityContextualLogHandler(mat);
                HDShaderUtils.ResetMaterialKeywords(mat);
                Debug.unityLogger.logHandler = h;
            }
        }
Ejemplo n.º 23
0
        static void Execute(CommandLineAction action)
        {
            switch (action.operation)
            {
            case CommandLineOperation.ResetMaterialKeywords:
            {
                Console.WriteLine("[HDEditorCLI][ResetMaterialKeywords] Starting material reset");

                var matIds = AssetDatabase.FindAssets("t:Material");

                for (int i = 0, length = matIds.Length; i < length; i++)
                {
                    var path = AssetDatabase.GUIDToAssetPath(matIds[i]);
                    var mat  = AssetDatabase.LoadAssetAtPath <Material>(path);

                    if (HDShaderUtils.ResetMaterialKeywords(mat))
                    {
                        Console.WriteLine("[HDEditorCLI][ResetMaterialKeywords] " + path);
                    }
                }
                break;
            }
            }
        }
Ejemplo n.º 24
0
 static void StencilRefactor(Material material, HDShaderUtils.ShaderID id)
 {
     HDShaderUtils.ResetMaterialKeywords(material);
 }
Ejemplo n.º 25
0
 public static void HDSpeedTree8MaterialFinalizer(Material mat)
 {
     SetHDSpeedTree8Defaults(mat);
     HDShaderUtils.ResetMaterialKeywords(mat);
 }
        public override void Convert(Material srcMaterial, Material dstMaterial)
        {
            base.Convert(srcMaterial, dstMaterial);

            HDShaderUtils.ResetMaterialKeywords(dstMaterial);
        }
Ejemplo n.º 27
0
        static void ExposedDecalInputsFromShaderGraph(Material material, HDShaderUtils.ShaderID id)
        {
            if (id == HDShaderUtils.ShaderID.Decal)
            {
                // In order for the new properties (kAffectsAlbedo...) to be taken into account, we need to make it dirty so that the parameter is created first
                HDShaderUtils.ResetMaterialKeywords(material);

                var serializedMaterial = new SerializedObject(material);

                // Note: the property must not exist in the .shader for RemoveSerializedFloat to work (otherwise it will be re-added)
                const string kAlbedoMode = "_AlbedoMode";
                float        albedoMode  = 1.0f;
                if (TryFindProperty(serializedMaterial, kAlbedoMode, SerializedType.Float, out var propertyAlbedoMode, out _, out _))
                {
                    albedoMode = propertyAlbedoMode.floatValue;
                    RemoveSerializedFloat(serializedMaterial, kAlbedoMode);
                }

                // For normal map we don't remove the property _NormalMap but just check if there is a texture assign and then enable _AffectNormal
                const string kNormalMap = "_NormalMap";
                float        normalMap  = 0.0f;
                if (TryFindProperty(serializedMaterial, kNormalMap, SerializedType.Texture, out var propertyNormalTexture, out _, out _))
                {
                    normalMap = propertyNormalTexture.FindPropertyRelative("m_Texture").objectReferenceValue != null ? 1.0f : 0.0f;
                }

                // For normal map we don't remove the property _NormalMap but just check if there is a texture assign and then enable _AffectNormal
                const string kMaskMap = "_MaskMap";
                float        maskMap  = 0.0f;
                if (TryFindProperty(serializedMaterial, kMaskMap, SerializedType.Texture, out var propertyMaskMapTexture, out _, out _))
                {
                    maskMap = propertyMaskMapTexture.FindPropertyRelative("m_Texture").objectReferenceValue != null ? 1.0f : 0.0f;
                }

                const string kMaskmapMetal = "_MaskmapMetal";
                float        maskMapMetal  = 0.0f;
                if (TryFindProperty(serializedMaterial, kMaskmapMetal, SerializedType.Float, out var propertyMaskMapMetal, out _, out _))
                {
                    maskMapMetal = propertyMaskMapMetal.floatValue;
                    RemoveSerializedFloat(serializedMaterial, kMaskmapMetal);
                }

                const string kMaskmapAO = "_MaskmapAO";
                float        maskMapAO  = 0.0f;
                if (TryFindProperty(serializedMaterial, kMaskmapAO, SerializedType.Float, out var propertyMaskMapAO, out _, out _))
                {
                    maskMapAO = propertyMaskMapAO.floatValue;
                    RemoveSerializedFloat(serializedMaterial, kMaskmapAO);
                }

                const string kMaskmapSmoothness = "_MaskmapSmoothness";
                float        maskMapSmoothness  = 0.0f;
                if (TryFindProperty(serializedMaterial, kMaskmapSmoothness, SerializedType.Float, out var propertyMaskMapSmoothness, out _, out _))
                {
                    maskMapSmoothness = propertyMaskMapSmoothness.floatValue;
                    RemoveSerializedFloat(serializedMaterial, kMaskmapSmoothness);
                }

                const string kEmissive = "_Emissive";
                float        emissive  = 0.0f;
                if (TryFindProperty(serializedMaterial, kEmissive, SerializedType.Float, out var propertyEmissive, out _, out _))
                {
                    emissive = propertyEmissive.floatValue;
                    RemoveSerializedFloat(serializedMaterial, kEmissive);
                }

                // Not used anymore, just removed
                const string kMaskBlendMode = "_MaskBlendMode";
                if (TryFindProperty(serializedMaterial, kMaskBlendMode, SerializedType.Float, out var propertyUnused, out _, out _))
                {
                    RemoveSerializedFloat(serializedMaterial, kMaskBlendMode);
                }

                serializedMaterial.ApplyModifiedProperties();

                // Now apply old value to new properties
                const string kAffectAlbedo = "_AffectAlbedo";
                material.SetFloat(kAffectAlbedo, albedoMode);

                const string kAffectNormal = "_AffectNormal";
                material.SetFloat(kAffectNormal, normalMap);

                const string kAffectSmoothness = "_AffectSmoothness";
                material.SetFloat(kAffectSmoothness, maskMapSmoothness * maskMap);

                const string kAffectMetal = "_AffectMetal";
                material.SetFloat(kAffectMetal, maskMapMetal * maskMap);

                const string kAffectAO = "_AffectAO";
                material.SetFloat(kAffectAO, maskMapAO * maskMap);

                const string kAffectEmission = "_AffectEmission";
                material.SetFloat(kAffectEmission, emissive);

                // We can't erase obsolete disabled pass from already existing Material, so we need to re-enable all of them
                const string s_MeshDecalsMStr            = "DBufferMesh_M";
                const string s_MeshDecalsSStr            = "DBufferMesh_S";
                const string s_MeshDecalsMSStr           = "DBufferMesh_MS";
                const string s_MeshDecalsAOStr           = "DBufferMesh_AO";
                const string s_MeshDecalsMAOStr          = "DBufferMesh_MAO";
                const string s_MeshDecalsAOSStr          = "DBufferMesh_AOS";
                const string s_MeshDecalsMAOSStr         = "DBufferMesh_MAOS";
                const string s_MeshDecals3RTStr          = "DBufferMesh_3RT";
                const string s_MeshDecalsForwardEmissive = "Mesh_Emissive";

                material.SetShaderPassEnabled(s_MeshDecalsMStr, true);
                material.SetShaderPassEnabled(s_MeshDecalsSStr, true);
                material.SetShaderPassEnabled(s_MeshDecalsMSStr, true);
                material.SetShaderPassEnabled(s_MeshDecalsAOStr, true);
                material.SetShaderPassEnabled(s_MeshDecalsMAOStr, true);
                material.SetShaderPassEnabled(s_MeshDecalsAOSStr, true);
                material.SetShaderPassEnabled(s_MeshDecalsMAOSStr, true);
                material.SetShaderPassEnabled(s_MeshDecals3RTStr, true);
                material.SetShaderPassEnabled(s_MeshDecalsForwardEmissive, true);
            }

            if (id == HDShaderUtils.ShaderID.SG_Decal)
            {
                // We can't erase obsolete disabled pass from already existing Material, so we need to re-enable all of them
                const string s_ShaderGraphMeshDecals4RT            = "ShaderGraph_DBufferMesh4RT";
                const string s_ShaderGraphMeshDecals3RT            = "ShaderGraph_DBufferMesh3RT";
                const string s_ShaderGraphMeshDecalForwardEmissive = "ShaderGraph_MeshEmissive";

                material.SetShaderPassEnabled(s_ShaderGraphMeshDecals4RT, true);
                material.SetShaderPassEnabled(s_ShaderGraphMeshDecals3RT, true);
                material.SetShaderPassEnabled(s_ShaderGraphMeshDecalForwardEmissive, true);
            }

            if (id == HDShaderUtils.ShaderID.Decal || id == HDShaderUtils.ShaderID.SG_Decal)
            {
                HDShaderUtils.ResetMaterialKeywords(material);
            }
        }
        public void OnPreprocessMaterialDescription(MaterialDescription description, Material material, AnimationClip[] clips)
        {
            var pipelineAsset = GraphicsSettings.currentRenderPipeline;

            if (!pipelineAsset || pipelineAsset.GetType() != typeof(HDRenderPipelineAsset))
            {
                return;
            }

            var lowerCaseExtension = Path.GetExtension(assetPath).ToLower();

            if (lowerCaseExtension != ".fbx" && lowerCaseExtension != ".obj" && lowerCaseExtension != ".dae" && lowerCaseExtension != ".obj" && lowerCaseExtension != ".blend" && lowerCaseExtension != ".mb" && lowerCaseExtension != ".ma" && lowerCaseExtension != ".max")
            {
                return;
            }

            var shader = AssetDatabase.LoadAssetAtPath <Shader>(k_ShaderPath);

            if (shader == null)
            {
                return;
            }

            material.shader = shader;

            Vector4 vectorProperty;
            float   floatProperty;
            TexturePropertyDescription textureProperty;

            bool isTransparent = false;

            float opacity;
            float transparencyFactor;

            if (!description.TryGetProperty("Opacity", out opacity))
            {
                if (description.TryGetProperty("TransparencyFactor", out transparencyFactor))
                {
                    opacity = transparencyFactor == 1.0f ? 1.0f : 1.0f - transparencyFactor;
                }
                if (opacity == 1.0f && description.TryGetProperty("TransparentColor", out vectorProperty))
                {
                    opacity = vectorProperty.x == 1.0f ? 1.0f : 1.0f - vectorProperty.x;
                }
            }
            if (opacity < 1.0f || (opacity == 1.0f && description.TryGetProperty("TransparentColor", out textureProperty)))
            {
                isTransparent = true;
            }
            else if (description.HasAnimationCurve("TransparencyFactor") || description.HasAnimationCurve("TransparentColor"))
            {
                isTransparent = true;
            }

            if (isTransparent)
            {
                material.SetFloat("_BlendMode", (float)BlendMode.Alpha);
                material.SetFloat("_EnableBlendModePreserveSpecularLighting", 1.0f);
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
                material.SetFloat("_SurfaceType", (float)SurfaceType.Transparent);
                material.SetFloat("_Cutoff", .0f);
                material.SetFloat("_AlphaCutoffEnable", 1.0f);
                material.SetFloat("_AlphaCutoff", .0f);
                material.SetFloat("_AlphaCutoffShadow", 1.0f);
                material.SetFloat("_UseShadowThreshold", 1.0f);
            }
            else
            {
                material.renderQueue = -1;
            }

            if (description.TryGetProperty("ReflectionFactor", out floatProperty))
            {
                material.SetFloat("_Metallic", floatProperty);
            }

            if (description.TryGetProperty("DiffuseColor", out textureProperty) && textureProperty.texture != null)
            {
                Color diffuseColor = new Color(1.0f, 1.0f, 1.0f, 1.0f);
                if (description.TryGetProperty("DiffuseFactor", out floatProperty))
                {
                    diffuseColor *= floatProperty;
                }
                diffuseColor.a = opacity;

                SetMaterialTextureProperty("_BaseColorMap", material, textureProperty);
                material.SetColor("_BaseColor", diffuseColor);
            }
            else if (description.TryGetProperty("DiffuseColor", out vectorProperty))
            {
                Color diffuseColor = vectorProperty;
                if (description.TryGetProperty("DiffuseFactor", out floatProperty))
                {
                    diffuseColor *= floatProperty;
                }
                diffuseColor.a = opacity;
                material.SetColor("_BaseColor", PlayerSettings.colorSpace == ColorSpace.Linear ? diffuseColor.gamma : diffuseColor);
            }

            if (description.TryGetProperty("Bump", out textureProperty) && textureProperty.texture != null)
            {
                SetMaterialTextureProperty("_BumpMap", material, textureProperty);

                if (description.TryGetProperty("BumpFactor", out floatProperty))
                {
                    material.SetFloat("_BumpScale", floatProperty);
                }
            }
            else if (description.TryGetProperty("NormalMap", out textureProperty) && textureProperty.texture != null)
            {
                SetMaterialTextureProperty("_BumpMap", material, textureProperty);

                if (description.TryGetProperty("BumpFactor", out floatProperty))
                {
                    material.SetFloat("_BumpScale", floatProperty);
                }
            }

            if (description.TryGetProperty("EmissiveColor", out textureProperty))
            {
                Color emissiveColor = new Color(1.0f, 1.0f, 1.0f, 1.0f);

                material.SetColor("_EmissionColor", emissiveColor);
                material.SetColor("_EmissiveColor", emissiveColor);
                SetMaterialTextureProperty("_EmissionMap", material, textureProperty);

                if (description.TryGetProperty("EmissiveFactor", out floatProperty) && floatProperty > 0.0f)
                {
                    material.EnableKeyword("_EMISSION");
                    material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;
                }
            }
            else if (description.TryGetProperty("EmissiveColor", out vectorProperty) && vectorProperty.magnitude > vectorProperty.w ||
                     description.HasAnimationCurve("EmissiveColor.x"))
            {
                if (description.TryGetProperty("EmissiveFactor", out floatProperty))
                {
                    vectorProperty *= floatProperty;
                }

                material.SetColor("_EmissionColor", vectorProperty);
                material.SetColor("_EmissiveColor", vectorProperty);
                if (floatProperty > 0.0f)
                {
                    material.EnableKeyword("_EMISSION");
                    material.globalIlluminationFlags |= MaterialGlobalIlluminationFlags.RealtimeEmissive;
                }
            }

            material.SetFloat("_Glossiness", 0.0f);

            if (PlayerSettings.colorSpace == ColorSpace.Linear)
            {
                RemapAndTransformColorCurves(description, clips, "DiffuseColor", "_BaseColor", ConvertFloatLinearToGamma);
            }
            else
            {
                RemapColorCurves(description, clips, "DiffuseColor", "_BaseColor");
            }

            RemapTransparencyCurves(description, clips);

            RemapColorCurves(description, clips, "EmissiveColor", "_EmissionColor");
            RemapColorCurves(description, clips, "EmissiveColor", "_EmissiveColor");

            HDShaderUtils.ResetMaterialKeywords(material);
        }
Ejemplo n.º 29
0
        static void RenderQueueUpgrade(Material material, HDShaderUtils.ShaderID id)
        {
            // In order for the ray tracing keyword to be taken into account, we need to make it dirty so that the parameter is created first
            HDShaderUtils.ResetMaterialKeywords(material);

            // Replace previous ray tracing render queue for opaque to regular opaque with raytracing
            if (material.renderQueue == ((int)UnityEngine.Rendering.RenderQueue.GeometryLast + 20))
            {
                material.renderQueue = (int)HDRenderQueue.Priority.Opaque;
                material.SetFloat(kRayTracing, 1.0f);
            }
            // Replace previous ray tracing render queue for transparent to regular transparent with raytracing
            else if (material.renderQueue == 3900)
            {
                material.renderQueue = (int)HDRenderQueue.Priority.Transparent;
                material.SetFloat(kRayTracing, 1.0f);
            }

            // For shader graphs, there is an additional pass we need to do
            if (material.HasProperty("_RenderQueueType"))
            {
                int renderQueueType = (int)material.GetFloat("_RenderQueueType");
                switch (renderQueueType)
                {
                // This was ray tracing opaque, should go back to opaque
                case 3:
                {
                    renderQueueType = 1;
                }
                break;

                // If it was in the transparent range, reduce it by 1
                case 4:
                case 5:
                case 6:
                case 7:
                {
                    renderQueueType = renderQueueType - 1;
                }
                break;

                // If it was in the ray tracing transparent, should go back to transparent
                case 8:
                {
                    renderQueueType = renderQueueType - 4;
                }
                break;

                // If it was in overlay should be reduced by 2
                case 10:
                {
                    renderQueueType = renderQueueType - 2;
                }
                break;

                // background, opaque and AfterPostProcessOpaque are not impacted
                default:
                    break;
                }


                // Push it back to the material
                material.SetFloat("_RenderQueueType", (float)renderQueueType);
            }

            HDShaderUtils.ResetMaterialKeywords(material);
        }
Ejemplo n.º 30
0
        static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
        {
            foreach (var asset in importedAssets)
            {
                if (!asset.ToLowerInvariant().EndsWith(".mat"))
                {
                    continue;
                }

                var material = (Material)AssetDatabase.LoadAssetAtPath(asset, typeof(Material));
                if (!HDShaderUtils.IsHDRPShader(material.shader, upgradable: true))
                {
                    continue;
                }

                HDShaderUtils.ShaderID id  = HDShaderUtils.GetShaderEnumFromShader(material.shader);
                var          latestVersion = k_Migrations.Length;
                var          wasUpgraded   = false;
                var          assetVersions = AssetDatabase.LoadAllAssetsAtPath(asset);
                AssetVersion assetVersion  = null;
                foreach (var subAsset in assetVersions)
                {
                    if (subAsset != null && subAsset.GetType() == typeof(AssetVersion))
                    {
                        assetVersion = subAsset as AssetVersion;
                        break;
                    }
                }

                //subasset not found
                if (!assetVersion)
                {
                    wasUpgraded            = true;
                    assetVersion           = ScriptableObject.CreateInstance <AssetVersion>();
                    assetVersion.hideFlags = HideFlags.HideInHierarchy | HideFlags.HideInInspector | HideFlags.NotEditable;
                    if (s_CreatedAssets.Contains(asset))
                    {
                        //just created
                        assetVersion.version = latestVersion;
                        s_CreatedAssets.Remove(asset);

                        //[TODO: remove comment once fixed]
                        //due to FB 1175514, this not work. It is being fixed though.
                        //delayed call of the following work in some case and cause infinite loop in other cases.
                        AssetDatabase.AddObjectToAsset(assetVersion, asset);

                        // Init material in case it's used before an inspector window is opened
                        HDShaderUtils.ResetMaterialKeywords(material);
                    }
                    else
                    {
                        //asset exist prior migration
                        assetVersion.version = 0;
                        AssetDatabase.AddObjectToAsset(assetVersion, asset);
                    }
                }

                //upgrade
                while (assetVersion.version < latestVersion)
                {
                    k_Migrations[assetVersion.version](material, id);
                    assetVersion.version++;
                    wasUpgraded = true;
                }

                if (wasUpgraded)
                {
                    EditorUtility.SetDirty(assetVersion);
                    s_ImportedAssetThatNeedSaving.Add(asset);
                    s_NeedsSavingAssets = true;
                }
            }
        }