public override void OnInspectorGUI()
            {
                //Drop down list is all these
                MaterialPerInstanceProperties materialPerInstanceProperties = target as MaterialPerInstanceProperties;

                if (materialPerInstanceProperties == null)
                {
                    return;
                }

                GUILayout.Label("Per Instance Properties", EditorStyles.boldLabel);
                EditorGUILayout.PropertyField(serializedObject.FindProperty("_renderer"));

                if (materialPerInstanceProperties._renderer != null)
                {
                    _properties      = MaterialEditor.GetMaterialProperties(materialPerInstanceProperties._renderer.sharedMaterials);
                    _propertiesNames = new GUIContent[_properties.Length];
                    for (int i = 0; i < _properties.Length; i++)
                    {
                        _propertiesNames[i] = new GUIContent(_properties[i].displayName);
                    }

                    GUILayout.Space(3f);

                    _propertiesList.displayAdd    = _properties.Length > 0;
                    _propertiesList.displayRemove = true;
                    _propertiesList.list          = GetProperties(materialPerInstanceProperties);
                    _propertiesList.DoLayoutList();
                    SetProperties(materialPerInstanceProperties, _propertiesList.list);
                }

                serializedObject.ApplyModifiedProperties();
            }
예제 #2
0
    static void DeleteUnusedProperties(Material material, string path)
    {
        var newMaterial = new Material(material.shader);

        newMaterial.name                    = material.name;
        newMaterial.renderQueue             = (material.shader.renderQueue == material.renderQueue) ? -1 : material.renderQueue;
        newMaterial.enableInstancing        = material.enableInstancing;
        newMaterial.doubleSidedGI           = material.doubleSidedGI;
        newMaterial.globalIlluminationFlags = material.globalIlluminationFlags;
        newMaterial.hideFlags               = material.hideFlags;
        newMaterial.shaderKeywords          = material.shaderKeywords;

        var properties = MaterialEditor.GetMaterialProperties(new Material[] { material });

        for (int i0 = 0; i0 < properties.Length; ++i0)
        {
            SetPropertyToMaterial(newMaterial, properties[i0], null);
        }

        string tempPath = AssetDatabase.GenerateUniqueAssetPath(path);

        AssetDatabase.CreateAsset(newMaterial, tempPath);
        FileUtil.ReplaceFile(tempPath, path);
        AssetDatabase.DeleteAsset(tempPath);
    }
예제 #3
0
        /// <summary>
        /// Copy Shader properties from source to destination material.
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static void CopyMaterialProperties(Material source, Material destination)
        {
            MaterialProperty[] source_prop = MaterialEditor.GetMaterialProperties(new Material[] { source });

            for (int i = 0; i < source_prop.Length; i++)
            {
                int property_ID = Shader.PropertyToID(source_prop[i].name);
                if (destination.HasProperty(property_ID))
                {
                    //Debug.Log(source_prop[i].name + "  Type:" + ShaderUtil.GetPropertyType(source.shader, i));
                    switch (ShaderUtil.GetPropertyType(source.shader, i))
                    {
                    case ShaderUtil.ShaderPropertyType.Color:
                        destination.SetColor(property_ID, source.GetColor(property_ID));
                        break;

                    case ShaderUtil.ShaderPropertyType.Float:
                        destination.SetFloat(property_ID, source.GetFloat(property_ID));
                        break;

                    case ShaderUtil.ShaderPropertyType.Range:
                        destination.SetFloat(property_ID, source.GetFloat(property_ID));
                        break;

                    case ShaderUtil.ShaderPropertyType.TexEnv:
                        destination.SetTexture(property_ID, source.GetTexture(property_ID));
                        break;

                    case ShaderUtil.ShaderPropertyType.Vector:
                        destination.SetVector(property_ID, source.GetVector(property_ID));
                        break;
                    }
                }
            }
        }
예제 #4
0
        public static object GetMaterialPropertyValue(SearchSelectorArgs args)
        {
            if (!(args["propertyPath"] is string propertyPath))
            {
                return(null);
            }

            var item     = args.current;
            var material = item.ToObject <Material>();

            if (!material)
            {
                return(null);
            }

            var matProp = MaterialEditor.GetMaterialProperty(new Object[] { material }, propertyPath);

            if (matProp == null || matProp.name == null)
            {
                var materialProperties = MaterialEditor.GetMaterialProperties(new Object[] { material });
                for (var i = 0; i < materialProperties.Length; i++)
                {
                    if (!materialProperties[i].name.EndsWith(propertyPath, System.StringComparison.OrdinalIgnoreCase))
                    {
                        continue;
                    }
                    matProp = materialProperties[i];
                    break;
                }
            }

            return(GetMaterialPropertyValue(matProp));
        }
