コード例 #1
0
    private Shader[] GetUserShaders()
    {
        string rootPath = Application.dataPath + (mLoadAllShaders ? "" : TCP2_ShaderGeneratorUtils.OUTPUT_PATH);

        if (System.IO.Directory.Exists(rootPath))
        {
            string[]      paths      = System.IO.Directory.GetFiles(rootPath, "*.shader", System.IO.SearchOption.AllDirectories);
            List <Shader> shaderList = new List <Shader>();

            foreach (string path in paths)
            {
#if UNITY_EDITOR_WIN
                string assetPath = "Assets" + path.Replace(@"\", @"/").Replace(Application.dataPath, "");
#else
                string assetPath = "Assets" + path.Replace(Application.dataPath, "");
#endif
                Shader         shader         = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Shader)) as Shader;
                ShaderImporter shaderImporter = ShaderImporter.GetAtPath(assetPath) as ShaderImporter;
                if (shaderImporter != null && shader != null && !shaderList.Contains(shader))
                {
                    if (shaderImporter.userData.Contains("USER"))
                    {
                        shaderList.Add(shader);
                    }
                }
            }

            return(shaderList.ToArray());
        }

        return(null);
    }
コード例 #2
0
ファイル: TCP2_ShaderGenerator.cs プロジェクト: cspid/Comic
    private Shader[] GetUserShaders()
    {
        var rootPath = Application.dataPath + (sLoadAllShaders ? "" : TCP2_ShaderGeneratorUtils.OutputPath);

        if (Directory.Exists(rootPath))
        {
            var paths      = Directory.GetFiles(rootPath, "*.shader", SearchOption.AllDirectories);
            var shaderList = new List <Shader>();

            foreach (var path in paths)
            {
#if UNITY_EDITOR_WIN
                var assetPath = "Assets" + path.Replace(@"\", @"/").Replace(Application.dataPath, "");
#else
                string assetPath = "Assets" + path.Replace(Application.dataPath, "");
#endif
                var shaderImporter = ShaderImporter.GetAtPath(assetPath) as ShaderImporter;
                if (shaderImporter != null)
                {
                    if (shaderImporter.userData.Contains("USER"))
                    {
                        var shader = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Shader)) as Shader;
                        if (shader != null && !shaderList.Contains(shader))
                        {
                            shaderList.Add(shader);
                        }
                    }
                }
            }

            return(shaderList.ToArray());
        }

        return(new Shader[0]);
    }
コード例 #3
0
        private static void GetProperties(ref List <TextureProp> m_Properties, ShaderImporter importer)
        {
            var shader        = importer.GetShader();
            var propertyCount = ShaderUtil.GetPropertyCount(shader);

            for (var i = 0; i < propertyCount; i++)
            {
                if (ShaderUtil.GetPropertyType(shader, i) != ShaderUtil.ShaderPropertyType.TexEnv)
                {
                    continue;
                }

                var propertyName = ShaderUtil.GetPropertyName(shader, i);
                var displayName  = ShaderUtil.GetPropertyDescription(shader, i);                 // might be empty
                var texture      = importer.GetDefaultTexture(propertyName);

                var assetBundleName = "";
                if (texture != null)
                {
                    var textureAssetPath = AssetDatabase.GetAssetPath(texture);
                    assetBundleName = AssetDatabase.GetImplicitAssetBundleName(textureAssetPath);
                }

                var temp = new TextureProp
                {
                    propertyName    = propertyName,
                    displayName     = displayName,
                    texture         = texture,
                    assetBundleName = assetBundleName,
                    //dimension = ShaderUtil.GetTexDim(shader, i)
                };
                m_Properties.Add(temp);
            }
        }
コード例 #4
0
        public void Apply(AssetImporter originalImporter, string assetPath, Property[] properties)
        {
            ShaderImporter importer = (ShaderImporter)originalImporter;

            for (int i = 0; i < properties.Length; i++)
            {
                var property = properties [i];

                switch (property.name)
                {
                case "userData":
                    importer.userData = property.value;
                    break;

                case "assetBundleName":
                    importer.assetBundleName = property.value;
                    break;

                case "assetBundleVariant":
                    importer.assetBundleVariant = property.value;
                    break;

                case "name":
                    importer.name = property.value;
                    break;

                case "hideFlags":
                    importer.hideFlags = (HideFlags)System.Enum.Parse(typeof(HideFlags), property.value, true);
                    break;
                }
            }
        }
コード例 #5
0
    private void UpdateFeaturesFromShader()
    {
        if (targetMaterial != null && targetMaterial.shader != null)
        {
            string name = targetMaterial.shader.name;
            if (name.Contains("Mobile"))
            {
                isMobileShader = true;
            }
            else
            {
                isMobileShader = false;
            }
            List <string> nameFeatures = new List <string>(name.Split(' '));
            for (int i = 0; i < ShaderVariants.Count; i++)
            {
                ShaderVariantsEnabled[i] = nameFeatures.Contains(ShaderVariants[i]);
            }
            //Get flags for compiled shader to hide certain parts of the UI
            ShaderImporter shaderImporter = ShaderImporter.GetAtPath(AssetDatabase.GetAssetPath(targetMaterial.shader)) as ShaderImporter;
            if (shaderImporter != null)
            {
//				mShaderFeatures = new List<string>(shaderImporter.userData.Split(new string[]{","}, System.StringSplitOptions.RemoveEmptyEntries));
                TCP2_ShaderGeneratorUtils.ParseUserData(shaderImporter, out mShaderFeatures);
                if (mShaderFeatures.Count > 0 && mShaderFeatures[0] == "USER")
                {
                    isGeneratedShader = true;
                }
            }
        }
    }
コード例 #6
0
	//Get Features array from ShaderImporter
	static public void ParseUserData(ShaderImporter importer, out List<string> Features)
	{
		string[] array;
		string[] dummy;
		Dictionary<string,string> dummyDict;
		ParseUserData(importer, out array, out dummy, out dummyDict, out dummy);
		Features = new List<string>(array);
	}
コード例 #7
0
    public static void ParseUserData(ShaderImporter importer, out string[] Features, out string[] Flags, out Dictionary <string, string> Keywords, out string[] CustomData)
    {
        var featuresList   = new List <string>();
        var flagsList      = new List <string>();
        var customDataList = new List <string>();
        var keywordsDict   = new Dictionary <string, string>();

        var data = importer.userData.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);

        foreach (var d in data)
        {
            if (string.IsNullOrEmpty(d))
            {
                continue;
            }

            switch (d[0])
            {
            //Features
            case 'F':
                if (d == "F")
                {
                    break;                                      //Prevent getting "empty" feature
                }
                featuresList.Add(d.Substring(1));
                break;

            //Flags
            case 'f': flagsList.Add(d.Substring(1)); break;

            //Keywords
            case 'K':
                var kw = d.Substring(1).Split(':');
                if (kw.Length != 2)
                {
                    Debug.LogError("[TCP2 Shader Generator] Error while parsing userData: invalid Keywords format.");
                    Features = null; Flags = null; Keywords = null; CustomData = null;
                    return;
                }
                else
                {
                    keywordsDict.Add(kw[0], kw[1]);
                }
                break;

            //Custom Data
            case 'c': customDataList.Add(d.Substring(1)); break;

            //old format
            default: featuresList.Add(d); break;
            }
        }

        Features   = featuresList.ToArray();
        Flags      = flagsList.ToArray();
        Keywords   = keywordsDict;
        CustomData = customDataList.ToArray();
    }
