TMP_BaseShaderGUI.cs 18.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
using UnityEngine;
using UnityEditor;

namespace TMPro.EditorUtilities
{
    /// <summary>Base class for TextMesh Pro shader GUIs.</summary>
    public abstract class TMP_BaseShaderGUI : ShaderGUI
    {
        /// <summary>Representation of a #pragma shader_feature.</summary>
        /// <description>It is assumed that the first feature option is for no keyword (underscores).</description>
        protected class ShaderFeature
        {
            public string undoLabel;

            public GUIContent label;

            /// <summary>The keyword labels, for display. Include the no-keyword as the first option.</summary>
            public GUIContent[] keywordLabels;

            /// <summary>The shader keywords. Exclude the no-keyword option.</summary>
            public string[] keywords;

            int m_State;

            public bool Active
            {
                get { return m_State >= 0; }
            }

            public int State
            {
                get { return m_State; }
            }

            public void ReadState(Material material)
            {
                for (int i = 0; i < keywords.Length; i++)
                {
                    if (material.IsKeywordEnabled(keywords[i]))
                    {
                        m_State = i;
                        return;
                    }
                }

                m_State = -1;
            }

            public void SetActive(bool active, Material material)
            {
                m_State = active ? 0 : -1;
                SetStateKeywords(material);
            }

            public void DoPopup(MaterialEditor editor, Material material)
            {
                EditorGUI.BeginChangeCheck();
                int selection = EditorGUILayout.Popup(label, m_State + 1, keywordLabels);
                if (EditorGUI.EndChangeCheck())
                {
                    m_State = selection - 1;
                    editor.RegisterPropertyChangeUndo(undoLabel);
                    SetStateKeywords(material);
                }
            }

            void SetStateKeywords(Material material)
            {
                for (int i = 0; i < keywords.Length; i++)
                {
                    if (i == m_State)
                    {
                        material.EnableKeyword(keywords[i]);
                    }
                    else
                    {
                        material.DisableKeyword(keywords[i]);
                    }
                }
            }
        }

        static GUIContent s_TempLabel = new GUIContent();

        protected static bool s_DebugExtended;

        static int s_UndoRedoCount, s_LastSeenUndoRedoCount;

        static float[][] s_TempFloats =
        {
            null, new float[1], new float[2], new float[3], new float[4]
        };

        protected static GUIContent[] s_XywhVectorLabels =
        {
            new GUIContent("X"),
            new GUIContent("Y"),
            new GUIContent("W", "Width"),
            new GUIContent("H", "Height")
        };

        protected static GUIContent[] s_LbrtVectorLabels =
        {
            new GUIContent("L", "Left"),
            new GUIContent("B", "Bottom"),
            new GUIContent("R", "Right"),
            new GUIContent("T", "Top")
        };

        protected static GUIContent[] s_CullingTypeLabels =
        {
            new GUIContent("Off"),
            new GUIContent("Front"),
            new GUIContent("Back")
        };

        static TMP_BaseShaderGUI()
        {
            // Keep track of how many undo/redo events happened.
            Undo.undoRedoPerformed += () => s_UndoRedoCount += 1;
        }

        bool m_IsNewGUI = true;

        float m_DragAndDropMinY;

        protected MaterialEditor m_Editor;

        protected Material m_Material;

        protected MaterialProperty[] m_Properties;

        void PrepareGUI()
        {
            m_IsNewGUI = false;
            ShaderUtilities.GetShaderPropertyIDs();

            // New GUI just got constructed. This happens in response to a selection,
            // but also after undo/redo events.
            if (s_LastSeenUndoRedoCount != s_UndoRedoCount)
            {
                // There's been at least one undo/redo since the last time this GUI got constructed.
                // Maybe the undo/redo was for this material? Assume that is was.
                TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, m_Material as Material);
            }

            s_LastSeenUndoRedoCount = s_UndoRedoCount;
        }

        public override void OnGUI(MaterialEditor materialEditor, MaterialProperty[] properties)
        {
            m_Editor = materialEditor;
            m_Material = materialEditor.target as Material;
            this.m_Properties = properties;

            if (m_IsNewGUI)
            {
                PrepareGUI();
            }

            DoDragAndDropBegin();
            EditorGUI.BeginChangeCheck();
            DoGUI();
            if (EditorGUI.EndChangeCheck())
            {
                TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, m_Material);
            }