예제 #5
0
    public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
    {
        base.AssignNewShaderToMaterial(material, oldShader, newShader);

        if (oldShader == null || !oldShader.name.Contains("Legacy Shaders/"))
        {
            return;
        }

        BlendMode blendMode = BlendMode.Opaque;

        if (oldShader.name.Contains("/Transparent/Cutout/"))
        {
            blendMode = BlendMode.Cutout;
        }
        else if (oldShader.name.Contains("/Transparent/"))
        {
            // NOTE: legacy shaders did not provide physically based transparency
            // therefore Fade mode
            blendMode = BlendMode.Fade;
        }
        material.SetFloat("_Mode", ( float )blendMode);

        DetermineWorkflow(MaterialEditor.GetMaterialProperties(new Material[] { material }));
        MaterialChanged(material, m_WorkflowMode);
    }
예제 #6
0
        public PresetHandler(Shader s)
        {
            Material m = new Material(s);

            MaterialProperty[] props = MaterialEditor.GetMaterialProperties(new Material[] { m });
            testPresetsChanged(props);
        }
예제 #7
0
    /// <summary>
    /// マテリアルの不要なプロパティを削除する
    /// </summary>
    /// <param name="mat">対象のマテリアル</param>
    /// <param name="path">マテリアルが保存されているパス</param>
    public static void DeleteUnusedProperties(Material mat, string path)
    {
        // 不要なパラメータを削除する方法として、新しいマテリアルを作ってそこに必要なパラメータだけコピーする
        var newMat = new Material(mat.shader);

        // パラメータのコピー
        newMat.name                    = mat.name;
        newMat.renderQueue             = (mat.shader.renderQueue == mat.renderQueue) ? -1 : mat.renderQueue;
        newMat.enableInstancing        = mat.enableInstancing;
        newMat.doubleSidedGI           = mat.doubleSidedGI;
        newMat.globalIlluminationFlags = mat.globalIlluminationFlags;
        newMat.hideFlags               = mat.hideFlags;
        newMat.shaderKeywords          = mat.shaderKeywords;

        // Propertiesのコピー
        var properties = MaterialEditor.GetMaterialProperties(new Material[] { mat });

        for (int pIdx = 0; pIdx < properties.Length; ++pIdx)
        {
            SetPropertyToMaterial(newMat, properties[pIdx]);
        }

        // GUIDが変わらないように置き換える
        string tempPath = path + "_temp";

        AssetDatabase.CreateAsset(newMat, tempPath);
        FileUtil.ReplaceFile(tempPath, path);
        AssetDatabase.DeleteAsset(tempPath);
    }
예제 #8
0
        protected IEnumerable <PortData> GetMaterialPortDatas(Material material)
        {
            if (material == null)
            {
                yield break;
            }

            var currentDimension = rtSettings.GetTextureDimension(graph);

            foreach (var prop in MaterialEditor.GetMaterialProperties(new [] { material }))
            {
                if (prop.flags == MaterialProperty.PropFlags.HideInInspector ||
                    prop.flags == MaterialProperty.PropFlags.NonModifiableTextureData ||
                    prop.flags == MaterialProperty.PropFlags.PerRendererData)
                {
                    continue;
                }

                if (!PropertySupportsDimension(prop, currentDimension))
                {
                    continue;
                }

                yield return(new PortData {
                    identifier = prop.name,
                    displayName = prop.displayName,
                    displayType = GetPropertyType(prop),
                });
            }
        }
예제 #9
0
        internal static void MaterialShaderReferences(CustomObjectIndexerTarget context, ObjectIndexer indexer)
        {
            var material = context.target as Material;

            if (material == null)
            {
                return;
            }

            if (material.shader)
            {
                var fullShaderName = material.shader.name.ToLowerInvariant();
                indexer.AddReference(context.documentIndex, fullShaderName);
            }

            if (!indexer.settings.options.properties)
            {
                return;
            }

            var properties = MaterialEditor.GetMaterialProperties(new Material[] { material });

            foreach (var property in properties)
            {
                var propertyName = property.name.ToLowerInvariant();
                if (propertyName.Length > 0 && propertyName[0] == '_')
                {
                    propertyName = propertyName.Substring(1);
                }
                switch (property.type)
                {
                case MaterialProperty.PropType.Color:
                    IndexColor(propertyName, property.colorValue, indexer, context.documentIndex);
                    break;

                case MaterialProperty.PropType.Vector:
                    IndexVector(propertyName, property.vectorValue, indexer, context.documentIndex);
                    break;

                case MaterialProperty.PropType.Float:
                    indexer.AddNumber(propertyName, property.floatValue, indexer.settings.baseScore, context.documentIndex);
                    break;

                case MaterialProperty.PropType.Range:
                    IndexVector(propertyName, property.rangeLimits, indexer, context.documentIndex);
                    break;

                case MaterialProperty.PropType.Texture:
                    if (property.textureValue)
                    {
                        indexer.AddReference(context.documentIndex, AssetDatabase.GetAssetPath(property.textureValue));
                        if (!string.IsNullOrEmpty(property.textureValue.name))
                        {
                            indexer.AddProperty(propertyName, property.textureValue.name.ToLowerInvariant(), context.documentIndex);
                        }
                    }
                    break;
                }
            }
        }