コード例 #8
0
    static bool DoShader(Object shader)
    {
        var            r_path = AssetDatabase.GetAssetPath(shader);
        ShaderImporter ti     = AssetImporter.GetAtPath(r_path) as ShaderImporter;

        if (ti != null)
        {
            ti.assetBundleName = "shaders";
            return(true);
        }
        return(false);
    }
コード例 #9
0
	//Returns hash of file content to check for manual modifications (with 'h' prefix)
	static public string GetShaderContentHash(ShaderImporter importer)
	{
		string shaderHash = null;
		string shaderFilePath = Application.dataPath.Replace("Assets", "") + importer.assetPath;
		if(System.IO.File.Exists( shaderFilePath ))
		{
			string shaderContent = System.IO.File.ReadAllText( shaderFilePath );
			shaderHash = (shaderContent != null) ? string.Format("h{0}", shaderContent.GetHashCode().ToString("X")) : "";
		}

		return shaderHash;
	}
コード例 #10
0
    private static Dictionary <string, List <Shader> > RetrieveAllBundles()
    {
        if (!Directory.Exists(shaderDirectory))
        {
            Debug.LogError("The shaders directory (\"" + shaderDirectory + "\") does not exist. Thus, there are no bundles to build. Aborting.");
            return(null);
        }

        // Get all assets
        string[] assets = Directory.GetFiles(shaderDirectory, "*.shader");
        Dictionary <string, List <Shader> > bundles = new Dictionary <string, List <Shader> >();

        // Get asset bundle names from each file
        foreach (string file in assets)
        {
            ShaderImporter importer = (ShaderImporter)AssetImporter.GetAtPath(file);

            if (importer == null)
            {
                Debug.LogWarning("Could not import asset \"" + file + "\". Skipping.");
                continue;
            }

            // Get asset bundle name
            string bundleName = importer.assetBundleName;
            if (bundleName != "")
            {
                // Create a folder for each bundle if applicable
                if (!Directory.Exists(assetBundleDirectory + "/" + bundleName))
                {
                    Directory.CreateDirectory(assetBundleDirectory + "/" + bundleName);
                }

                // Create a bundle if applicable
                if (!bundles.ContainsKey(bundleName))
                {
                    List <Shader> list = new List <Shader>();
                    bundles[bundleName] = list;
                }
                bundles[bundleName].Add(importer.GetShader());
            }
        }

        if (bundles.Count == 0)
        {
            Debug.LogError("There are no AssetBundles to build. Aborting.");
            return(null);
        }

        return(bundles);
    }
コード例 #11
0
        private void UpdateShaderMap()
        {
            int shadersWithDefaultMapCount = 0;

            m_shadersWithDefaultMap.Clear();

            StringBuilder report = new StringBuilder();

            string[] assetGUIDs = AssetDatabase.FindAssets("t:shader");
            Debug.Log("Found shaders: " + assetGUIDs.Length);
            foreach (var assetGUID in assetGUIDs)
            {
                var            assetPath      = AssetDatabase.GUIDToAssetPath(assetGUID);
                var            importer       = AssetImporter.GetAtPath(assetPath);
                ShaderImporter shaderImporter = importer as ShaderImporter;

                List <TextureProp> properties = new List <TextureProp>();
                GetProperties(ref properties, shaderImporter);
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Shader: " + assetPath + " (bundle: " + importer.assetBundleName + ")");
                bool hasDefaultMap = false;

                ShaderDefaultMap sdm = new ShaderDefaultMap();
                sdm.shader          = shaderImporter.GetShader();
                sdm.assetBundleName = importer.assetBundleName;
                sdm.properties      = new List <TextureProp>();

                // Walk through shader's textures and see if it's in the same asset bundle
                for (int i = 0; i < properties.Count; ++i)
                {
                    var prop = properties[i];
                    if (prop.texture != null)
                    {
                        sdm.properties.Add(prop);
                        hasDefaultMap = true;
                        sb.AppendLine("\t" + prop.propertyName + ", " + prop.texture.name + " (bundle: " + prop.assetBundleName + ")");
                    }
                }

                if (hasDefaultMap)
                {
                    m_shadersWithDefaultMap.Add(sdm);
                    report.AppendLine(sb.ToString());
                    ++shadersWithDefaultMapCount;
                }
            }

            //Debug.Log(report.ToString());
            //Debug.LogWarning("Shaders with Default Map: " + shadersWithDefaultMapCount);
        }
コード例 #12
0
        public void UpdateShaderOnPropertyNodes(ref Shader shader)
        {
            if (m_propertyNodes.Count == 0)
            {
                return;
            }

            try
            {
                bool hasContents = false;
                //string metaNewcontents = IOUtils.LINE_TERMINATOR.ToString();
                TextureDefaultsDataColector defaultCol = new TextureDefaultsDataColector();
                foreach (KeyValuePair <int, PropertyNode> kvp in m_propertyNodes)
                {
                    hasContents = kvp.Value.UpdateShaderDefaults(ref shader, ref defaultCol) || hasContents;
                }

                if (hasContents)
                {
                    ShaderImporter importer = ( ShaderImporter )ShaderImporter.GetAtPath(AssetDatabase.GetAssetPath(shader));
                    importer.SetDefaultTextures(defaultCol.NamesArr, defaultCol.ValuesArr);
                    importer.SaveAndReimport();

                    defaultCol.Destroy();
                    defaultCol = null;
                    //string metaFilepath = AssetDatabase.GetTextMetaFilePathFromAssetPath( AssetDatabase.GetAssetPath( shader ) );
                    //string metaContents = IOUtils.LoadTextFileFromDisk( metaFilepath );

                    //int startIndex = metaContents.IndexOf( IOUtils.MetaBegin );
                    //int endIndex = metaContents.IndexOf( IOUtils.MetaEnd );

                    //if ( startIndex > 0 && endIndex > 0 )
                    //{
                    //	startIndex += IOUtils.MetaBegin.Length;
                    //	string replace = metaContents.Substring( startIndex, ( endIndex - startIndex ) );
                    //	if ( hasContents )
                    //	{
                    //		metaContents = metaContents.Replace( replace, metaNewcontents );
                    //	}
                    //}
                    //IOUtils.SaveTextfileToDisk( metaContents, metaFilepath, false );
                }
            }
            catch (Exception e)
            {
                Debug.LogException(e);
            }
        }
コード例 #13
0
            public static TCP2_Config CreateFromShader(Shader shader)
            {
                var shaderImporter = ShaderImporter.GetAtPath(AssetDatabase.GetAssetPath(shader)) as ShaderImporter;

                var config = new TCP2_Config();

                config.ShaderName           = shader.name;
                config.Filename             = Path.GetFileName(AssetDatabase.GetAssetPath(shader)).Replace(".shader", "");
                config.isModifiedExternally = false;
                var valid = config.ParseUserData(shaderImporter);

                if (valid)
                {
                    return(config);
                }
                return(null);
            }