            DoDragAndDropEnd();
        }

        /// <summary>Override this method to create the specific shader GUI.</summary>
        protected abstract void DoGUI();

        static string[] s_PanelStateLabel = new string[] { "\t- <i>Click to collapse</i> -", "\t- <i>Click to expand</i>  -" };

        protected bool BeginPanel(string panel, bool expanded)
        {
            EditorGUI.indentLevel = 0;

            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
            Rect r = EditorGUI.IndentedRect(GUILayoutUtility.GetRect(20, 18));
            r.x += 20;
            r.width += 6;

            bool enabled = GUI.enabled;
            GUI.enabled = true;
            expanded = TMP_EditorUtility.EditorToggle(r, expanded, new GUIContent(panel), TMP_UIStyleManager.panelTitle);
            r.width -= 30;
            EditorGUI.LabelField(r, new GUIContent(expanded ? s_PanelStateLabel[0] : s_PanelStateLabel[1]), TMP_UIStyleManager.rightLabel);
            GUI.enabled = enabled;

            EditorGUI.indentLevel += 1;
            EditorGUI.BeginDisabledGroup(false);

            return expanded;
        }

        protected bool BeginPanel(string panel, ShaderFeature feature, bool expanded, bool readState = true)
        {
            EditorGUI.indentLevel = 0;

            if (readState)
            {
                feature.ReadState(m_Material);
            }

            EditorGUI.BeginChangeCheck();

            EditorGUILayout.BeginVertical(EditorStyles.helpBox);
            GUILayout.BeginHorizontal();

            Rect r = EditorGUI.IndentedRect(GUILayoutUtility.GetRect(20, 20, GUILayout.Width(20f)));
            bool active = EditorGUI.Toggle(r, feature.Active);

            if (EditorGUI.EndChangeCheck())
            {
                m_Editor.RegisterPropertyChangeUndo(feature.undoLabel);
                feature.SetActive(active, m_Material);
            }

            r = EditorGUI.IndentedRect(GUILayoutUtility.GetRect(20, 18));
            r.width += 6;

            bool enabled = GUI.enabled;
            GUI.enabled = true;
            expanded = TMP_EditorUtility.EditorToggle(r, expanded, new GUIContent(panel), TMP_UIStyleManager.panelTitle);
            r.width -= 10;
            EditorGUI.LabelField(r, new GUIContent(expanded ? s_PanelStateLabel[0] : s_PanelStateLabel[1]), TMP_UIStyleManager.rightLabel);
            GUI.enabled = enabled;

            GUILayout.EndHorizontal();

            EditorGUI.indentLevel += 1;
            EditorGUI.BeginDisabledGroup(!active);

            return expanded;
        }

        public void EndPanel()
        {
            EditorGUI.EndDisabledGroup();
            EditorGUI.indentLevel -= 1;
            EditorGUILayout.EndVertical();
        }

        MaterialProperty BeginProperty(string name)
        {
            MaterialProperty property = FindProperty(name, m_Properties);
            EditorGUI.BeginChangeCheck();
            EditorGUI.showMixedValue = property.hasMixedValue;
            m_Editor.BeginAnimatedCheck(Rect.zero, property);

            return property;
        }

        bool EndProperty()
        {
            m_Editor.EndAnimatedCheck();
            EditorGUI.showMixedValue = false;
            return EditorGUI.EndChangeCheck();
        }

        protected void DoPopup(string name, string label, GUIContent[] options)
        {
            MaterialProperty property = BeginProperty(name);
            s_TempLabel.text = label;
            int index = EditorGUILayout.Popup(s_TempLabel, (int)property.floatValue, options);
            if (EndProperty())
            {
                property.floatValue = index;
            }
        }

        protected void DoCubeMap(string name, string label)
        {
            DoTexture(name, label, typeof(Cubemap));
        }

        protected void DoTexture2D(string name, string label, bool withTilingOffset = false, string[] speedNames = null)
        {
            DoTexture(name, label, typeof(Texture2D), withTilingOffset, speedNames);
        }

        void DoTexture(string name, string label, System.Type type, bool withTilingOffset = false, string[] speedNames = null)
        {
            MaterialProperty property = FindProperty(name, m_Properties);
            m_Editor.BeginAnimatedCheck(Rect.zero, property);

            Rect rect = EditorGUILayout.GetControlRect(true, 60f);
            float totalWidth = rect.width;
            rect.width = EditorGUIUtility.labelWidth + 60f;
            s_TempLabel.text = label;

            EditorGUI.BeginChangeCheck();
            Object tex = EditorGUI.ObjectField(rect, s_TempLabel, property.textureValue, type, false);
            if (EditorGUI.EndChangeCheck())
            {
                property.textureValue = tex as Texture;
            }

            rect.x += rect.width + 4f;
            rect.width = totalWidth - rect.width - 4f;
            rect.height = EditorGUIUtility.singleLineHeight;

            if (withTilingOffset)
            {
                DoTilingOffset(rect, property);
                rect.y += (rect.height + 2f) * 2f;
            }

            m_Editor.EndAnimatedCheck();

            if (speedNames != null)
            {
                DoUVSpeed(rect, speedNames);
            }
        }

        void DoTilingOffset(Rect rect, MaterialProperty property)
        {
            float labelWidth = EditorGUIUtility.labelWidth;
            int indentLevel = EditorGUI.indentLevel;
            EditorGUI.indentLevel = 0;
            EditorGUIUtility.labelWidth = Mathf.Min(40f, rect.width * 0.20f);

            Vector4 vector = property.textureScaleAndOffset;

            bool changed = false;
            float[] values = s_TempFloats[2];

            s_TempLabel.text = "Tiling";
            Rect vectorRect = EditorGUI.PrefixLabel(rect, s_TempLabel);
            values[0] = vector.x;
            values[1] = vector.y;

            EditorGUI.BeginChangeCheck();
            EditorGUI.MultiFloatField(vectorRect, s_XywhVectorLabels, values);
            if (EditorGUI.EndChangeCheck())
            {
                vector.x = values[0];
                vector.y = values[1];
                changed = true;
            }

            rect.y += rect.height + 2f;
            s_TempLabel.text = "Offset";
            vectorRect = EditorGUI.PrefixLabel(rect, s_TempLabel);
            values[0] = vector.z;
            values[1] = vector.w;

            EditorGUI.BeginChangeCheck();
            EditorGUI.MultiFloatField(vectorRect, s_XywhVectorLabels, values);
            if (EditorGUI.EndChangeCheck())
            {
                vector.z = values[0];
                vector.w = values[1];
                changed = true;
            }

            if (changed)
            {
                property.textureScaleAndOffset = vector;
            }

            EditorGUIUtility.labelWidth = labelWidth;
            EditorGUI.indentLevel = indentLevel;
        }

        protected void DoUVSpeed(Rect rect, string[] names)
        {
            float labelWidth = EditorGUIUtility.labelWidth;
            int indentLevel = EditorGUI.indentLevel;
            EditorGUI.indentLevel = 0;
            EditorGUIUtility.labelWidth = Mathf.Min(40f, rect.width * 0.20f);

            s_TempLabel.text = "Speed";
            rect = EditorGUI.PrefixLabel(rect, s_TempLabel);

            EditorGUIUtility.labelWidth = 13f;
            rect.width = rect.width * 0.5f - 1f;
            DoFloat(rect, names[0], "X");
            rect.x += rect.width + 2f;
            DoFloat(rect, names[1], "Y");
            EditorGUIUtility.labelWidth = labelWidth;
            EditorGUI.indentLevel = indentLevel;
        }

        protected void DoToggle(string name, string label)
        {
            MaterialProperty property = BeginProperty(name);
            s_TempLabel.text = label;
            bool value = EditorGUILayout.Toggle(s_TempLabel, property.floatValue == 1f);
            if (EndProperty())
            {
                property.floatValue = value ? 1f : 0f;
            }
        }

        protected void DoFloat(string name, string label)
        {
            MaterialProperty property = BeginProperty(name);
            Rect rect = EditorGUILayout.GetControlRect();
            rect.width = EditorGUIUtility.labelWidth + 55f;
            s_TempLabel.text = label;
            float value = EditorGUI.FloatField(rect, s_TempLabel, property.floatValue);
            if (EndProperty())
            {
                property.floatValue = value;
            }
        }

        protected void DoColor(string name, string label)
        {
            MaterialProperty property = BeginProperty(name);
            s_TempLabel.text = label;
            Color value = EditorGUI.ColorField(EditorGUILayout.GetControlRect(), s_TempLabel, property.colorValue, false, true, true);
            if (EndProperty())
            {
                property.colorValue = value;
            }
        }

        void DoFloat(Rect rect, string name, string label)
        {
            MaterialProperty property = BeginProperty(name);
            s_TempLabel.text = label;
            float value = EditorGUI.FloatField(rect, s_TempLabel, property.floatValue);
            if (EndProperty())
            {
                property.floatValue = value;
            }
        }

        protected void DoSlider(string name, string label)
        {
            MaterialProperty property = BeginProperty(name);
            Vector2 range = property.rangeLimits;
            s_TempLabel.text = label;
            float value = EditorGUI.Slider(
                EditorGUILayout.GetControlRect(), s_TempLabel, property.floatValue, range.x, range.y
            );
            if (EndProperty())
            {
                property.floatValue = value;
            }
        }

        protected void DoVector3(string name, string label)
        {
            MaterialProperty property = BeginProperty(name);
            s_TempLabel.text = label;
            Vector4 value = EditorGUILayout.Vector3Field(s_TempLabel, property.vectorValue);
            if (EndProperty())
            {
                property.vectorValue = value;
            }
        }

        protected void DoVector(string name, string label, GUIContent[] subLabels)
        {
            MaterialProperty property = BeginProperty(name);
            Rect rect = EditorGUILayout.GetControlRect();
            s_TempLabel.text = label;
            rect = EditorGUI.PrefixLabel(rect, s_TempLabel);
            Vector4 vector = property.vectorValue;

            float[] values = s_TempFloats[subLabels.Length];
            for (int i = 0; i < subLabels.Length; i++)
            {
                values[i] = vector[i];
            }

            EditorGUI.MultiFloatField(rect, subLabels, values);
            if (EndProperty())
            {
                for (int i = 0; i < subLabels.Length; i++)
                {
                    vector[i] = values[i];
                }

                property.vectorValue = vector;
            }
        }

        void DoDragAndDropBegin()
        {
            m_DragAndDropMinY = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true)).y;
        }

        void DoDragAndDropEnd()
        {
            Rect rect = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
            Event evt = Event.current;
            if (evt.type == EventType.DragUpdated)
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
                evt.Use();
            }
            else if (
                evt.type == EventType.DragPerform &&
                Rect.MinMaxRect(rect.xMin, m_DragAndDropMinY, rect.xMax, rect.yMax).Contains(evt.mousePosition)
            )
            {
                DragAndDrop.AcceptDrag();
                evt.Use();
                Material droppedMaterial = DragAndDrop.objectReferences[0] as Material;
                if (droppedMaterial && droppedMaterial != m_Material)
                {
                    PerformDrop(droppedMaterial);
                }
            }
        }

        void PerformDrop(Material droppedMaterial)
        {
            Texture droppedTex = droppedMaterial.GetTexture(ShaderUtilities.ID_MainTex);
            if (!droppedTex)
            {
                return;
            }

            Texture currentTex = m_Material.GetTexture(ShaderUtilities.ID_MainTex);
            TMP_FontAsset requiredFontAsset = null;
            if (droppedTex != currentTex)
            {
                requiredFontAsset = TMP_EditorUtility.FindMatchingFontAsset(droppedMaterial);
                if (!requiredFontAsset)
                {
                    return;
                }
            }

            foreach (GameObject o in Selection.gameObjects)
            {
                if (requiredFontAsset)
                {
                    TMP_Text textComponent = o.GetComponent<TMP_Text>();
                    if (textComponent)
                    {
                        Undo.RecordObject(textComponent, "Font Asset Change");
                        textComponent.font = requiredFontAsset;
                    }
                }

                TMPro_EventManager.ON_DRAG_AND_DROP_MATERIAL_CHANGED(o, m_Material, droppedMaterial);
                EditorUtility.SetDirty(o);
            }
        }
    }
}