예제 #10
0
        /// <summary>
        /// Setup the material when shader is changed
        /// </summary>
        /// <param name="materialDst"></param>
        /// <param name="oldShader"></param>
        /// <param name="newShader"></param>
        protected virtual void MaterialSetup(Material materialDst, Shader oldShader, Shader newShader)
        {
            Material materialSrc = new Material(materialDst);

            MaterialProperty[] propertiesSrc = MaterialEditor.GetMaterialProperties(new Material[] { materialSrc });

            base.AssignNewShaderToMaterial(materialDst, oldShader, newShader);

            MaterialProperty[] propertiesDst = MaterialEditor.GetMaterialProperties(new Material[] { materialDst });
            FindProperties(propertiesDst);
            _particles.FindProperties(propertiesDst);
            _outline.FindProperties(propertiesDst);
            _refraction.FindProperties(propertiesDst);

            ConvertSimilarValues(propertiesSrc, materialSrc, materialDst);

            if (_outline.active)
            {
                Properties.surface.SetValue(materialDst, Surface.Opaque, Properties.alphaClipping.GetValue(materialDst));
            }
            if (_refraction.active)
            {
                Properties.surface.SetValue(materialDst, Surface.Transparent, Properties.alphaClipping.GetValue(materialDst));
            }

            UpdateKeywords();
        }
예제 #11
0
    public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
    {
        // _Emission property is lost after assigning Standard shader to the material
        // thus transfer it before assigning the new shader
        if (material.HasProperty("_Emission"))
        {
            material.SetColor("_EmissionColor", material.GetColor("_Emission"));
        }

        base.AssignNewShaderToMaterial(material, oldShader, newShader);

        if (oldShader == null || !oldShader.name.Contains("Legacy Shaders/"))
        {
            SetupMaterialWithBlendMode(material, (BlendMode)material.GetFloat("_Mode"));
            return;
        }

        BlendMode blendMode = BlendMode.Opaque;

        if (oldShader.name.Contains("/Transparent/Cutout/"))
        {
            blendMode = BlendMode.Cutout;
        }
        else if (oldShader.name.Contains("/Transparent/"))
        {
            // NOTE: legacy shaders did not provide physically based transparency
            // therefore Fade mode
            blendMode = BlendMode.Fade;
        }
        material.SetFloat("_Mode", (float)blendMode);

        DetermineWorkflow(MaterialEditor.GetMaterialProperties(new Material[] { material }));
        MaterialChanged(material, m_WorkflowMode);
    }
예제 #12
0
        // Custom property draw, we don't want things that are connected to an edge or useless like the render queue
        protected bool MaterialPropertiesGUI(Material material, bool autoLabelWidth = true)
        {
            if (material == null || material.shader == null)
            {
                return(false);
            }

            if (autoLabelWidth)
            {
                EditorGUIUtility.wideMode   = false;
                EditorGUIUtility.labelWidth = nodeTarget.nodeWidth / 3.0f;
            }

            MaterialProperty[] properties = MaterialEditor.GetMaterialProperties(new [] { material });
            var portViews = GetPortViewsFromFieldName(nameof(ShaderNode.materialInputs));

            MaterialEditor editor;

            if (!materialEditors.TryGetValue(material, out editor))
            {
                editor = materialEditors[material] = Editor.CreateEditor(material) as MaterialEditor;
                MixturePropertyDrawer.RegisterEditor(editor, this, owner.graph);
            }

            bool propertiesChanged = CheckPropertyChanged(material, properties);

            foreach (var property in properties)
            {
                if ((property.flags & (MaterialProperty.PropFlags.HideInInspector | MaterialProperty.PropFlags.PerRendererData)) != 0)
                {
                    continue;
                }

                // Retrieve the port view from the property name
                var portView = portViews?.FirstOrDefault(p => p.portData.identifier == property.name);
                if (portView != null && portView.connected)
                {
                    continue;
                }

                float h = editor.GetPropertyHeight(property, property.displayName);
                Rect  r = EditorGUILayout.GetControlRect(true, h);

                if (property.name.Contains("Vector2"))
                {
                    property.vectorValue = (Vector4)EditorGUI.Vector2Field(r, property.displayName, (Vector2)property.vectorValue);
                }
                else if (property.name.Contains("Vector3"))
                {
                    property.vectorValue = (Vector4)EditorGUI.Vector3Field(r, property.displayName, (Vector3)property.vectorValue);
                }
                else
                {
                    editor.ShaderProperty(r, property, property.displayName);
                }
            }

            return(propertiesChanged);
        }