コード例 #14
0
    private void LoadCurrentConfigFromShader(Shader shader)
    {
        ShaderImporter shaderImporter = ShaderImporter.GetAtPath(AssetDatabase.GetAssetPath(shader)) as ShaderImporter;

        string[] features;
        string[] flags;
        string[] customData;
        Dictionary <string, string> keywords;

        TCP2_ShaderGeneratorUtils.ParseUserData(shaderImporter, out features, out flags, out keywords, out customData);
        if (features != null && features.Length > 0 && features[0] == "USER")
        {
            mCurrentConfig            = new TCP2_Config();
            mCurrentConfig.ShaderName = shader.name;
            mCurrentConfig.Filename   = System.IO.Path.GetFileName(AssetDatabase.GetAssetPath(shader));
            mCurrentConfig.Features   = new List <string>(features);
            mCurrentConfig.Flags      = (flags != null) ? new List <string>(flags) : new List <string>();
            mCurrentConfig.Keywords   = (keywords != null) ? new Dictionary <string, string>(keywords) : new Dictionary <string, string>();
            mCurrentShader            = shader;
            mConfigChoice             = mUserShadersLabels.IndexOf(shader.name);
            mDirtyConfig = false;
            AutoNames();
            mCurrentHash = mCurrentConfig.ToHash();

            mIsModified = false;
            if (customData != null && customData.Length > 0)
            {
                ulong timestamp;
                if (ulong.TryParse(customData[0], out timestamp))
                {
                    if (shaderImporter.assetTimeStamp != timestamp)
                    {
                        mIsModified = true;
                    }
                }
            }
        }
        else
        {
            EditorApplication.Beep();
            this.ShowNotification(new GUIContent("Invalid shader loaded: it doesn't seem to have been generated by the TCP2 Shader Generator!"));
            mCurrentShader = null;
            NewShader();
        }
    }
コード例 #15
0
    //--------------------------------------------------------------------------------------------------

    public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
    {
        base.AssignNewShaderToMaterial(material, oldShader, newShader);

        //Detect if User Shader (from Shader Generator)
        isGeneratedShader = false;
        mShaderFeatures   = null;
        ShaderImporter shaderImporter = ShaderImporter.GetAtPath(AssetDatabase.GetAssetPath(newShader)) as ShaderImporter;

        if (shaderImporter != null)
        {
            TCP2_ShaderGeneratorUtils.ParseUserData(shaderImporter, out mShaderFeatures);
            if (mShaderFeatures.Count > 0 && mShaderFeatures[0] == "USER")
            {
                isGeneratedShader = true;
            }
        }
    }
コード例 #16
0
 //Get Flags array from ShaderImporter
 static public string[] GetUserDataFlags(ShaderImporter importer)
 {
     //Contains Flags
     if (importer.userData.Contains("|"))
     {
         string[] data = importer.userData.Split('|');
         if (data.Length < 2)
         {
             Debug.LogError("[TCP2 Shader Generator] Invalid userData in ShaderImporter.\n" + importer.userData);
             return(null);
         }
         else
         {
             string[] flags = data[1].Split(new string[] { "," }, System.StringSplitOptions.RemoveEmptyEntries);
             return(flags);
         }
     }
     //No Flags data
     else
     {
         return(null);
     }
 }
コード例 #17
0
    //--------------------------------------------------------------------------------------------------
    // IO

    //Save .shader file
    static private Shader SaveShader(TCP2_Config config, string sourceCode, bool overwritePrompt, bool modifiedPrompt)
    {
        if (string.IsNullOrEmpty(config.Filename))
        {
            Debug.LogError("[TCP2 Shader Generator] Can't save Shader: filename is null or empty!");
            return(null);
        }

        //Save file
        string path = Application.dataPath + OUTPUT_PATH;

        if (!System.IO.Directory.Exists(path))
        {
            System.IO.Directory.CreateDirectory(path);
        }

        string fullPath  = path + config.Filename + ".shader";
        bool   overwrite = true;

        if (overwritePrompt && System.IO.File.Exists(fullPath))
        {
            overwrite = EditorUtility.DisplayDialog("TCP2 : Shader Generation", "The following shader already exists:\n\n" + fullPath + "\n\nOverwrite?", "Yes", "No");
        }

        if (modifiedPrompt)
        {
            overwrite = EditorUtility.DisplayDialog("TCP2 : Shader Generation", "The following shader seems to have been modified externally or manually:\n\n" + fullPath + "\n\nOverwrite anyway?", "Yes", "No");
        }

        if (overwrite)
        {
            string directory = System.IO.Path.GetDirectoryName(path + config.Filename);
            if (!System.IO.Directory.Exists(directory))
            {
                System.IO.Directory.CreateDirectory(directory);
            }

            //Write file to disk
            System.IO.File.WriteAllText(path + config.Filename + ".shader", sourceCode, System.Text.Encoding.UTF8);
            AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

            //Import (to compile shader)
            string assetPath = "Assets" + OUTPUT_PATH + config.Filename + ".shader";

            Shader shader = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Shader)) as Shader;
            if (SelectGeneratedShader)
            {
                Selection.objects = new Object[] { shader };
            }

            //Set ShaderImporter userData
            ShaderImporter shaderImporter = ShaderImporter.GetAtPath(assetPath) as ShaderImporter;
            if (shaderImporter != null)
            {
                string[] customData = new string[] { shaderImporter.assetTimeStamp.ToString() };
                string   userData   = config.ToUserData(customData);
                shaderImporter.userData = userData;

                //Needed to save userData in .meta file
                AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.Default);
            }
            else
            {
                Debug.LogWarning("[TCP2 Shader Generator] Couldn't find ShaderImporter.\nMetadatas will be missing from the shader file.");
            }

            return(shader);
        }

        return(null);
    }
コード例 #18
0
 private bool IsEqual(ShaderImporter target, ShaderImporter reference)
 {
     return(true);
 }
コード例 #19
0
 private void OverwriteImportSettings(ShaderImporter target, ShaderImporter reference)
 {
 }
コード例 #20
0
    // Create a material instance of a given shader and configure textures and such
    void CreateMaterial(Shader shader)
    {
        string shaderPath       = AssetDatabase.GetAssetPath(shader);
        string shaderDirectory  = Path.GetDirectoryName(shaderPath);
        string shaderParentPath = Path.GetDirectoryName(Path.GetDirectoryName(shaderPath));
        string shaderName       = shader.name.Substring("Shade/".Length);
        string materialPath     = Path.Combine(shaderParentPath, shaderName);

        Material material = AssetDatabase.LoadAssetAtPath <Material>(materialPath + ".mat");

        if (material == null)
        {
            material = new Material(shader);
            AssetDatabase.CreateAsset(material, materialPath + ".mat");
        }

        material.shader = shader;

        // Find the Graph.json file for this shader, find any Texture nodes and properly configure the associated material properties for them
        TextAsset      shaderGraphAsset = AssetDatabase.LoadAssetAtPath <TextAsset>(Path.Combine(shaderDirectory, "Graph.json"));
        ShaderGraph    graph            = JsonUtility.FromJson <ShaderGraph>(shaderGraphAsset.text);
        ShaderImporter shaderImporter   = ShaderImporter.GetAtPath(shaderPath) as ShaderImporter;

        string[] textureTypes =
        {
            "Texture",
            "Gradient",
            "Bake",
            "Tiler"
        };

        foreach (ShaderNode n in graph.nodes)
        {
            if (n.options.userLabel != null)
            {
                string lowercaseName = Char.ToLowerInvariant(n.options.userLabel[0]) + n.options.userLabel.Substring(1);
                string propertyName  = "_" + lowercaseName.Replace(" ", "");

                if (Array.Exists(textureTypes, element => element == n.name))
                {
                    string    textureName = n.options.value != null ? n.options.value : n.options.userLabel;
                    Texture2D tex         = AssetDatabase.LoadAssetAtPath <Texture2D>(Path.Combine(shaderDirectory, textureName + ".png"));
                    if (tex != null)
                    {
                        material.SetTexture(propertyName, tex);
                        shaderImporter.SetDefaultTextures(new[] { propertyName }, new[] { tex });

                        string          texturePath = AssetDatabase.GetAssetPath(tex);
                        TextureImporter importer    = (TextureImporter)AssetImporter.GetAtPath(texturePath);

                        if (n.options.wrapMode != null)
                        {
                            switch (n.options.wrapMode)
                            {
                            case "repeat":
                                importer.wrapMode = TextureWrapMode.Repeat;
                                break;

                            case "clamp":
                                importer.wrapMode = TextureWrapMode.Clamp;
                                break;

                            case "mirror":
                                importer.wrapMode = TextureWrapMode.Mirror;
                                break;
                            }
                        }
                        else
                        {
                            importer.wrapMode = TextureWrapMode.Clamp;
                        }

                        if (n.options.filterMode != null)
                        {
                            switch (n.options.filterMode)
                            {
                            case "point":
                                importer.filterMode = FilterMode.Point;
                                break;

                            case "linear":
                                importer.filterMode = n.options.generateMipmaps ? FilterMode.Trilinear : FilterMode.Bilinear;
                                break;
                            }
                        }

                        importer.textureType = n.options.isNormalMap ? TextureImporterType.NormalMap : TextureImporterType.Default;

                        importer.SaveAndReimport();
                    }
                }
            }
        }
    }
コード例 #21
0
ファイル: TCP2_ShaderGenerator.cs プロジェクト: cspid/Comic
    void OnGUI()
    {
        sGUIEnabled = GUI.enabled;

        EditorGUILayout.BeginHorizontal();
        TCP2_GUI.HeaderBig("TOONY COLORS PRO 2 - SHADER GENERATOR");
        TCP2_GUI.HelpButton("Shader Generator");
        EditorGUILayout.EndHorizontal();
        TCP2_GUI.Separator();

        var lW = EditorGUIUtility.labelWidth;

        EditorGUIUtility.labelWidth = 105f;

        //Avoid refreshing Template meta at every Repaint
        EditorGUILayout.BeginHorizontal();
        var _tmpTemplate = EditorGUILayout.ObjectField("Template:", Template.textAsset, typeof(TextAsset), false) as TextAsset;

        if (_tmpTemplate != Template.textAsset)
        {
            Template.SetTextAsset(_tmpTemplate);
        }
        //Load template
        if (loadTemplateMenu != null)
        {
            if (GUILayout.Button("Load ▼", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
            {
                loadTemplateMenu.ShowAsContext();
            }
        }

        /*
         * if(GUILayout.Button("Reload", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
         * {
         *      Template.Reload();
         * }
         */
        EditorGUILayout.EndHorizontal();

        //Template not found
        if (Template == null || Template.textAsset == null)
        {
            EditorGUILayout.HelpBox("Couldn't find template file!\n\nVerify that the file 'TCP2_ShaderTemplate_Default.txt' is in your project.\nPlease reimport the pack if you can't find it!", MessageType.Error);
            return;
        }

        //Infobox for custom templates
        if (!string.IsNullOrEmpty(Template.templateInfo))
        {
            TCP2_GUI.HelpBoxLayout(Template.templateInfo, MessageType.Info);
        }
        if (!string.IsNullOrEmpty(Template.templateWarning))
        {
            TCP2_GUI.HelpBoxLayout(Template.templateWarning, MessageType.Warning);
        }

        TCP2_GUI.Separator();

        //If current shader is unsaved, show yellow color
        var gColor = GUI.color;

        GUI.color = mDirtyConfig ? gColor * unsavedChangesColor : GUI.color;

        EditorGUI.BeginChangeCheck();
        mCurrentShader = EditorGUILayout.ObjectField("Current Shader:", mCurrentShader, typeof(Shader), false) as Shader;
        if (EditorGUI.EndChangeCheck())
        {
            if (mCurrentShader != null)
            {
                LoadCurrentConfigFromShader(mCurrentShader);
            }
        }
        EditorGUILayout.BeginHorizontal();

        GUILayout.Space(EditorGUIUtility.labelWidth + 4);
        if (mDirtyConfig)
        {
            var guiContent = new GUIContent("Unsaved changes");
            var rect       = GUILayoutUtility.GetRect(guiContent, EditorStyles.helpBox, GUILayout.Height(16));
            rect.y -= 2;
            GUI.Label(rect, guiContent, EditorStyles.helpBox);
        }

        GUILayout.FlexibleSpace();
        using (new EditorGUI.DisabledScope(mCurrentShader == null))
        {
            if (GUILayout.Button("Copy", EditorStyles.miniButtonLeft, GUILayout.Width(60f), GUILayout.Height(16)))
            {
                CopyShader();
            }
        }
        if (GUILayout.Button("Load ▼", EditorStyles.miniButtonMid, GUILayout.Width(60f), GUILayout.Height(16)))
        {
            loadShadersMenu.ShowAsContext();
        }
        if (GUILayout.Button("New", EditorStyles.miniButtonRight, GUILayout.Width(60f), GUILayout.Height(16)))
        {
            NewShader();
        }
        GUILayout.Space(18);            //leave space to align with the Object Field box
        EditorGUILayout.EndHorizontal();
        GUI.color = gColor;

        if (mCurrentConfig == null)
        {
            NewShader();
        }

        if (mCurrentConfig.isModifiedExternally)
        {
            EditorGUILayout.HelpBox("It looks like this shader has been modified externally/manually. Updating it will overwrite the changes.", MessageType.Warning);
        }

        EditorGUIUtility.labelWidth = lW;

        //Name & Filename
        TCP2_GUI.Separator();
        GUI.enabled = (mCurrentShader == null);
        EditorGUI.BeginChangeCheck();
        mCurrentConfig.ShaderName = EditorGUILayout.TextField(new GUIContent("Shader Name", "Path will indicate how to find the Shader in Unity's drop-down list"), mCurrentConfig.ShaderName);
        mCurrentConfig.ShaderName = Regex.Replace(mCurrentConfig.ShaderName, @"[^a-zA-Z0-9 _!/]", "");
        if (EditorGUI.EndChangeCheck() && sAutoNames)
        {
            mCurrentConfig.AutoNames();
        }
        GUI.enabled &= !sAutoNames;
        EditorGUILayout.BeginHorizontal();
        mCurrentConfig.Filename = EditorGUILayout.TextField("File Name", mCurrentConfig.Filename);
        mCurrentConfig.Filename = Regex.Replace(mCurrentConfig.Filename, @"[^a-zA-Z0-9 _!/]", "");
        GUILayout.Label(".shader", GUILayout.Width(50f));
        EditorGUILayout.EndHorizontal();
        GUI.enabled = sGUIEnabled;

        TCP2_GUI.Separator();

        //########################################################################################################
        // FEATURES

        TCP2_GUI.Header("FEATURES");

        //Scroll view
        mScrollPosition = EditorGUILayout.BeginScrollView(mScrollPosition);
        EditorGUI.BeginChangeCheck();

        if (Template.newSystem)
        {
            //New UI embedded into Template
            Template.FeaturesGUI(mCurrentConfig);

            if (mFirstHashPass)
            {
                mCurrentHash   = mCurrentConfig.ToHash();
                mFirstHashPass = false;
            }
        }
        else
        {
            EditorGUILayout.HelpBox("Old template versions aren't supported anymore.", MessageType.Warning);
        }

#if DEBUG_MODE
        TCP2_GUI.SeparatorBig();

        TCP2_GUI.SubHeaderGray("DEBUG MODE");

        GUILayout.BeginHorizontal();
        mDebugText = EditorGUILayout.TextField("Custom", mDebugText);
        if (GUILayout.Button("Add Feature", EditorStyles.miniButtonLeft, GUILayout.Width(80f)))
        {
            mCurrentConfig.Features.Add(mDebugText);
        }
        if (GUILayout.Button("Add Flag", EditorStyles.miniButtonRight, GUILayout.Width(80f)))
        {
            mCurrentConfig.Flags.Add(mDebugText);
        }

        GUILayout.EndHorizontal();
        GUILayout.Label("Features:");
        GUILayout.BeginHorizontal();
        int count = 0;
        for (int i = 0; i < mCurrentConfig.Features.Count; i++)
        {
            if (count >= 3)
            {
                count = 0;
                GUILayout.EndHorizontal();
                GUILayout.BeginHorizontal();
            }
            count++;
            if (GUILayout.Button(mCurrentConfig.Features[i], EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
            {
                mCurrentConfig.Features.RemoveAt(i);
                break;
            }
        }
        GUILayout.EndHorizontal();
        GUILayout.Label("Flags:");
        GUILayout.BeginHorizontal();
        count = 0;
        for (int i = 0; i < mCurrentConfig.Flags.Count; i++)
        {
            if (count >= 3)
            {
                count = 0;
                GUILayout.EndHorizontal();
                GUILayout.BeginHorizontal();
            }
            count++;
            if (GUILayout.Button(mCurrentConfig.Flags[i], EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
            {
                mCurrentConfig.Flags.RemoveAt(i);
                break;
            }
        }
        GUILayout.EndHorizontal();
        GUILayout.Label("Keywords:");
        GUILayout.BeginHorizontal();
        count = 0;
        foreach (KeyValuePair <string, string> kvp in mCurrentConfig.Keywords)
        {
            if (count >= 3)
            {
                count = 0;
                GUILayout.EndHorizontal();
                GUILayout.BeginHorizontal();
            }
            count++;
            if (GUILayout.Button(kvp.Key + ":" + kvp.Value, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
            {
                mCurrentConfig.Keywords.Remove(kvp.Key);
                break;
            }
        }
        GUILayout.EndHorizontal();

        //----------------------------------------------------------------

        Space();
        if (mCurrentShader != null)
        {
            if (mCurrentShaderImporter == null)
            {
                mCurrentShaderImporter = ShaderImporter.GetAtPath(AssetDatabase.GetAssetPath(mCurrentShader)) as ShaderImporter;
            }

            if (mCurrentShaderImporter != null && mCurrentShaderImporter.GetShader() == mCurrentShader)
            {
                mDebugExpandUserData = EditorGUILayout.Foldout(mDebugExpandUserData, "Shader UserData");
                if (mDebugExpandUserData)
                {
                    string[] userData = mCurrentShaderImporter.userData.Split(',');
                    foreach (var str in userData)
                    {
                        GUILayout.Label(str);
                    }
                }
            }
        }
#endif

        //Update config
        if (EditorGUI.EndChangeCheck())
        {
            var newHash = mCurrentConfig.ToHash();
            if (newHash != mCurrentHash)
            {
                mDirtyConfig = true;
            }
            else
            {
                mDirtyConfig = false;
            }
        }

        //Scroll view
        EditorGUILayout.EndScrollView();

        Space();

        //GENERATE

        EditorGUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        GUI.color = mDirtyConfig ? gColor * unsavedChangesColor : GUI.color;
        if (GUILayout.Button(mCurrentShader == null ? "Generate Shader" : "Update Shader", GUILayout.Width(120f), GUILayout.Height(30f)))
        {
            if (Template == null)
            {
                EditorUtility.DisplayDialog("TCP2 : Shader Generation", "Can't generate shader: no Template file defined!\n\nYou most likely want to link the TCP2_User.txt file to the Template field in the Shader Generator.", "Ok");
                return;
            }

            //Set config type
            if (Template.templateType != null)
            {
                mCurrentConfig.configType = Template.templateType;
            }

            //Set config file
            mCurrentConfig.templateFile = Template.textAsset.name;

            var generatedShader = TCP2_ShaderGeneratorUtils.Compile(mCurrentConfig, mCurrentShader, Template, true, !sOverwriteConfigs);
            ReloadUserShaders();
            if (generatedShader != null)
            {
                mDirtyConfig = false;
                LoadCurrentConfigFromShader(generatedShader);
            }

            //Workaround to force the inspector to refresh, so that state is reset.
            //Needed in case of switching between specular/metallic and related
            //options, while the inspector is opened, so that it shows/hides the
            //relevant properties according to the changes.
            TCP2_MaterialInspector_SurfacePBS_SG.InspectorNeedsUpdate = true;
        }
        GUI.color = gColor;
        EditorGUILayout.EndHorizontal();
        TCP2_GUI.Separator();

        // OPTIONS
        TCP2_GUI.Header("OPTIONS");

        GUILayout.BeginHorizontal();
        sSelectGeneratedShader = GUILayout.Toggle(sSelectGeneratedShader, new GUIContent("Select Generated Shader", "Will select the generated file in the Project view"), GUILayout.Width(180f));
        sAutoNames             = GUILayout.Toggle(sAutoNames, new GUIContent("Automatic Name", "Will automatically generate the shader filename based on its UI name"), GUILayout.ExpandWidth(false));
        GUILayout.EndHorizontal();
        GUILayout.BeginHorizontal();
        sOverwriteConfigs = GUILayout.Toggle(sOverwriteConfigs, new GUIContent("Always overwrite shaders", "Overwrite shaders when generating/updating (no prompt)"), GUILayout.Width(180f));
        sHideDisabled     = GUILayout.Toggle(sHideDisabled, new GUIContent("Hide disabled fields", "Hide properties settings when they cannot be accessed"), GUILayout.ExpandWidth(false));
        GUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        EditorGUI.BeginChangeCheck();
        TCP2_ShaderGeneratorUtils.CustomOutputDir = GUILayout.Toggle(TCP2_ShaderGeneratorUtils.CustomOutputDir, new GUIContent("Custom Output Directory:", "Will save the generated shaders in a custom directory within the Project"), GUILayout.Width(165f));
        GUI.enabled &= TCP2_ShaderGeneratorUtils.CustomOutputDir;
        if (TCP2_ShaderGeneratorUtils.CustomOutputDir)
        {
            TCP2_ShaderGeneratorUtils.OutputPath = EditorGUILayout.TextField("", TCP2_ShaderGeneratorUtils.OutputPath);
            if (GUILayout.Button("Select...", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
            {
                var outputPath = TCP2_Utils.OpenFolderPanel_ProjectPath("Choose custom output directory for TCP2 generated shaders");
                if (!string.IsNullOrEmpty(outputPath))
                {
                    TCP2_ShaderGeneratorUtils.OutputPath = outputPath;
                }
            }
        }
        else
        {
            EditorGUILayout.TextField("", TCP2_ShaderGeneratorUtils.OUTPUT_PATH);
        }
        if (EditorGUI.EndChangeCheck())
        {
            ReloadUserShaders();
        }

        GUI.enabled = sGUIEnabled;
        EditorGUILayout.EndHorizontal();

        EditorGUI.BeginChangeCheck();
        sLoadAllShaders = GUILayout.Toggle(sLoadAllShaders, new GUIContent("Reload Shaders from all Project", "Load shaders from all your Project folders instead of just Toony Colors Pro 2.\nEnable it if you move your generated shader files outside of the default TCP2 Generated folder."), GUILayout.ExpandWidth(false));
        if (EditorGUI.EndChangeCheck())
        {
            ReloadUserShaders();
        }

        TCP2_ShaderGeneratorUtils.SelectGeneratedShader = sSelectGeneratedShader;
    }
コード例 #22
0
    //--------------------------------------------------------------------------------------------------
    // IO

    //Save .shader file
    private static Shader SaveShader(TCP2_Config config, Shader existingShader, string sourceCode, bool overwritePrompt, bool modifiedPrompt)
    {
        if (string.IsNullOrEmpty(config.Filename))
        {
            Debug.LogError("[TCP2 Shader Generator] Can't save Shader: filename is null or empty!");
            return(null);
        }

        //Save file
        var outputPath = OutputPath;
        var filename   = config.Filename;

        //Get existing shader exact path
        if (existingShader != null)
        {
            outputPath = GetExistingShaderPath(config, existingShader);

            /*
             * if(config.Filename.Contains("/"))
             * {
             *      filename = config.Filename.Substring(config.Filename.LastIndexOf('/')+1);
             * }
             */
        }

        var systemPath = Application.dataPath + outputPath;

        if (!Directory.Exists(systemPath))
        {
            Directory.CreateDirectory(systemPath);
        }

        var fullPath  = systemPath + filename + ".shader";
        var overwrite = true;

        if (overwritePrompt && File.Exists(fullPath))
        {
            overwrite = EditorUtility.DisplayDialog("TCP2 : Shader Generation", "The following shader already exists:\n\n" + fullPath + "\n\nOverwrite?", "Yes", "No");
        }

        if (modifiedPrompt)
        {
            overwrite = EditorUtility.DisplayDialog("TCP2 : Shader Generation", "The following shader seems to have been modified externally or manually:\n\n" + fullPath + "\n\nOverwrite anyway?", "Yes", "No");
        }

        if (overwrite)
        {
            var directory = Path.GetDirectoryName(fullPath);
            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            //Write file to disk
            File.WriteAllText(fullPath, sourceCode, Encoding.UTF8);
            AssetDatabase.Refresh(ImportAssetOptions.ForceSynchronousImport);

            //Import (to compile shader)
            var assetPath = fullPath.Replace(Application.dataPath, "Assets");

            var shader = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Shader)) as Shader;
            if (SelectGeneratedShader)
            {
                Selection.objects = new Object[] { shader };
            }

            //Set ShaderImporter userData
            var shaderImporter = ShaderImporter.GetAtPath(assetPath) as ShaderImporter;
            if (shaderImporter != null)
            {
                //Get file hash to verify if it has been manually altered afterwards
                var shaderHash = GetShaderContentHash(shaderImporter);

                //Use hash if available, else use timestamp
                var customDataList = new List <string>();
                customDataList.Add(!string.IsNullOrEmpty(shaderHash) ? shaderHash : shaderImporter.assetTimeStamp.ToString());
                customDataList.Add(config.GetShaderTargetCustomData());
                var configTypeCustomData = config.GetConfigTypeCustomData();
                if (configTypeCustomData != null)
                {
                    customDataList.Add(configTypeCustomData);
                }
                customDataList.Add(config.GetConfigFileCustomData());

                var userData = config.ToUserData(customDataList.ToArray());
                shaderImporter.userData = userData;

                //Needed to save userData in .meta file
                AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.Default);
            }
            else
            {
                Debug.LogWarning("[TCP2 Shader Generator] Couldn't find ShaderImporter.\nMetadatas will be missing from the shader file.");
            }

            return(shader);
        }

        return(null);
    }
コード例 #23
0
    void OnGUI()
    {
        sGUIEnabled = GUI.enabled;

        EditorGUILayout.BeginHorizontal();
        TCP2_GUI.HeaderBig("TOONY COLORS PRO 2 - SHADER GENERATOR");
        TCP2_GUI.HelpButton("Shader Generator");
        EditorGUILayout.EndHorizontal();
        TCP2_GUI.Separator();

        float lW = EditorGUIUtility.labelWidth;

        EditorGUIUtility.labelWidth = 105f;

        //Avoid refreshing Template meta at every Repaint
        EditorGUILayout.BeginHorizontal();
        TextAsset _tmpTemplate = EditorGUILayout.ObjectField("Template:", Template.textAsset, typeof(TextAsset), false) as TextAsset;

        if (_tmpTemplate != Template.textAsset)
        {
            Template.SetTextAsset(_tmpTemplate);
        }
        //Load template
        if (loadTemplateMenu != null)
        {
            if (GUILayout.Button("Load ▼", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
            {
                loadTemplateMenu.ShowAsContext();
            }
        }
        EditorGUILayout.EndHorizontal();

        //Template not found
        if (Template == null || Template.textAsset == null)
        {
            EditorGUILayout.HelpBox("Couldn't find template file!\n\nVerify that the file 'TCP2_ShaderTemplate_Default.txt' is in your project.\nPlease reimport the pack if you can't find it!", MessageType.Error);
            return;
        }

        //Infobox for custom templates
        if (!string.IsNullOrEmpty(Template.templateInfo))
        {
            EditorGUILayout.HelpBox(Template.templateInfo, MessageType.Info);
        }
        if (!string.IsNullOrEmpty(Template.templateWarning))
        {
            EditorGUILayout.HelpBox(Template.templateWarning, MessageType.Warning);
        }

        TCP2_GUI.Separator();

        EditorGUI.BeginChangeCheck();
        EditorGUILayout.BeginHorizontal();
        mCurrentShader = EditorGUILayout.ObjectField("Current Shader:", mCurrentShader, typeof(Shader), false) as Shader;
        if (EditorGUI.EndChangeCheck())
        {
            if (mCurrentShader != null)
            {
                LoadCurrentConfigFromShader(mCurrentShader);
            }
        }
        if (GUILayout.Button("Copy Shader", EditorStyles.miniButton, GUILayout.Width(78f)))
        {
            CopyShader();
        }
        if (GUILayout.Button("New Shader", EditorStyles.miniButton, GUILayout.Width(76f)))
        {
            NewShader();
        }
        EditorGUILayout.EndHorizontal();

        if (mCurrentConfig.isModifiedExternally)
        {
            EditorGUILayout.HelpBox("It looks like this shader has been modified externally/manually. Updating it will overwrite the changes.", MessageType.Warning);
        }

        if (mUserShaders != null && mUserShaders.Length > 0)
        {
            EditorGUI.BeginChangeCheck();
            int   prevChoice = mConfigChoice;
            Color gColor     = GUI.color;
            GUI.color = mDirtyConfig ? gColor * Color.yellow : GUI.color;
            GUILayout.BeginHorizontal();
            mConfigChoice = EditorGUILayout.Popup("Load Shader:", mConfigChoice, mUserShadersLabels.ToArray());
            if (GUILayout.Button("◄", EditorStyles.miniButtonLeft, GUILayout.Width(22)))
            {
                mConfigChoice--;
                if (mConfigChoice < 1)
                {
                    mConfigChoice = mUserShaders.Length;
                }
            }
            if (GUILayout.Button("►", EditorStyles.miniButtonRight, GUILayout.Width(22)))
            {
                mConfigChoice++;
                if (mConfigChoice > mUserShaders.Length)
                {
                    mConfigChoice = 1;
                }
            }
            GUILayout.EndHorizontal();
            GUI.color = gColor;
            if (EditorGUI.EndChangeCheck() && prevChoice != mConfigChoice)
            {
                bool load = true;
                if (mDirtyConfig)
                {
                    if (mCurrentShader != null)
                    {
                        load = EditorUtility.DisplayDialog("TCP2 : Shader Generation", "You have unsaved changes for the following shader:\n\n" + mCurrentShader.name + "\n\nDiscard the changes and load a new shader?", "Yes", "No");
                    }
                    else
                    {
                        load = EditorUtility.DisplayDialog("TCP2 : Shader Generation", "You have unsaved changes.\n\nDiscard the changes and load a new shader?", "Yes", "No");
                    }
                }

                if (load)
                {
                    //New Shader
                    if (mConfigChoice == 0)
                    {
                        NewShader();
                    }
                    else
                    {
                        //Load selected Shader
                        Shader selectedShader = mUserShaders[mConfigChoice - 1];
                        mCurrentShader = selectedShader;
                        LoadCurrentConfigFromShader(mCurrentShader);
                    }
                }
                else
                {
                    //Revert choice
                    mConfigChoice = prevChoice;
                }
            }
        }

        EditorGUIUtility.labelWidth = lW;

        if (mCurrentConfig == null)
        {
            NewShader();
        }

        //Name & Filename
        TCP2_GUI.Separator();
        GUI.enabled = (mCurrentShader == null);
        EditorGUI.BeginChangeCheck();
        mCurrentConfig.ShaderName = EditorGUILayout.TextField(new GUIContent("Shader Name", "Path will indicate how to find the Shader in Unity's drop-down list"), mCurrentConfig.ShaderName);
        mCurrentConfig.ShaderName = Regex.Replace(mCurrentConfig.ShaderName, @"[^a-zA-Z0-9 _!/]", "");
        if (EditorGUI.EndChangeCheck() && sAutoNames)
        {
            mCurrentConfig.AutoNames();
        }
        GUI.enabled &= !sAutoNames;
        EditorGUILayout.BeginHorizontal();
        mCurrentConfig.Filename = EditorGUILayout.TextField("File Name", mCurrentConfig.Filename);
        mCurrentConfig.Filename = Regex.Replace(mCurrentConfig.Filename, @"[^a-zA-Z0-9 _!/]", "");
        GUILayout.Label(".shader", GUILayout.Width(50f));
        EditorGUILayout.EndHorizontal();
        GUI.enabled = sGUIEnabled;

        Space();

        //########################################################################################################
        // FEATURES

        TCP2_GUI.Header("FEATURES");

        //Scroll view
        mScrollPosition = EditorGUILayout.BeginScrollView(mScrollPosition);
        EditorGUI.BeginChangeCheck();

        if (Template.newSystem)
        {
            //New UI embedded into Template
            Template.FeaturesGUI(mCurrentConfig);
        }
        else
        {
            EditorGUILayout.HelpBox("Old template versions aren't supported anymore.", MessageType.Warning);
        }

#if DEBUG_MODE
        TCP2_GUI.SeparatorBig();

        TCP2_GUI.SubHeaderGray("DEBUG MODE");

        GUILayout.BeginHorizontal();
        mDebugText = EditorGUILayout.TextField("Custom", mDebugText);
        if (GUILayout.Button("Add Feature", EditorStyles.miniButtonLeft, GUILayout.Width(80f)))
        {
            mCurrentConfig.Features.Add(mDebugText);
        }
        if (GUILayout.Button("Add Flag", EditorStyles.miniButtonRight, GUILayout.Width(80f)))
        {
            mCurrentConfig.Flags.Add(mDebugText);
        }

        GUILayout.EndHorizontal();
        GUILayout.Label("Features:");
        GUILayout.BeginHorizontal();
        int count = 0;
        for (int i = 0; i < mCurrentConfig.Features.Count; i++)
        {
            if (count >= 3)
            {
                count = 0;
                GUILayout.EndHorizontal();
                GUILayout.BeginHorizontal();
            }
            count++;
            if (GUILayout.Button(mCurrentConfig.Features[i], EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
            {
                mCurrentConfig.Features.RemoveAt(i);
                break;
            }
        }
        GUILayout.EndHorizontal();
        GUILayout.Label("Flags:");
        GUILayout.BeginHorizontal();
        count = 0;
        for (int i = 0; i < mCurrentConfig.Flags.Count; i++)
        {
            if (count >= 3)
            {
                count = 0;
                GUILayout.EndHorizontal();
                GUILayout.BeginHorizontal();
            }
            count++;
            if (GUILayout.Button(mCurrentConfig.Flags[i], EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
            {
                mCurrentConfig.Flags.RemoveAt(i);
                break;
            }
        }
        GUILayout.EndHorizontal();
        GUILayout.Label("Keywords:");
        GUILayout.BeginHorizontal();
        count = 0;
        foreach (KeyValuePair <string, string> kvp in mCurrentConfig.Keywords)
        {
            if (count >= 3)
            {
                count = 0;
                GUILayout.EndHorizontal();
                GUILayout.BeginHorizontal();
            }
            count++;
            if (GUILayout.Button(kvp.Key + ":" + kvp.Value, EditorStyles.toolbarButton, GUILayout.ExpandWidth(false)))
            {
                mCurrentConfig.Keywords.Remove(kvp.Key);
                break;
            }
        }
        GUILayout.EndHorizontal();

        //----------------------------------------------------------------

        Space();
        if (mCurrentShader != null)
        {
            if (mCurrentShaderImporter == null)
            {
                mCurrentShaderImporter = ShaderImporter.GetAtPath(AssetDatabase.GetAssetPath(mCurrentShader)) as ShaderImporter;
            }

            if (mCurrentShaderImporter != null && mCurrentShaderImporter.GetShader() == mCurrentShader)
            {
                mDebugExpandUserData = EditorGUILayout.Foldout(mDebugExpandUserData, "Shader UserData");
                if (mDebugExpandUserData)
                {
                    string[] userData = mCurrentShaderImporter.userData.Split(',');
                    foreach (var str in userData)
                    {
                        GUILayout.Label(str);
                    }
                }
            }
        }
#endif

        //Update config
        if (EditorGUI.EndChangeCheck())
        {
            int newHash = mCurrentConfig.ToHash();
            if (newHash != mCurrentHash)
            {
                mDirtyConfig = true;
            }
            else
            {
                mDirtyConfig = false;
            }
        }

        //Scroll view
        EditorGUILayout.EndScrollView();

        Space();

        //GENERATE

        EditorGUILayout.BeginHorizontal();
        GUILayout.FlexibleSpace();
        if (GUILayout.Button(mCurrentShader == null ? "Generate Shader" : "Update Shader", GUILayout.Width(120f), GUILayout.Height(30f)))
        {
            if (Template == null)
            {
                EditorUtility.DisplayDialog("TCP2 : Shader Generation", "Can't generate shader: no Template file defined!\n\nYou most likely want to link the TCP2_User.txt file to the Template field in the Shader Generator.", "Ok");
                return;
            }

            //Set config type
            if (Template.templateType != null)
            {
                mCurrentConfig.configType = Template.templateType;
            }

            //Set config file
            mCurrentConfig.templateFile = Template.textAsset.name;

            Shader generatedShader = TCP2_ShaderGeneratorUtils.Compile(mCurrentConfig, mCurrentShader, Template, true, !sOverwriteConfigs);
            ReloadUserShaders();
            if (generatedShader != null)
            {
                mDirtyConfig = false;
                LoadCurrentConfigFromShader(generatedShader);
            }
        }
        EditorGUILayout.EndHorizontal();
        TCP2_GUI.Separator();

        // OPTIONS
        TCP2_GUI.Header("OPTIONS");

        GUILayout.BeginHorizontal();
        sSelectGeneratedShader = GUILayout.Toggle(sSelectGeneratedShader, new GUIContent("Select Generated Shader", "Will select the generated file in the Project view"), GUILayout.Width(180f));
        sAutoNames             = GUILayout.Toggle(sAutoNames, new GUIContent("Automatic Name", "Will automatically generate the shader filename based on its UI name"), GUILayout.ExpandWidth(false));
        GUILayout.EndHorizontal();
        GUILayout.BeginHorizontal();
        sOverwriteConfigs = GUILayout.Toggle(sOverwriteConfigs, new GUIContent("Always overwrite shaders", "Overwrite shaders when generating/updating (no prompt)"), GUILayout.Width(180f));
        sHideDisabled     = GUILayout.Toggle(sHideDisabled, new GUIContent("Hide disabled fields", "Hide properties settings when they cannot be accessed"), GUILayout.ExpandWidth(false));
        GUILayout.EndHorizontal();

        EditorGUILayout.BeginHorizontal();
        EditorGUI.BeginChangeCheck();
        TCP2_ShaderGeneratorUtils.CustomOutputDir = GUILayout.Toggle(TCP2_ShaderGeneratorUtils.CustomOutputDir, new GUIContent("Custom Output Directory:", "Will save the generated shaders in a custom directory within the Project"), GUILayout.Width(165f));
        GUI.enabled &= TCP2_ShaderGeneratorUtils.CustomOutputDir;
        if (TCP2_ShaderGeneratorUtils.CustomOutputDir)
        {
            TCP2_ShaderGeneratorUtils.OutputPath = EditorGUILayout.TextField("", TCP2_ShaderGeneratorUtils.OutputPath);
            if (GUILayout.Button("Select...", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
            {
                string path = EditorUtility.OpenFolderPanel("Choose custom output directory for TCP2 generated shaders", Application.dataPath, "");
                if (!string.IsNullOrEmpty(path))
                {
                    bool validPath = TCP2_Utils.SystemToUnityPath(ref path);
                    if (validPath)
                    {
                        if (path == "Assets")
                        {
                            TCP2_ShaderGeneratorUtils.OutputPath = "/";
                        }
                        else
                        {
                            TCP2_ShaderGeneratorUtils.OutputPath = path.Substring("Assets/".Length);
                        }
                    }
                    else
                    {
                        EditorApplication.Beep();
                        EditorUtility.DisplayDialog("Invalid Path", "The selected path is invalid.\n\nPlease select a folder inside the \"Assets\" folder of your project!", "Ok");
                    }
                }
            }
        }
        else
        {
            EditorGUILayout.TextField("", TCP2_ShaderGeneratorUtils.OUTPUT_PATH);
        }
        if (EditorGUI.EndChangeCheck())
        {
            ReloadUserShaders();
        }

        GUI.enabled = sGUIEnabled;
        EditorGUILayout.EndHorizontal();

        EditorGUI.BeginChangeCheck();
        sLoadAllShaders = GUILayout.Toggle(sLoadAllShaders, new GUIContent("Reload Shaders from all Project", "Load shaders from all your Project folders instead of just Toony Colors Pro 2.\nEnable it if you move your generated shader files outside of the default TCP2 Generated folder."), GUILayout.ExpandWidth(false));
        if (EditorGUI.EndChangeCheck())
        {
            ReloadUserShaders();
        }

        TCP2_ShaderGeneratorUtils.SelectGeneratedShader = sSelectGeneratedShader;
    }
コード例 #24
0
    static public TCP2_Config CreateFromShader(Shader shader)
    {
        ShaderImporter shaderImporter = ShaderImporter.GetAtPath(AssetDatabase.GetAssetPath(shader)) as ShaderImporter;

        string[] features;
        string[] flags;
        string[] customData;
        Dictionary <string, string> keywords;

        TCP2_ShaderGeneratorUtils.ParseUserData(shaderImporter, out features, out flags, out keywords, out customData);
        if (features != null && features.Length > 0 && features[0] == "USER")
        {
            var config = new TCP2_Config();
            config.ShaderName = shader.name;
            config.Filename   = System.IO.Path.GetFileName(AssetDatabase.GetAssetPath(shader));
            config.Features   = new List <string>(features);
            config.Flags      = (flags != null) ? new List <string>(flags) : new List <string>();
            config.Keywords   = (keywords != null) ? new Dictionary <string, string>(keywords) : new Dictionary <string, string>();
            config.AutoNames();

            //mCurrentShader = shader;
            //mConfigChoice = mUserShadersLabels.IndexOf(shader.name);
            //mDirtyConfig = false;
            //AutoNames();
            //mCurrentHash = mCurrentConfig.ToHash();

            config.isModifiedExternally = false;
            if (customData != null && customData.Length > 0)
            {
                foreach (string data in customData)
                {
                    //Hash
                    if (data.Length > 0 && data[0] == 'h')
                    {
                        string dataHash = data;
                        string fileHash = TCP2_ShaderGeneratorUtils.GetShaderContentHash(shaderImporter);

                        if (!string.IsNullOrEmpty(fileHash) && dataHash != fileHash)
                        {
                            config.isModifiedExternally = true;
                        }
                    }
                    //Timestamp
                    else
                    {
                        ulong timestamp;
                        if (ulong.TryParse(data, out timestamp))
                        {
                            if (shaderImporter.assetTimeStamp != timestamp)
                            {
                                config.isModifiedExternally = true;
                            }
                        }
                    }

                    //Shader Model target
                    if (data.StartsWith("SM:"))
                    {
                        config.shaderTarget = int.Parse(data.Substring(3));
                    }

                    //Configuration Type
                    if (data.StartsWith("CT:"))
                    {
                        config.configType = data.Substring(3);
                    }

                    //Configuration File
                    if (data.StartsWith("CF:"))
                    {
                        config.templateFile = data.Substring(3);
                    }
                }
            }

            return(config);
        }
        else
        {
            return(null);
        }
    }
コード例 #25
0
ファイル: TCP2_Config.cs プロジェクト: cspid/TheOutside
    bool ParseUserData(ShaderImporter importer)
    {
        if (string.IsNullOrEmpty(importer.userData))
        {
            return(false);
        }

        string[]      data           = importer.userData.Split(new string[] { "," }, System.StringSplitOptions.RemoveEmptyEntries);
        List <string> customDataList = new List <string>();

        foreach (string d in data)
        {
            if (string.IsNullOrEmpty(d))
            {
                continue;
            }

            switch (d[0])
            {
            //Features
            case 'F':
                if (d == "F")
                {
                    break;                                  //Prevent getting "empty" feature
                }
                this.Features.Add(d.Substring(1));
                break;

            //Flags
            case 'f': this.Flags.Add(d.Substring(1)); break;

            //Keywords
            case 'K':
                string[] kw = d.Substring(1).Split(':');
                if (kw.Length != 2)
                {
                    Debug.LogError("[TCP2 Shader Generator] Error while parsing userData: invalid Keywords format.");
                    return(false);
                }
                else
                {
                    this.Keywords.Add(kw[0], kw[1]);
                }
                break;

            //Custom Data
            case 'c': customDataList.Add(d.Substring(1)); break;

            //old format
            default: this.Features.Add(d); break;
            }
        }

        foreach (string customData in customDataList)
        {
            //Hash
            if (customData.Length > 0 && customData[0] == 'h')
            {
                string dataHash = customData;
                string fileHash = TCP2_ShaderGeneratorUtils.GetShaderContentHash(importer);

                if (!string.IsNullOrEmpty(fileHash) && dataHash != fileHash)
                {
                    this.isModifiedExternally = true;
                }
            }
            //Timestamp
            else
            {
                ulong timestamp;
                if (ulong.TryParse(customData, out timestamp))
                {
                    if (importer.assetTimeStamp != timestamp)
                    {
                        this.isModifiedExternally = true;
                    }
                }
            }

            //Shader Model target
            if (customData.StartsWith("SM:"))
            {
                this.shaderTarget = int.Parse(customData.Substring(3));
            }

            //Configuration Type
            if (customData.StartsWith("CT:"))
            {
                this.configType = customData.Substring(3);
            }

            //Configuration File
            if (customData.StartsWith("CF:"))
            {
                this.templateFile = customData.Substring(3);
            }
        }

        return(true);
    }