예제 #13
0
        /// <inheritdoc />
        protected override void Setup(Object[] setTargets, Object[] setEditorTargets, Type setEditorType, IParentDrawer setParent, IInspector setInspector)
        {
            base.Setup(setTargets, setEditorTargets, setEditorType, setParent, setInspector);

            // we have to set IsVisible
            var materialEditor = Editor as MaterialEditor;

            if (materialEditor != null)
            {
                                #if DEV_MODE
                Debug.Log("materialEditor not null with setEditorType=" + StringUtils.ToString(setEditorType) + ", Editor=" + StringUtils.TypeToString(Editor) + ", HeaderEditor=" + StringUtils.TypeToString(HeaderEditor));
                                #endif

                                #if UNITY_2019_2_OR_NEWER
                // Was unable to figure out how the isVisible property value can be set using reflection, and as a result
                // calling OnInspectorGUI for the MaterialEditor draws nothing.
                // However, was able to get around the issue by getting the ShaderGUI from the MaterialEditor via MaterialEditor.customShaderGUI
                // (which was added in Unity 2019.2) and drawing the GUI using that instead.
                // The material properties are needed for the OnGUI method of the ShaderGUI.
                materialProperties = MaterialEditor.GetMaterialProperties(targets);
                                #elif UNITY_2018_3_OR_NEWER
                var isVisible = typeof(MaterialEditor).GetField("m_IsVisible", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                if (isVisible != null)
                {
                    isVisible.SetValue(Editor, true);
                }
                                #if DEV_MODE
                else
                {
                    Debug.LogWarning("MaterialEditor field \"m_IsVisible\" not found");
                }
                                #endif
                                #else
                var forceVisible = typeof(MaterialEditor).GetProperty("forceVisible", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                if (forceVisible != null)
                {
                    forceVisible.SetValue(Editor, true, null);
                }
                                #if DEV_MODE
                else
                {
                    Debug.LogWarning("MaterialEditor field \"forceVisible\" not found");
                }
                                #endif
                                #endif
            }
                        #if DEV_MODE && PI_ASSERTATIONS
            else
            {
                                #if DEV_MODE
                Debug.Log("materialEditor null with setEditorType=" + StringUtils.ToString(setEditorType) + ", Editor=" + StringUtils.TypeToString(Editor) + ", HeaderEditor=" + StringUtils.TypeToString(HeaderEditor));
                                #endif

                Debug.Assert(setEditorType != typeof(MaterialEditor));
            }
                        #endif
        }
        protected override void Update()
        {
            //自定义的value全部导出,不和默认值做过滤
            var target             = this.source;
            var materialProperties = MaterialEditor.GetMaterialProperties(new UnityEngine.Object[] { target });

            foreach (var materialProperty in materialProperties)
            {
                if (materialProperty.flags == MaterialProperty.PropFlags.HideInInspector)
                {
                    continue;
                }

                var    uniform = new MyJson_Tree();
                string type    = materialProperty.type.ToString();
                if (type == "Float" || type == "Range")
                {
                    this.values.SetNumber(materialProperty.name, this.GetFloat(materialProperty.name, 0.0f));
                }
                else if (type == "Vector")
                {
                    this.values.SetVector4(materialProperty.name, this.GetVector4(materialProperty.name, Vector4.zero));
                }
                else if (type == "Color")
                {
                    this.values.SetColor(materialProperty.name, this.GetColor(materialProperty.name, Color.white));
                }
                else if (type == "Texture")
                {
                    var tex = this.GetTexture(materialProperty.name, null);
                    if (tex != null)
                    {
                        string texdim = materialProperty.textureDimension.ToString();
                        if (texdim == "Tex2D")
                        {
                            this.SetTexture(materialProperty.name, tex);

                            string propertyName = materialProperty.name + "_ST";
                            if (target.HasProperty(propertyName))
                            {
                                this.values.SetVector4(propertyName, this.GetVector4(propertyName, Vector4.zero));
                            }
                        }
                        else
                        {
                            throw new Exception("not suport texdim:" + texdim);
                        }
                    }
                }
                else
                {
                    throw new Exception("not support type: " + materialProperty.type);
                }
            }

            MyLog.Log("自定义Shader:" + this.technique);
        }
예제 #15
0
        public static List <KeyValuePair <string, System.Object> > AnalyzeMaterial(Object obj,
                                                                                   SerializedObject serializedObject)
        {
            var propertys = new List <KeyValuePair <string, object> >();


            string texNames = string.Empty;

            var property = serializedObject.FindProperty("m_Shader");

            propertys.Add(new KeyValuePair <string, object>("依赖Shader", property.objectReferenceValue ? property.objectReferenceValue.name : "[其他AB内]"));

            property = serializedObject.FindProperty("m_SavedProperties");
            var property2 = property.FindPropertyRelative("m_TexEnvs");

            foreach (SerializedProperty property3 in property2)
            {
                SerializedProperty property4 = property3.FindPropertyRelative("second");
                SerializedProperty property5 = property4.FindPropertyRelative("m_Texture");

                if (property5.objectReferenceValue)
                {
                    if (!string.IsNullOrEmpty(texNames))
                    {
                        texNames += ", ";
                    }
                    texNames += property5.objectReferenceValue.name;
                }
                else
                {
                    if (!string.IsNullOrEmpty(texNames))
                    {
                        texNames += ", ";
                    }
                    texNames += "[其他AB内]";
                }
            }
            propertys.Add(new KeyValuePair <string, object>("依赖纹理", texNames));
            Material mat = obj as Material;

            MaterialProperty[] proTes = MaterialEditor.GetMaterialProperties(new Object[] { obj });
            for (int i = 0; proTes != null && i < proTes.Length; ++i)
            {
                if (proTes[i].type == MaterialProperty.PropType.Texture)
                {
                    if (mat == null)
                    {
                        continue;
                    }
                    Texture tex  = mat.GetTexture(proTes[i].name);
                    string  path = AssetDatabase.GetAssetPath(tex);
                }
            }

            return(propertys);
        }
예제 #16
0
    private void InitMaterialProps()
    {
        MaterialProperties = MaterialEditor.GetMaterialProperties(Targets);
        MaterialPropNames  = new Dictionary <string, MaterialProperty>();

        for (int i = 0; i < MaterialProperties.Length; ++i)
        {
            MaterialPropNames.Add(MaterialProperties[i].name, MaterialProperties[i]);
        }
    }
예제 #17
0
        // Custom property draw, we don't want things that are connected to an edge or useless like the render queue
        protected int GetMaterialHash(Material material)
        {
            int hash = 0;

            if (material == null || material.shader == null)
            {
                return(hash);
            }

            MaterialProperty[] properties = MaterialEditor.GetMaterialProperties(new [] { material });
            var portViews = GetPortViewsFromFieldName(nameof(ShaderNode.materialInputs));

            foreach (var property in properties)
            {
                if ((property.flags & (MaterialProperty.PropFlags.HideInInspector | MaterialProperty.PropFlags.PerRendererData)) != 0)
                {
                    continue;
                }

                // Retrieve the port view from the property name
                var portView = portViews?.FirstOrDefault(p => p.portData.identifier == property.name);
                if (portView != null && portView.connected)
                {
                    continue;
                }

                switch (property.type)
                {
                case MaterialProperty.PropType.Float:
                    hash += property.floatValue.GetHashCode();
                    break;

                case MaterialProperty.PropType.Color:
                    hash += property.colorValue.GetHashCode();
                    break;

                case MaterialProperty.PropType.Range:
                    hash += property.rangeLimits.GetHashCode();
                    hash += property.floatValue.GetHashCode();
                    break;

                case MaterialProperty.PropType.Vector:
                    hash += property.vectorValue.GetHashCode();
                    break;

                case MaterialProperty.PropType.Texture:
                    hash += property.textureValue?.GetHashCode() ?? 0;
                    hash += property.textureScaleAndOffset.GetHashCode();
                    hash += property.textureDimension.GetHashCode();
                    break;
                }
            }

            return(hash);
        }
예제 #18
0
        private static void getDependencies(string file, Dictionary <string, string> dict)
        {
            string main_ext = System.IO.Path.GetExtension(file).ToLower();

            string[] dep = AssetDatabase.GetDependencies(file, false);

            // dirty material has dirty texture dependencies
            if (main_ext == ".mat")
            {
                Material mat = AssetDatabase.LoadAssetAtPath <Material>(file);
                if (mat == null)
                {
                    return;
                }
                MaterialProperty[] proTes = MaterialEditor.GetMaterialProperties(new Object[] { mat });
                for (int i = 0; i < proTes.Length; ++i)
                {
                    if (proTes[i].type == MaterialProperty.PropType.Texture)
                    {
                        Texture tex  = mat.GetTexture(proTes[i].name);
                        string  path = AssetDatabase.GetAssetPath(tex);
                        if (!dict.ContainsKey(path))
                        {
                            dict.Add(path, path);
                        }
                    }
                }
                for (int i = 0; i < dep.Length; ++i)
                {
                    // assume material only depencies Texture & Shader
                    if (dep[i].EndsWith(".shader") && !dict.ContainsKey(dep[i]))
                    {
                        dict.Add(dep[i], dep[i]);
                    }
                }
                Resources.UnloadAsset(mat);
            }
            else
            {
                for (int i = 0; i < dep.Length; ++i)
                {
                    if (!dict.ContainsKey(dep[i]))
                    {
                        dict.Add(dep[i], dep[i]);
                    }
                    getDependencies(dep[i], dict);
                }
            }

            if (++m_count % m_mod == 0)
            {
                AssetDatabase.SaveAssets();
            }
        }
        public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
        {
            if (material.HasProperty("_Emission"))
            {
                material.SetColor("_EmissionColor", material.GetColor("_Emission"));
            }
            base.AssignNewShaderToMaterial(material, oldShader, newShader);

            MaterialProperty[] properties = MaterialEditor.GetMaterialProperties(new Material[] { material });
            FindProperties(properties, material);

            SetGIFlags();
        }
        public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
        {
            if (material.HasProperty(MKXRayFreeMaterialHelper.PropertyNames.EMISSION))
            {
                MKXRayFreeMaterialHelper.SetEmissionColor(material, material.GetColor(MKXRayFreeMaterialHelper.PropertyNames.EMISSION));
            }
            base.AssignNewShaderToMaterial(material, oldShader, newShader);

            MaterialProperty[] properties = MaterialEditor.GetMaterialProperties(new Material[] { material });
            FindProperties(properties, material);

            SetGIFlags();
        }
예제 #21
0
        void InitChangeList(object menuData)
        {
            var groupName = menuData as string;

            itemsProperty.ClearArray();
            foreach (var i in SelectionGroupUtility.GetComponents <Renderer>(groupName))
            {
                for (var index = 0; index < i.sharedMaterials.Length; index++)
                {
                    //required to work around bug in GetMaterialProperties
                    var singleMaterial = new[] { i.sharedMaterials[index] };
                    foreach (var p in MaterialEditor.GetMaterialProperties(singleMaterial))
                    {
                        if (p.type == MaterialProperty.PropType.Color ||
                            p.type == MaterialProperty.PropType.Float ||
                            p.type == MaterialProperty.PropType.Range ||
                            p.type == MaterialProperty.PropType.Vector)
                        {
                            itemsProperty.InsertArrayElementAtIndex(0);
                            var change = itemsProperty.GetArrayElementAtIndex(0);
                            change.FindPropertyRelative("memberNameQuery").stringValue     = i.name;
                            change.FindPropertyRelative("materialIndex").intValue          = index;
                            change.FindPropertyRelative("propertyDisplayName").stringValue = p.displayName;
                            change.FindPropertyRelative("propertyName").stringValue        = p.name;
                            var typeProperty = change.FindPropertyRelative("propertyType");
                            switch (p.type)
                            {
                            case MaterialProperty.PropType.Color:
                                change.FindPropertyRelative("colorValue").colorValue = UnityEngine.Random.ColorHSV(0, 1, 0.7f, 1, 0.5f, 1f);
                                typeProperty.intValue = PropertyChange.COLOR;
                                break;

                            case MaterialProperty.PropType.Float:
                            case MaterialProperty.PropType.Range:
                                change.FindPropertyRelative("floatValue").floatValue = 0;
                                typeProperty.intValue = PropertyChange.FLOAT;
                                break;

                            case MaterialProperty.PropType.Vector:
                                typeProperty.intValue = PropertyChange.VECTOR;
                                change.FindPropertyRelative("vectorValue").vector4Value = Vector4.zero;
                                break;
                            }
                        }
                    }
                }
            }
            itemsProperty.serializedObject.ApplyModifiedProperties();
        }
    private static void ConvertToLinear()
    {
        Object[] mmm = Selection.objects;
        if (mmm == null)
        {
            Debug.Log(mmm);
            return;
        }

        foreach (MaterialProperty m in MaterialEditor.GetMaterialProperties(mmm))
        {
            if (m.flags == MaterialProperty.PropFlags.HDR)
            {
                m.colorValue = m.colorValue.linear;
            }
        }
    }
예제 #23
0
    //从Renderer绑定的材质中读取所有的贴图
    private List <Texture2D> CollectTextures(GameObject target)
    {
        List <Texture2D> result = new List <Texture2D>();

        MeshRenderer[]        meshRenderers        = target.GetComponentsInChildren <MeshRenderer>();
        SkinnedMeshRenderer[] skinnedMeshRenderers = target.GetComponentsInChildren <SkinnedMeshRenderer>();
        List <Material>       mats = new List <Material>();

        for (int i = 0; i < meshRenderers.Length; i++)
        {
            if (meshRenderers[i].sharedMaterial)
            {
                if (!mats.Contains(meshRenderers[i].sharedMaterial))
                {
                    mats.Add(meshRenderers[i].sharedMaterial);
                }
            }
        }
        for (int i = 0; i < skinnedMeshRenderers.Length; i++)
        {
            if (skinnedMeshRenderers[i].sharedMaterial)
            {
                if (!mats.Contains(skinnedMeshRenderers[i].sharedMaterial))
                {
                    mats.Add(skinnedMeshRenderers[i].sharedMaterial);
                }
            }
        }
        if (mats.Count > 0)
        {
            foreach (var mat in mats)
            {
                var matProperties = MaterialEditor.GetMaterialProperties(new Material[] { mat });
                for (int i = 0; i < matProperties.Length; i++)
                {
                    if (matProperties[i].type == MaterialProperty.PropType.Texture &&
                        matProperties[i].textureDimension == UnityEngine.Rendering.TextureDimension.Tex2D && matProperties[i].textureValue != null)
                    {
                        result.Add((Texture2D)matProperties[i].textureValue);
                    }
                }
            }
            //MaterialProperty[] matProperties = MaterialEditor.GetMaterialProperties(mats.ToArray());
        }
        return(result);
    }
예제 #24
0
        protected void MaterialPropertiesGui(Material material)
        {
            if (material == null)
            {
                return;
            }

            if (materialEditor == null || cachedMaterial != material)
            {
                cachedMaterial = material;
                UnityEditor.Editor.CreateCachedEditor(cachedMaterial, typeof(MaterialEditor), ref cachedEditor);
                materialEditor = (MaterialEditor)cachedEditor;
                properties     = MaterialEditor.GetMaterialProperties(new UnityEngine.Object[] { cachedMaterial });
            }

            materialEditor.PropertiesDefaultGUI(properties);
        }
예제 #25
0
        public static IEnumerable <SearchColumn> Enumerate(IEnumerable <SearchItem> items)
        {
            var descriptors     = new List <SearchColumn>();
            var shaderProcessed = new HashSet <string>();

            bool materialRootItemAdded = false;

            foreach (var item in items)
            {
                var material = item.ToObject <Material>();
                if (!material)
                {
                    continue;
                }

                if (!materialRootItemAdded)
                {
                    descriptors.Add(new SearchColumn("Material", new GUIContent("Material", Utils.FindTextureForType(typeof(Material)))));
                    materialRootItemAdded = true;
                }

                if (shaderProcessed.Contains(material.shader.name))
                {
                    continue;
                }
                shaderProcessed.Add(material.shader.name);

                var shaderPath = "Material/" + material.shader.name;
                var shaderIcon = Utils.FindTextureForType(typeof(Shader));
                descriptors.Add(new SearchColumn(shaderPath, new GUIContent(material.shader.name, shaderIcon)));

                var materialProperties = MaterialEditor.GetMaterialProperties(new Object[] { material });
                for (var i = 0; i < materialProperties.Length; i++)
                {
                    var m        = materialProperties[i];
                    var propName = m.name;
                    var propPath = shaderPath + "/" + propName;
                    var col      = new SearchColumn(propPath, "#" + propName, provider: $"{m.type}",
                                                    new GUIContent(m.displayName, shaderIcon, m.name));
                    descriptors.Add(col);
                }
            }

            return(descriptors);
        }
예제 #26
0
                public override void OnInspectorGUI()
                {
                    MaterialParamTrack track    = base.target as MaterialParamTrack;
                    Material           material = GetClipBoundMaterial();

                    if (material != null)
                    {
                        MaterialProperty[] properties = MaterialEditor.GetMaterialProperties(new Object[] { material });
                        List <string>      parameters = new List <string>();

                        int index = 0;

                        for (int i = 0; i < properties.Length; i++)
                        {
                            if (MatchesTrack(track, properties[i]))
                            {
                                if (properties[i].name == track._parameterId)
                                {
                                    index = parameters.Count;
                                }

                                parameters.Add(properties[i].name);
                            }
                        }

                        if (properties.Length > 0)
                        {
                            index = EditorGUILayout.Popup(kParameterLabel, index, parameters.ToArray());
                            track._parameterId = parameters[index];
                        }
                        else
                        {
                            GUI.enabled = false;
                            EditorGUILayout.TextField(kNoParametersLabel);
                            GUI.enabled = true;
                        }
                    }
                    else
                    {
                        GUI.enabled = false;
                        EditorGUILayout.TextField(kParameterLabel, track._parameterId);
                        GUI.enabled = true;
                    }
                }
예제 #27
0
    static bool TryConvert(bool toLinear = true)
    {
        Object[] selection = Selection.objects;
        if (selection == null)
        {
            return(false);
        }

        int matCount   = 0;
        int colorCount = 0;

        foreach (Material mat in selection)
        {
            matCount++;
            MaterialProperty[] props = MaterialEditor.GetMaterialProperties(new Material[] { mat });
            if ((props == null) || (props.Length == 0))
            {
                return(false);
            }

            foreach (MaterialProperty m in props)
            {
                if (m.flags == MaterialProperty.PropFlags.HDR)
                {
                    //Color prev = m.colorValue;
                    m.colorValue = (toLinear ? m.colorValue.linear : m.colorValue.gamma);
                    colorCount++;
                    //Debug.Log("prev: " + prev + ", current: " + m.colorValue);
                }
            }
        }

        if (colorCount == 0)
        {
            EditorUtility.DisplayDialog("Result", "Found no HDR Color properties in the selected material" + (matCount > 1 ? "s." : "."), "OK");
        }
        else
        {
            EditorUtility.DisplayDialog("Result", "Converted " + colorCount + " HDR Color propert" + (colorCount > 1 ? "ies" : "y") + " in " + matCount + " material" + (matCount > 1 ? "s":"") + " to " + (toLinear ? "Linear" : "Gamma") + " color space.", "OK");
        }

        return(true);
    }
예제 #28
0
        bool CheckPropertyChanged(Material material, MaterialProperty[] properties)
        {
            bool propertyChanged = false;

            MaterialProperty[] oldProperties;
            oldMaterialProperties.TryGetValue(material, out oldProperties);

            if (oldProperties != null)
            {
                // Check if shader was changed (new/deleted properties)
                if (properties.Length != oldProperties.Length)
                {
                    propertyChanged = true;
                }
                else
                {
                    for (int i = 0; i < properties.Length; i++)
                    {
                        if (properties[i].type != oldProperties[i].type)
                        {
                            propertyChanged = true;
                        }
                        if (properties[i].displayName != oldProperties[i].displayName)
                        {
                            propertyChanged = true;
                        }
                        if (properties[i].flags != oldProperties[i].flags)
                        {
                            propertyChanged = true;
                        }
                        if (properties[i].name != oldProperties[i].name)
                        {
                            propertyChanged = true;
                        }
                    }
                }
            }

            oldMaterialProperties[material] = MaterialEditor.GetMaterialProperties(new [] { material });

            return(propertyChanged);
        }
 private static void UpdateMaterial(Dictionary <MaterialPropertyKey, MaterialPropertyAsset> materialProperties, HashSet <MaterialPropertyKey> unvisitedMaterialProperties, Material material)
 {
     if (material != null)
     {
         foreach (MaterialProperty materialProperty in MaterialEditor.GetMaterialProperties(new Material[] { material }))
         {
             var key = new MaterialPropertyKey(material.shader.name, materialProperty.name);
             unvisitedMaterialProperties.Remove(key);
             if (!materialProperties.ContainsKey(key))
             {
                 materialProperties.Add(key, new MaterialPropertyAsset
                 {
                     Shader       = material.shader,
                     propertyName = materialProperty.name,
                     propertyType = (MaterialPropertyType)materialProperty.type
                 });
             }
         }
     }
 }
예제 #30
0
 private void OnSelectionChange()
 {
     string[] selectedAssets = Selection.assetGUIDs;
     if (selectedAssets.Length == 1)
     {
         Object obj = AssetDatabase.LoadAssetAtPath <Object>(AssetDatabase.GUIDToAssetPath(selectedAssets[0]));
         if (obj.GetType() == typeof(Shader))
         {
             Shader   shader = (Shader)obj;
             Material m      = new Material(shader);
             if (m.HasProperty(Shader.PropertyToID("shader_eable_poi_settings_selection")))
             {
                 MaterialProperty[] props = MaterialEditor.GetMaterialProperties(new Material[] { m });
                 activeShader  = shader;
                 presetHandler = new PoiPresetHandler(props);
             }
         }
     }
     this.Repaint();
 }