Reimport upgraded TextMesh Pro, modified.

This commit is contained in:
2023-02-01 22:14:43 +08:00
parent 623c53f79a
commit bd256ba1a6
293 changed files with 98622 additions and 345 deletions

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 651f9a260a3765242b8026f1d4db06e4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: eecc124dc0b994047aac97ccf8c8ed0a
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,677 @@
#if HDRP_10_7_OR_NEWER
using UnityEngine;
using UnityEditor;
using UnityEditor.Rendering.HighDefinition;
namespace TMPro.EditorUtilities
{
/// <summary>Base class for TextMesh Pro shader GUIs.</summary>
internal abstract class TMP_BaseHDRPLitShaderGUI : LightingShaderGraphGUI
{
/// <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_BaseHDRPLitShaderGUI()
{
// 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;
}
protected override void OnMaterialGUI(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;
}
protected 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)
{
float objFieldSize = 60f;
bool smallLayout = EditorGUIUtility.currentViewWidth <= 440f && (withTilingOffset || speedNames != null);
float controlHeight = smallLayout ? objFieldSize * 2 : objFieldSize;
MaterialProperty property = FindProperty(name, m_Properties);
m_Editor.BeginAnimatedCheck(Rect.zero, property);
Rect rect = EditorGUILayout.GetControlRect(true, controlHeight);
float totalWidth = rect.width;
rect.width = EditorGUIUtility.labelWidth + objFieldSize;
rect.height = objFieldSize;
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;
}
float additionalHeight = controlHeight - objFieldSize;
float xOffset = smallLayout ? rect.width - objFieldSize : rect.width;
rect.y += additionalHeight;
rect.x += xOffset;
rect.width = totalWidth - xOffset;
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.40f);
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;
}
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.40f);
s_TempLabel.text = "Speed";
rect = EditorGUI.PrefixLabel(rect, s_TempLabel);
EditorGUIUtility.labelWidth = 10f;
rect.width = rect.width * 0.5f - 2f;
if (names.Length == 1)
{
DoFloat2(rect, names[0]);
}
else
{
DoFloat(rect, names[0], "X");
rect.x += rect.width + 4f;
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;
}
}
void DoFloat2(Rect rect, string name)
{
MaterialProperty property = BeginProperty(name);
float x = EditorGUI.FloatField(rect, "X", property.vectorValue.x);
rect.x += rect.width + 4f;
float y = EditorGUI.FloatField(rect, "Y", property.vectorValue.y);
if (EndProperty())
{
property.vectorValue = new Vector2(x, y);
}
}
protected void DoOffset(string name, string label)
{
MaterialProperty property = BeginProperty(name);
s_TempLabel.text = label;
Vector2 value = EditorGUI.Vector2Field(EditorGUILayout.GetControlRect(), s_TempLabel, property.vectorValue);
if (EndProperty())
{
property.vectorValue = 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 DoSlider(string name, Vector2 range, string label)
{
MaterialProperty property = BeginProperty(name);
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 DoSlider(string propertyName, string propertyField, string label)
{
MaterialProperty property = BeginProperty(propertyName);
Vector2 range = property.rangeLimits;
s_TempLabel.text = label;
Vector4 value = property.vectorValue;
switch (propertyField)
{
case "X":
value.x = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.x, range.x, range.y);
break;
case "Y":
value.y = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.y, range.x, range.y);
break;
case "Z":
value.z = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.z, range.x, range.y);
break;
case "W":
value.w = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.w, range.x, range.y);
break;
}
if (EndProperty())
{
property.vectorValue = value;
}
}
protected void DoSlider(string propertyName, string propertyField, Vector2 range, string label)
{
MaterialProperty property = BeginProperty(propertyName);
s_TempLabel.text = label;
Vector4 value = property.vectorValue;
switch (propertyField)
{
case "X":
value.x = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.x, range.x, range.y);
break;
case "Y":
value.y = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.y, range.x, range.y);
break;
case "Z":
value.z = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.z, range.x, range.y);
break;
case "W":
value.w = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.w, range.x, range.y);
break;
}
if (EndProperty())
{
property.vectorValue = value;
}
}
protected void DoVector2(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 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);
}
}
}
}
#endif

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: e3795795b029fde4395e6953ce72b5a6
timeCreated: 1469844810
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,681 @@
#if HDRP_10_7_OR_NEWER
using UnityEngine;
using UnityEditor;
using UnityEditor.Rendering.HighDefinition;
namespace TMPro.EditorUtilities
{
/// <summary>Base class for TextMesh Pro shader GUIs.</summary>
#if HDRP_11_OR_NEWER
internal abstract class TMP_BaseHDRPUnlitShaderGUI : UnlitShaderGraphGUI
#else
internal abstract class TMP_BaseHDRPUnlitShaderGUI : HDUnlitGUI
#endif
{
/// <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_BaseHDRPUnlitShaderGUI()
{
// 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;
}
protected override void OnMaterialGUI(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;
}
protected 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)
{
float objFieldSize = 60f;
bool smallLayout = EditorGUIUtility.currentViewWidth <= 440f && (withTilingOffset || speedNames != null);
float controlHeight = smallLayout ? objFieldSize * 2 : objFieldSize;
MaterialProperty property = FindProperty(name, m_Properties);
m_Editor.BeginAnimatedCheck(Rect.zero, property);
Rect rect = EditorGUILayout.GetControlRect(true, controlHeight);
float totalWidth = rect.width;
rect.width = EditorGUIUtility.labelWidth + objFieldSize;
rect.height = objFieldSize;
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;
}
float additionalHeight = controlHeight - objFieldSize;
float xOffset = smallLayout ? rect.width - objFieldSize : rect.width;
rect.y += additionalHeight;
rect.x += xOffset;
rect.width = totalWidth - xOffset;
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.40f);
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;
}
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.40f);
s_TempLabel.text = "Speed";
rect = EditorGUI.PrefixLabel(rect, s_TempLabel);
EditorGUIUtility.labelWidth = 10f;
rect.width = rect.width * 0.5f - 2f;
if (names.Length == 1)
{
DoFloat2(rect, names[0]);
}
else
{
DoFloat(rect, names[0], "X");
rect.x += rect.width + 4f;
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;
}
}
void DoFloat2(Rect rect, string name)
{
MaterialProperty property = BeginProperty(name);
float x = EditorGUI.FloatField(rect, "X", property.vectorValue.x);
rect.x += rect.width + 4f;
float y = EditorGUI.FloatField(rect, "Y", property.vectorValue.y);
if (EndProperty())
{
property.vectorValue = new Vector2(x, y);
}
}
protected void DoOffset(string name, string label)
{
MaterialProperty property = BeginProperty(name);
s_TempLabel.text = label;
Vector2 value = EditorGUI.Vector2Field(EditorGUILayout.GetControlRect(), s_TempLabel, property.vectorValue);
if (EndProperty())
{
property.vectorValue = 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 DoSlider(string name, Vector2 range, string label)
{
MaterialProperty property = BeginProperty(name);
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 DoSlider(string propertyName, string propertyField, string label)
{
MaterialProperty property = BeginProperty(propertyName);
Vector2 range = property.rangeLimits;
s_TempLabel.text = label;
Vector4 value = property.vectorValue;
switch (propertyField)
{
case "X":
value.x = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.x, range.x, range.y);
break;
case "Y":
value.y = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.y, range.x, range.y);
break;
case "Z":
value.z = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.z, range.x, range.y);
break;
case "W":
value.w = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.w, range.x, range.y);
break;
}
if (EndProperty())
{
property.vectorValue = value;
}
}
protected void DoSlider(string propertyName, string propertyField, Vector2 range, string label)
{
MaterialProperty property = BeginProperty(propertyName);
s_TempLabel.text = label;
Vector4 value = property.vectorValue;
switch (propertyField)
{
case "X":
value.x = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.x, range.x, range.y);
break;
case "Y":
value.y = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.y, range.x, range.y);
break;
case "Z":
value.z = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.z, range.x, range.y);
break;
case "W":
value.w = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.w, range.x, range.y);
break;
}
if (EndProperty())
{
property.vectorValue = value;
}
}
protected void DoVector2(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 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);
}
}
}
}
#endif

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 645409e9544820042937871953f20509
timeCreated: 1469844810
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,631 @@
#if HDRP_10_7_OR_NEWER
using UnityEngine;
using UnityEditor;
using UnityEditor.Rendering.HighDefinition;
namespace TMPro.EditorUtilities
{
internal class TMP_SDF_HDRPLitShaderGUI : TMP_BaseHDRPLitShaderGUI
{
static ShaderFeature s_OutlineFeature, s_UnderlayFeature, s_BevelFeature, s_GlowFeature, s_MaskFeature;
static bool s_Face = true, s_Outline = true, s_Outline2 = true, s_Outline3 = true, s_Underlay = true, s_Lighting = true, s_Glow, s_Bevel, s_Light, s_Bump, s_Env;
static string[]
s_FaceUVSpeedName = { "_FaceUVSpeed" },
s_FaceUvSpeedNames = { "_FaceUVSpeedX", "_FaceUVSpeedY" },
s_OutlineUvSpeedNames = { "_OutlineUVSpeedX", "_OutlineUVSpeedY" },
s_OutlineUvSpeedName = { "_OutlineUVSpeed" };
/// <summary>
///
/// </summary>
static TMP_SDF_HDRPLitShaderGUI()
{
s_OutlineFeature = new ShaderFeature()
{
undoLabel = "Outline",
keywords = new[] { "OUTLINE_ON" }
};
s_UnderlayFeature = new ShaderFeature()
{
undoLabel = "Underlay",
keywords = new[] { "UNDERLAY_ON", "UNDERLAY_INNER" },
label = new GUIContent("Underlay Type"),
keywordLabels = new[]
{
new GUIContent("None"), new GUIContent("Normal"), new GUIContent("Inner")
}
};
s_BevelFeature = new ShaderFeature()
{
undoLabel = "Bevel",
keywords = new[] { "BEVEL_ON" }
};
s_GlowFeature = new ShaderFeature()
{
undoLabel = "Glow",
keywords = new[] { "GLOW_ON" }
};
s_MaskFeature = new ShaderFeature()
{
undoLabel = "Mask",
keywords = new[] { "MASK_HARD", "MASK_SOFT" },
label = new GUIContent("Mask"),
keywordLabels = new[]
{
new GUIContent("Mask Off"), new GUIContent("Mask Hard"), new GUIContent("Mask Soft")
}
};
}
/// <summary>
///
/// </summary>
public TMP_SDF_HDRPLitShaderGUI()
{
// Remove the ShaderGraphUIBlock to avoid having duplicated properties in the UI.
uiBlocks.RemoveAll(b => b is ShaderGraphUIBlock);
}
protected override void DoGUI()
{
s_Face = BeginPanel("Face", s_Face);
if (s_Face)
{
DoFacePanel();
}
EndPanel();
// Outline panels
DoOutlinePanels();
// Underlay panel
s_Underlay = BeginPanel("Underlay", s_Underlay);
if (s_Underlay)
{
DoUnderlayPanel();
}
EndPanel();
// Lighting panel
DrawLightingPanel();
/*
if (m_Material.HasProperty(ShaderUtilities.ID_GlowColor))
{
s_Glow = BeginPanel("Glow", s_GlowFeature, s_Glow);
if (s_Glow)
{
DoGlowPanel();
}
EndPanel();
}
*/
s_DebugExtended = BeginPanel("Debug Settings", s_DebugExtended);
if (s_DebugExtended)
{
DoDebugPanelSRP();
}
EndPanel();
EditorGUILayout.Space();
EditorGUILayout.Space();
// Draw HDRP panels
uiBlocks.OnGUI(m_Editor, m_Properties);
#if HDRP_12_OR_NEWER
ValidateMaterial(m_Material);
#else
SetupMaterialKeywordsAndPass(m_Material);
#endif
}
void DoFacePanel()
{
EditorGUI.indentLevel += 1;
DoColor("_FaceColor", "Color");
if (m_Material.HasProperty(ShaderUtilities.ID_FaceTex))
{
if (m_Material.HasProperty("_FaceUVSpeedX"))
{
DoTexture2D("_FaceTex", "Texture", true, s_FaceUvSpeedNames);
}
else if (m_Material.HasProperty("_FaceUVSpeed"))
{
DoTexture2D("_FaceTex", "Texture", true, s_FaceUVSpeedName);
}
else
{
DoTexture2D("_FaceTex", "Texture", true);
}
}
if (m_Material.HasProperty("_Softness"))
{
DoSlider("_Softness", "X", new Vector2(0, 1), "Softness");
}
if (m_Material.HasProperty("_OutlineSoftness"))
{
DoSlider("_OutlineSoftness", "Softness");
}
if (m_Material.HasProperty(ShaderUtilities.ID_FaceDilate))
{
DoSlider("_FaceDilate", "Dilate");
if (m_Material.HasProperty(ShaderUtilities.ID_Shininess))
{
DoSlider("_FaceShininess", "Gloss");
}
}
if (m_Material.HasProperty(ShaderUtilities.ID_IsoPerimeter))
{
DoSlider("_IsoPerimeter", "X", new Vector2(-1, 1), "Dilate");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoOutlinePanels()
{
s_Outline = BeginPanel("Outline 1", s_Outline);
if (s_Outline)
DoOutlinePanelWithTexture(1, "Y", "Color");
EndPanel();
s_Outline2 = BeginPanel("Outline 2", s_Outline2);
if (s_Outline2)
DoOutlinePanel(2, "Z", "Color");
EndPanel();
s_Outline3 = BeginPanel("Outline 3", s_Outline3);
if (s_Outline3)
DoOutlinePanel(3, "W", "Color");
EndPanel();
}
void DoOutlinePanel(int outlineID, string propertyField, string label)
{
EditorGUI.indentLevel += 1;
DoColor("_OutlineColor" + outlineID, label);
if (outlineID != 3)
DoOffset("_OutlineOffset" + outlineID, "Offset");
else
{
if (m_Material.GetFloat(ShaderUtilities.ID_OutlineMode) == 0)
DoOffset("_OutlineOffset" + outlineID, "Offset");
}
DoSlider("_Softness", propertyField, new Vector2(0, 1), "Softness");
DoSlider("_IsoPerimeter", propertyField, new Vector2(-1, 1), "Dilate");
if (outlineID == 3)
{
DoToggle("_OutlineMode", "Outline Mode");
}
if (m_Material.HasProperty("_OutlineShininess"))
{
//DoSlider("_OutlineShininess", "Gloss");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoOutlinePanelWithTexture(int outlineID, string propertyField, string label)
{
EditorGUI.indentLevel += 1;
DoColor("_OutlineColor" + outlineID, label);
if (m_Material.HasProperty(ShaderUtilities.ID_OutlineTex))
{
if (m_Material.HasProperty("_OutlineUVSpeedX"))
{
DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedNames);
}
else if (m_Material.HasProperty("_OutlineUVSpeed"))
{
DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedName);
}
else
{
DoTexture2D("_OutlineTex", "Texture", true);
}
}
DoOffset("_OutlineOffset" + outlineID, "Offset");
DoSlider("_Softness", propertyField, new Vector2(0, 1), "Softness");
DoSlider("_IsoPerimeter", propertyField, new Vector2(-1, 1), "Dilate");
if (m_Material.HasProperty("_OutlineShininess"))
{
//DoSlider("_OutlineShininess", "Gloss");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoUnderlayPanel()
{
EditorGUI.indentLevel += 1;
if (m_Material.HasProperty(ShaderUtilities.ID_IsoPerimeter))
{
DoColor("_UnderlayColor", "Color");
DoSlider("_UnderlayOffset", "X", new Vector2(-1, 1), "Offset X");
DoSlider("_UnderlayOffset", "Y", new Vector2(-1, 1), "Offset Y");
DoSlider("_UnderlayDilate", new Vector2(-1, 1), "Dilate");
DoSlider("_UnderlaySoftness", new Vector2(0, 1), "Softness");
}
else
{
s_UnderlayFeature.DoPopup(m_Editor, m_Material);
DoColor("_UnderlayColor", "Color");
DoSlider("_UnderlayOffsetX", "Offset X");
DoSlider("_UnderlayOffsetY", "Offset Y");
DoSlider("_UnderlayDilate", "Dilate");
DoSlider("_UnderlaySoftness", "Softness");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
static GUIContent[] s_BevelTypeLabels =
{
new GUIContent("Outer Bevel"),
new GUIContent("Inner Bevel")
};
void DrawLightingPanel()
{
s_Lighting = BeginPanel("Lighting", s_Lighting);
if (s_Lighting)
{
s_Bevel = BeginPanel("Bevel", s_Bevel);
if (s_Bevel)
{
DoBevelPanel();
}
EndPanel();
s_Light = BeginPanel("Local Lighting", s_Light);
if (s_Light)
{
DoLocalLightingPanel();
}
EndPanel();
/*
s_Bump = BeginPanel("Bump Map", s_Bump);
if (s_Bump)
{
DoBumpMapPanel();
}
EndPanel();
s_Env = BeginPanel("Environment Map", s_Env);
if (s_Env)
{
DoEnvMapPanel();
}
EndPanel();
*/
}
EndPanel();
}
void DoBevelPanel()
{
EditorGUI.indentLevel += 1;
DoPopup("_BevelType", "Type", s_BevelTypeLabels);
DoSlider("_BevelAmount", "Amount");
DoSlider("_BevelOffset", "Offset");
DoSlider("_BevelWidth", "Width");
DoSlider("_BevelRoundness", "Roundness");
DoSlider("_BevelClamp", "Clamp");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoLocalLightingPanel()
{
EditorGUI.indentLevel += 1;
DoSlider("_LightAngle", "Light Angle");
DoColor("_SpecularColor", "Specular Color");
DoSlider("_SpecularPower", "Specular Power");
DoSlider("_Reflectivity", "Reflectivity Power");
DoSlider("_Diffuse", "Diffuse Shadow");
DoSlider("_Ambient", "Ambient Shadow");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoSurfaceLightingPanel()
{
EditorGUI.indentLevel += 1;
DoColor("_SpecColor", "Specular Color");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoBumpMapPanel()
{
EditorGUI.indentLevel += 1;
DoTexture2D("_BumpMap", "Texture");
DoSlider("_BumpFace", "Face");
DoSlider("_BumpOutline", "Outline");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoEnvMapPanel()
{
EditorGUI.indentLevel += 1;
DoColor("_ReflectFaceColor", "Face Color");
DoColor("_ReflectOutlineColor", "Outline Color");
DoCubeMap("_Cube", "Texture");
DoVector3("_EnvMatrixRotation", "Rotation");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoGlowPanel()
{
EditorGUI.indentLevel += 1;
DoColor("_GlowColor", "Color");
DoSlider("_GlowOffset", "Offset");
DoSlider("_GlowInner", "Inner");
DoSlider("_GlowOuter", "Outer");
DoSlider("_GlowPower", "Power");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoDebugPanel()
{
EditorGUI.indentLevel += 1;
DoTexture2D("_MainTex", "Font Atlas");
DoFloat("_GradientScale", "Gradient Scale");
DoFloat("_TextureWidth", "Texture Width");
DoFloat("_TextureHeight", "Texture Height");
EditorGUILayout.Space();
DoFloat("_ScaleX", "Scale X");
DoFloat("_ScaleY", "Scale Y");
if (m_Material.HasProperty(ShaderUtilities.ID_Sharpness))
DoSlider("_Sharpness", "Sharpness");
DoSlider("_PerspectiveFilter", "Perspective Filter");
EditorGUILayout.Space();
DoFloat("_VertexOffsetX", "Offset X");
DoFloat("_VertexOffsetY", "Offset Y");
if (m_Material.HasProperty(ShaderUtilities.ID_MaskCoord))
{
EditorGUILayout.Space();
s_MaskFeature.ReadState(m_Material);
s_MaskFeature.DoPopup(m_Editor, m_Material);
if (s_MaskFeature.Active)
{
DoMaskSubgroup();
}
EditorGUILayout.Space();
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
else if (m_Material.HasProperty("_MaskTex"))
{
DoMaskTexSubgroup();
}
else if (m_Material.HasProperty(ShaderUtilities.ID_MaskSoftnessX))
{
EditorGUILayout.Space();
DoFloat("_MaskSoftnessX", "Softness X");
DoFloat("_MaskSoftnessY", "Softness Y");
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
if (m_Material.HasProperty(ShaderUtilities.ID_StencilID))
{
EditorGUILayout.Space();
DoFloat("_Stencil", "Stencil ID");
DoFloat("_StencilComp", "Stencil Comp");
}
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
bool useRatios = EditorGUILayout.Toggle("Use Ratios", !m_Material.IsKeywordEnabled("RATIOS_OFF"));
if (EditorGUI.EndChangeCheck())
{
m_Editor.RegisterPropertyChangeUndo("Use Ratios");
if (useRatios)
{
m_Material.DisableKeyword("RATIOS_OFF");
}
else
{
m_Material.EnableKeyword("RATIOS_OFF");
}
}
if (m_Material.HasProperty(ShaderUtilities.ShaderTag_CullMode))
{
EditorGUILayout.Space();
DoPopup("_CullMode", "Cull Mode", s_CullingTypeLabels);
}
EditorGUILayout.Space();
EditorGUI.BeginDisabledGroup(true);
DoFloat("_ScaleRatioA", "Scale Ratio A");
DoFloat("_ScaleRatioB", "Scale Ratio B");
DoFloat("_ScaleRatioC", "Scale Ratio C");
EditorGUI.EndDisabledGroup();
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoDebugPanelSRP()
{
EditorGUI.indentLevel += 1;
DoTexture2D("_MainTex", "Font Atlas");
DoFloat("_GradientScale", "Gradient Scale");
//DoFloat("_TextureWidth", "Texture Width");
//DoFloat("_TextureHeight", "Texture Height");
EditorGUILayout.Space();
/*
DoFloat("_ScaleX", "Scale X");
DoFloat("_ScaleY", "Scale Y");
if (m_Material.HasProperty(ShaderUtilities.ID_Sharpness))
DoSlider("_Sharpness", "Sharpness");
DoSlider("_PerspectiveFilter", "Perspective Filter");
EditorGUILayout.Space();
DoFloat("_VertexOffsetX", "Offset X");
DoFloat("_VertexOffsetY", "Offset Y");
if (m_Material.HasProperty(ShaderUtilities.ID_MaskCoord))
{
EditorGUILayout.Space();
s_MaskFeature.ReadState(m_Material);
s_MaskFeature.DoPopup(m_Editor, m_Material);
if (s_MaskFeature.Active)
{
DoMaskSubgroup();
}
EditorGUILayout.Space();
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
else if (m_Material.HasProperty("_MaskTex"))
{
DoMaskTexSubgroup();
}
else if (m_Material.HasProperty(ShaderUtilities.ID_MaskSoftnessX))
{
EditorGUILayout.Space();
DoFloat("_MaskSoftnessX", "Softness X");
DoFloat("_MaskSoftnessY", "Softness Y");
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
if (m_Material.HasProperty(ShaderUtilities.ID_StencilID))
{
EditorGUILayout.Space();
DoFloat("_Stencil", "Stencil ID");
DoFloat("_StencilComp", "Stencil Comp");
}
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
bool useRatios = EditorGUILayout.Toggle("Use Ratios", !m_Material.IsKeywordEnabled("RATIOS_OFF"));
if (EditorGUI.EndChangeCheck())
{
m_Editor.RegisterPropertyChangeUndo("Use Ratios");
if (useRatios)
{
m_Material.DisableKeyword("RATIOS_OFF");
}
else
{
m_Material.EnableKeyword("RATIOS_OFF");
}
}
*/
if (m_Material.HasProperty(ShaderUtilities.ShaderTag_CullMode))
{
EditorGUILayout.Space();
DoPopup("_CullMode", "Cull Mode", s_CullingTypeLabels);
}
EditorGUILayout.Space();
/*
EditorGUI.BeginDisabledGroup(true);
DoFloat("_ScaleRatioA", "Scale Ratio A");
DoFloat("_ScaleRatioB", "Scale Ratio B");
DoFloat("_ScaleRatioC", "Scale Ratio C");
EditorGUI.EndDisabledGroup();
*/
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoMaskSubgroup()
{
DoVector("_MaskCoord", "Mask Bounds", s_XywhVectorLabels);
if (Selection.activeGameObject != null)
{
Renderer renderer = Selection.activeGameObject.GetComponent<Renderer>();
if (renderer != null)
{
Rect rect = EditorGUILayout.GetControlRect();
rect.x += EditorGUIUtility.labelWidth;
rect.width -= EditorGUIUtility.labelWidth;
if (GUI.Button(rect, "Match Renderer Bounds"))
{
FindProperty("_MaskCoord", m_Properties).vectorValue = new Vector4(
0,
0,
Mathf.Round(renderer.bounds.extents.x * 1000) / 1000,
Mathf.Round(renderer.bounds.extents.y * 1000) / 1000
);
}
}
}
if (s_MaskFeature.State == 1)
{
DoFloat("_MaskSoftnessX", "Softness X");
DoFloat("_MaskSoftnessY", "Softness Y");
}
}
void DoMaskTexSubgroup()
{
EditorGUILayout.Space();
DoTexture2D("_MaskTex", "Mask Texture");
DoToggle("_MaskInverse", "Inverse Mask");
DoColor("_MaskEdgeColor", "Edge Color");
DoSlider("_MaskEdgeSoftness", "Edge Softness");
DoSlider("_MaskWipeControl", "Wipe Position");
DoFloat("_MaskSoftnessX", "Softness X");
DoFloat("_MaskSoftnessY", "Softness Y");
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
// protected override void SetupMaterialKeywordsAndPassInternal(Material material)
// {
// BaseLitGUI.SetupBaseLitKeywords(material);
// BaseLitGUI.SetupBaseLitMaterialPass(material);
// }
}
}
#endif

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 85016528879d5d644981050d1d0a4368
timeCreated: 1469844718
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,642 @@
#if HDRP_10_7_OR_NEWER
using UnityEngine;
using UnityEditor;
using UnityEditor.Rendering.HighDefinition;
namespace TMPro.EditorUtilities
{
internal class TMP_SDF_HDRPUnlitShaderGUI : TMP_BaseHDRPUnlitShaderGUI
{
#if !HDRP_11_OR_NEWER
const SurfaceOptionUIBlock.Features surfaceOptionFeatures = SurfaceOptionUIBlock.Features.Unlit;
private readonly MaterialUIBlockList uiBlocks = new MaterialUIBlockList
{
new SurfaceOptionUIBlock(MaterialUIBlock.Expandable.Base, features: surfaceOptionFeatures),
new ShaderGraphUIBlock(MaterialUIBlock.Expandable.ShaderGraph, ShaderGraphUIBlock.Features.Unlit),
new AdvancedOptionsUIBlock(MaterialUIBlock.Expandable.Advance, ~AdvancedOptionsUIBlock.Features.SpecularOcclusion)
};
#endif
static ShaderFeature s_OutlineFeature, s_UnderlayFeature, s_BevelFeature, s_GlowFeature, s_MaskFeature;
static bool s_Face = true, s_Outline = true, s_Outline2 = true, s_Outline3 = true, s_Underlay = true, s_Lighting = true, s_Glow, s_Bevel, s_Light, s_Bump, s_Env;
static string[]
s_FaceUVSpeedName = { "_FaceUVSpeed" },
s_FaceUvSpeedNames = { "_FaceUVSpeedX", "_FaceUVSpeedY" },
s_OutlineUvSpeedNames = { "_OutlineUVSpeedX", "_OutlineUVSpeedY" },
s_OutlineUvSpeedName = { "_OutlineUVSpeed" };
/// <summary>
///
/// </summary>
static TMP_SDF_HDRPUnlitShaderGUI()
{
s_OutlineFeature = new ShaderFeature()
{
undoLabel = "Outline",
keywords = new[] { "OUTLINE_ON" }
};
s_UnderlayFeature = new ShaderFeature()
{
undoLabel = "Underlay",
keywords = new[] { "UNDERLAY_ON", "UNDERLAY_INNER" },
label = new GUIContent("Underlay Type"),
keywordLabels = new[]
{
new GUIContent("None"), new GUIContent("Normal"), new GUIContent("Inner")
}
};
s_BevelFeature = new ShaderFeature()
{
undoLabel = "Bevel",
keywords = new[] { "BEVEL_ON" }
};
s_GlowFeature = new ShaderFeature()
{
undoLabel = "Glow",
keywords = new[] { "GLOW_ON" }
};
s_MaskFeature = new ShaderFeature()
{
undoLabel = "Mask",
keywords = new[] { "MASK_HARD", "MASK_SOFT" },
label = new GUIContent("Mask"),
keywordLabels = new[]
{
new GUIContent("Mask Off"), new GUIContent("Mask Hard"), new GUIContent("Mask Soft")
}
};
}
/// <summary>
///
/// </summary>
public TMP_SDF_HDRPUnlitShaderGUI()
{
// Remove the ShaderGraphUIBlock to avoid having duplicated properties in the UI.
uiBlocks.RemoveAll(b => b is ShaderGraphUIBlock);
}
protected override void DoGUI()
{
s_Face = BeginPanel("Face", s_Face);
if (s_Face)
{
DoFacePanel();
}
EndPanel();
// Outline panels
DoOutlinePanels();
// Underlay panel
s_Underlay = BeginPanel("Underlay", s_Underlay);
if (s_Underlay)
{
DoUnderlayPanel();
}
EndPanel();
// Lighting panel
DrawLightingPanel();
/*
if (m_Material.HasProperty(ShaderUtilities.ID_GlowColor))
{
s_Glow = BeginPanel("Glow", s_GlowFeature, s_Glow);
if (s_Glow)
{
DoGlowPanel();
}
EndPanel();
}
*/
s_DebugExtended = BeginPanel("Debug Settings", s_DebugExtended);
if (s_DebugExtended)
{
DoDebugPanelSRP();
}
EndPanel();
EditorGUILayout.Space();
EditorGUILayout.Space();
// Draw HDRP panels
uiBlocks.OnGUI(m_Editor, m_Properties);
#if HDRP_12_OR_NEWER
ValidateMaterial(m_Material);
#else
SetupMaterialKeywordsAndPass(m_Material);
#endif
}
void DoFacePanel()
{
EditorGUI.indentLevel += 1;
DoColor("_FaceColor", "Color");
if (m_Material.HasProperty(ShaderUtilities.ID_FaceTex))
{
if (m_Material.HasProperty("_FaceUVSpeedX"))
{
DoTexture2D("_FaceTex", "Texture", true, s_FaceUvSpeedNames);
}
else if (m_Material.HasProperty("_FaceUVSpeed"))
{
DoTexture2D("_FaceTex", "Texture", true, s_FaceUVSpeedName);
}
else
{
DoTexture2D("_FaceTex", "Texture", true);
}
}
if (m_Material.HasProperty("_Softness"))
{
DoSlider("_Softness", "X", new Vector2(0, 1), "Softness");
}
if (m_Material.HasProperty("_OutlineSoftness"))
{
DoSlider("_OutlineSoftness", "Softness");
}
if (m_Material.HasProperty(ShaderUtilities.ID_FaceDilate))
{
DoSlider("_FaceDilate", "Dilate");
if (m_Material.HasProperty(ShaderUtilities.ID_Shininess))
{
DoSlider("_FaceShininess", "Gloss");
}
}
if (m_Material.HasProperty(ShaderUtilities.ID_IsoPerimeter))
{
DoSlider("_IsoPerimeter", "X", new Vector2(-1, 1), "Dilate");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoOutlinePanels()
{
s_Outline = BeginPanel("Outline 1", s_Outline);
if (s_Outline)
DoOutlinePanelWithTexture(1, "Y", "Color");
EndPanel();
s_Outline2 = BeginPanel("Outline 2", s_Outline2);
if (s_Outline2)
DoOutlinePanel(2, "Z", "Color");
EndPanel();
s_Outline3 = BeginPanel("Outline 3", s_Outline3);
if (s_Outline3)
DoOutlinePanel(3, "W", "Color");
EndPanel();
}
void DoOutlinePanel(int outlineID, string propertyField, string label)
{
EditorGUI.indentLevel += 1;
DoColor("_OutlineColor" + outlineID, label);
if (outlineID != 3)
DoOffset("_OutlineOffset" + outlineID, "Offset");
else
{
if (m_Material.GetFloat(ShaderUtilities.ID_OutlineMode) == 0)
DoOffset("_OutlineOffset" + outlineID, "Offset");
}
DoSlider("_Softness", propertyField, new Vector2(0, 1), "Softness");
DoSlider("_IsoPerimeter", propertyField, new Vector2(-1, 1), "Dilate");
if (outlineID == 3)
{
DoToggle("_OutlineMode", "Outline Mode");
}
if (m_Material.HasProperty("_OutlineShininess"))
{
//DoSlider("_OutlineShininess", "Gloss");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoOutlinePanelWithTexture(int outlineID, string propertyField, string label)
{
EditorGUI.indentLevel += 1;
DoColor("_OutlineColor" + outlineID, label);
if (m_Material.HasProperty(ShaderUtilities.ID_OutlineTex))
{
if (m_Material.HasProperty("_OutlineUVSpeedX"))
{
DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedNames);
}
else if (m_Material.HasProperty("_OutlineUVSpeed"))
{
DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedName);
}
else
{
DoTexture2D("_OutlineTex", "Texture", true);
}
}
DoOffset("_OutlineOffset" + outlineID, "Offset");
DoSlider("_Softness", propertyField, new Vector2(0, 1), "Softness");
DoSlider("_IsoPerimeter", propertyField, new Vector2(-1, 1), "Dilate");
if (m_Material.HasProperty("_OutlineShininess"))
{
//DoSlider("_OutlineShininess", "Gloss");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoUnderlayPanel()
{
EditorGUI.indentLevel += 1;
if (m_Material.HasProperty(ShaderUtilities.ID_IsoPerimeter))
{
DoColor("_UnderlayColor", "Color");
DoSlider("_UnderlayOffset", "X", new Vector2(-1, 1), "Offset X");
DoSlider("_UnderlayOffset", "Y", new Vector2(-1, 1), "Offset Y");
DoSlider("_UnderlayDilate", new Vector2(-1, 1), "Dilate");
DoSlider("_UnderlaySoftness", new Vector2(0, 1), "Softness");
}
else
{
s_UnderlayFeature.DoPopup(m_Editor, m_Material);
DoColor("_UnderlayColor", "Color");
DoSlider("_UnderlayOffsetX", "Offset X");
DoSlider("_UnderlayOffsetY", "Offset Y");
DoSlider("_UnderlayDilate", "Dilate");
DoSlider("_UnderlaySoftness", "Softness");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
static GUIContent[] s_BevelTypeLabels =
{
new GUIContent("Outer Bevel"),
new GUIContent("Inner Bevel")
};
void DrawLightingPanel()
{
s_Lighting = BeginPanel("Lighting", s_Lighting);
if (s_Lighting)
{
s_Bevel = BeginPanel("Bevel", s_Bevel);
if (s_Bevel)
{
DoBevelPanel();
}
EndPanel();
s_Light = BeginPanel("Local Lighting", s_Light);
if (s_Light)
{
DoLocalLightingPanel();
}
EndPanel();
/*
s_Bump = BeginPanel("Bump Map", s_Bump);
if (s_Bump)
{
DoBumpMapPanel();
}
EndPanel();
s_Env = BeginPanel("Environment Map", s_Env);
if (s_Env)
{
DoEnvMapPanel();
}
EndPanel();
*/
}
EndPanel();
}
void DoBevelPanel()
{
EditorGUI.indentLevel += 1;
DoPopup("_BevelType", "Type", s_BevelTypeLabels);
DoSlider("_BevelAmount", "Amount");
DoSlider("_BevelOffset", "Offset");
DoSlider("_BevelWidth", "Width");
DoSlider("_BevelRoundness", "Roundness");
DoSlider("_BevelClamp", "Clamp");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoLocalLightingPanel()
{
EditorGUI.indentLevel += 1;
DoSlider("_LightAngle", "Light Angle");
DoColor("_SpecularColor", "Specular Color");
DoSlider("_SpecularPower", "Specular Power");
DoSlider("_Reflectivity", "Reflectivity Power");
DoSlider("_Diffuse", "Diffuse Shadow");
DoSlider("_Ambient", "Ambient Shadow");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoSurfaceLightingPanel()
{
EditorGUI.indentLevel += 1;
DoColor("_SpecColor", "Specular Color");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoBumpMapPanel()
{
EditorGUI.indentLevel += 1;
DoTexture2D("_BumpMap", "Texture");
DoSlider("_BumpFace", "Face");
DoSlider("_BumpOutline", "Outline");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoEnvMapPanel()
{
EditorGUI.indentLevel += 1;
DoColor("_ReflectFaceColor", "Face Color");
DoColor("_ReflectOutlineColor", "Outline Color");
DoCubeMap("_Cube", "Texture");
DoVector3("_EnvMatrixRotation", "Rotation");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoGlowPanel()
{
EditorGUI.indentLevel += 1;
DoColor("_GlowColor", "Color");
DoSlider("_GlowOffset", "Offset");
DoSlider("_GlowInner", "Inner");
DoSlider("_GlowOuter", "Outer");
DoSlider("_GlowPower", "Power");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoDebugPanel()
{
EditorGUI.indentLevel += 1;
DoTexture2D("_MainTex", "Font Atlas");
DoFloat("_GradientScale", "Gradient Scale");
DoFloat("_TextureWidth", "Texture Width");
DoFloat("_TextureHeight", "Texture Height");
EditorGUILayout.Space();
DoFloat("_ScaleX", "Scale X");
DoFloat("_ScaleY", "Scale Y");
if (m_Material.HasProperty(ShaderUtilities.ID_Sharpness))
DoSlider("_Sharpness", "Sharpness");
DoSlider("_PerspectiveFilter", "Perspective Filter");
EditorGUILayout.Space();
DoFloat("_VertexOffsetX", "Offset X");
DoFloat("_VertexOffsetY", "Offset Y");
if (m_Material.HasProperty(ShaderUtilities.ID_MaskCoord))
{
EditorGUILayout.Space();
s_MaskFeature.ReadState(m_Material);
s_MaskFeature.DoPopup(m_Editor, m_Material);
if (s_MaskFeature.Active)
{
DoMaskSubgroup();
}
EditorGUILayout.Space();
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
else if (m_Material.HasProperty("_MaskTex"))
{
DoMaskTexSubgroup();
}
else if (m_Material.HasProperty(ShaderUtilities.ID_MaskSoftnessX))
{
EditorGUILayout.Space();
DoFloat("_MaskSoftnessX", "Softness X");
DoFloat("_MaskSoftnessY", "Softness Y");
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
if (m_Material.HasProperty(ShaderUtilities.ID_StencilID))
{
EditorGUILayout.Space();
DoFloat("_Stencil", "Stencil ID");
DoFloat("_StencilComp", "Stencil Comp");
}
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
bool useRatios = EditorGUILayout.Toggle("Use Ratios", !m_Material.IsKeywordEnabled("RATIOS_OFF"));
if (EditorGUI.EndChangeCheck())
{
m_Editor.RegisterPropertyChangeUndo("Use Ratios");
if (useRatios)
{
m_Material.DisableKeyword("RATIOS_OFF");
}
else
{
m_Material.EnableKeyword("RATIOS_OFF");
}
}
if (m_Material.HasProperty(ShaderUtilities.ShaderTag_CullMode))
{
EditorGUILayout.Space();
DoPopup("_CullMode", "Cull Mode", s_CullingTypeLabels);
}
EditorGUILayout.Space();
EditorGUI.BeginDisabledGroup(true);
DoFloat("_ScaleRatioA", "Scale Ratio A");
DoFloat("_ScaleRatioB", "Scale Ratio B");
DoFloat("_ScaleRatioC", "Scale Ratio C");
EditorGUI.EndDisabledGroup();
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoDebugPanelSRP()
{
EditorGUI.indentLevel += 1;
DoTexture2D("_MainTex", "Font Atlas");
DoFloat("_GradientScale", "Gradient Scale");
//DoFloat("_TextureWidth", "Texture Width");
//DoFloat("_TextureHeight", "Texture Height");
EditorGUILayout.Space();
/*
DoFloat("_ScaleX", "Scale X");
DoFloat("_ScaleY", "Scale Y");
if (m_Material.HasProperty(ShaderUtilities.ID_Sharpness))
DoSlider("_Sharpness", "Sharpness");
DoSlider("_PerspectiveFilter", "Perspective Filter");
EditorGUILayout.Space();
DoFloat("_VertexOffsetX", "Offset X");
DoFloat("_VertexOffsetY", "Offset Y");
if (m_Material.HasProperty(ShaderUtilities.ID_MaskCoord))
{
EditorGUILayout.Space();
s_MaskFeature.ReadState(m_Material);
s_MaskFeature.DoPopup(m_Editor, m_Material);
if (s_MaskFeature.Active)
{
DoMaskSubgroup();
}
EditorGUILayout.Space();
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
else if (m_Material.HasProperty("_MaskTex"))
{
DoMaskTexSubgroup();
}
else if (m_Material.HasProperty(ShaderUtilities.ID_MaskSoftnessX))
{
EditorGUILayout.Space();
DoFloat("_MaskSoftnessX", "Softness X");
DoFloat("_MaskSoftnessY", "Softness Y");
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
if (m_Material.HasProperty(ShaderUtilities.ID_StencilID))
{
EditorGUILayout.Space();
DoFloat("_Stencil", "Stencil ID");
DoFloat("_StencilComp", "Stencil Comp");
}
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
bool useRatios = EditorGUILayout.Toggle("Use Ratios", !m_Material.IsKeywordEnabled("RATIOS_OFF"));
if (EditorGUI.EndChangeCheck())
{
m_Editor.RegisterPropertyChangeUndo("Use Ratios");
if (useRatios)
{
m_Material.DisableKeyword("RATIOS_OFF");
}
else
{
m_Material.EnableKeyword("RATIOS_OFF");
}
}
*/
if (m_Material.HasProperty(ShaderUtilities.ShaderTag_CullMode))
{
EditorGUILayout.Space();
DoPopup("_CullMode", "Cull Mode", s_CullingTypeLabels);
}
EditorGUILayout.Space();
/*
EditorGUI.BeginDisabledGroup(true);
DoFloat("_ScaleRatioA", "Scale Ratio A");
DoFloat("_ScaleRatioB", "Scale Ratio B");
DoFloat("_ScaleRatioC", "Scale Ratio C");
EditorGUI.EndDisabledGroup();
*/
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoMaskSubgroup()
{
DoVector("_MaskCoord", "Mask Bounds", s_XywhVectorLabels);
if (Selection.activeGameObject != null)
{
Renderer renderer = Selection.activeGameObject.GetComponent<Renderer>();
if (renderer != null)
{
Rect rect = EditorGUILayout.GetControlRect();
rect.x += EditorGUIUtility.labelWidth;
rect.width -= EditorGUIUtility.labelWidth;
if (GUI.Button(rect, "Match Renderer Bounds"))
{
FindProperty("_MaskCoord", m_Properties).vectorValue = new Vector4(
0,
0,
Mathf.Round(renderer.bounds.extents.x * 1000) / 1000,
Mathf.Round(renderer.bounds.extents.y * 1000) / 1000
);
}
}
}
if (s_MaskFeature.State == 1)
{
DoFloat("_MaskSoftnessX", "Softness X");
DoFloat("_MaskSoftnessY", "Softness Y");
}
}
void DoMaskTexSubgroup()
{
EditorGUILayout.Space();
DoTexture2D("_MaskTex", "Mask Texture");
DoToggle("_MaskInverse", "Inverse Mask");
DoColor("_MaskEdgeColor", "Edge Color");
DoSlider("_MaskEdgeSoftness", "Edge Softness");
DoSlider("_MaskWipeControl", "Wipe Position");
DoFloat("_MaskSoftnessX", "Softness X");
DoFloat("_MaskSoftnessY", "Softness Y");
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
// protected override void SetupMaterialKeywordsAndPassInternal(Material material)
// {
// BaseLitGUI.SetupBaseLitKeywords(material);
// BaseLitGUI.SetupBaseLitMaterialPass(material);
// }
}
}
#endif

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: bad96c2cfa78a124cb8ec890d2386dfe
timeCreated: 1469844718
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: ea7c31b5b377c314db28ad3fabbbd38d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,63 @@
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
namespace TMPro.EditorUtilities
{
[CustomPropertyDrawer(typeof(TMP_Dropdown.OptionDataList), true)]
class DropdownOptionListDrawer : PropertyDrawer
{
private ReorderableList m_ReorderableList;
private void Init(SerializedProperty property)
{
if (m_ReorderableList != null)
return;
SerializedProperty array = property.FindPropertyRelative("m_Options");
m_ReorderableList = new ReorderableList(property.serializedObject, array);
m_ReorderableList.drawElementCallback = DrawOptionData;
m_ReorderableList.drawHeaderCallback = DrawHeader;
m_ReorderableList.elementHeight += 40;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
Init(property);
m_ReorderableList.DoList(position);
}
private void DrawHeader(Rect rect)
{
GUI.Label(rect, "Options");
}
private void DrawOptionData(Rect rect, int index, bool isActive, bool isFocused)
{
SerializedProperty itemData = m_ReorderableList.serializedProperty.GetArrayElementAtIndex(index);
SerializedProperty itemText = itemData.FindPropertyRelative("m_Text");
SerializedProperty itemImage = itemData.FindPropertyRelative("m_Image");
SerializedProperty itemColor = itemData.FindPropertyRelative("m_Color");
RectOffset offset = new RectOffset(0, 0, -1, -3);
rect = offset.Add(rect);
rect.height = EditorGUIUtility.singleLineHeight;
EditorGUI.PropertyField(rect, itemText, GUIContent.none);
rect.y += EditorGUIUtility.singleLineHeight + 2;
EditorGUI.PropertyField(rect, itemImage, GUIContent.none);
rect.y += EditorGUIUtility.singleLineHeight + 2;
EditorGUI.PropertyField(rect, itemColor, GUIContent.none);
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
Init(property);
return m_ReorderableList.GetHeight();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 705d3db7bce31a7439cc4c95cde5b04f
timeCreated: 1464818008
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,273 @@
using UnityEngine;
using UnityEditor;
namespace TMPro.EditorUtilities
{
[CustomPropertyDrawer(typeof(TextAlignmentOptions))]
public class TMP_TextAlignmentDrawer : PropertyDrawer
{
const int k_AlignmentButtonWidth = 24;
const int k_AlignmentButtonHeight = 20;
const int k_WideViewWidth = 504;
const int k_ControlsSpacing = 6;
const int k_GroupWidth = k_AlignmentButtonWidth * 6;
static readonly int k_TextAlignmentHash = "DoTextAligmentControl".GetHashCode();
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUIUtility.currentViewWidth > k_WideViewWidth ? k_AlignmentButtonHeight : k_AlignmentButtonHeight * 2 + 3;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var id = GUIUtility.GetControlID(k_TextAlignmentHash, FocusType.Keyboard, position);
EditorGUI.BeginProperty(position, label, property);
{
var controlArea = EditorGUI.PrefixLabel(position, id, label);
var horizontalAligment = new Rect(controlArea.x, controlArea.y, k_GroupWidth, k_AlignmentButtonHeight);
var verticalAligment = new Rect(!(EditorGUIUtility.currentViewWidth > k_WideViewWidth) ? controlArea.x : horizontalAligment.xMax + k_ControlsSpacing, !(EditorGUIUtility.currentViewWidth > k_WideViewWidth) ? controlArea.y + k_AlignmentButtonHeight + 3 : controlArea.y, k_GroupWidth, k_AlignmentButtonHeight);
EditorGUI.BeginChangeCheck();
var selectedHorizontal = DoHorizontalAligmentControl(horizontalAligment, property);
var selectedVertical = DoVerticalAligmentControl(verticalAligment, property);
if (EditorGUI.EndChangeCheck())
{
var value = (0x1 << selectedHorizontal) | (0x100 << selectedVertical);
property.intValue = value;
}
}
EditorGUI.EndProperty();
}
static int DoHorizontalAligmentControl(Rect position, SerializedProperty alignment)
{
var selected = TMP_EditorUtility.GetHorizontalAlignmentGridValue(alignment.intValue);
var values = new bool[6];
values[selected] = true;
if (alignment.hasMultipleDifferentValues)
{
foreach (var obj in alignment.serializedObject.targetObjects)
{
var text = obj as TMP_Text;
if (text != null)
{
values[TMP_EditorUtility.GetHorizontalAlignmentGridValue((int)text.alignment)] = true;
}
}
}
position.width = k_AlignmentButtonWidth;
for (var i = 0; i < values.Length; i++)
{
var oldValue = values[i];
var newValue = TMP_EditorUtility.EditorToggle(position, oldValue, TMP_UIStyleManager.alignContentA[i], i == 0 ? TMP_UIStyleManager.alignmentButtonLeft : (i == 5 ? TMP_UIStyleManager.alignmentButtonRight : TMP_UIStyleManager.alignmentButtonMid));
if (newValue != oldValue)
{
selected = i;
}
position.x += position.width;
}
return selected;
}
static int DoVerticalAligmentControl(Rect position, SerializedProperty alignment)
{
var selected = TMP_EditorUtility.GetVerticalAlignmentGridValue(alignment.intValue);
var values = new bool[6];
values[selected] = true;
if (alignment.hasMultipleDifferentValues)
{
foreach (var obj in alignment.serializedObject.targetObjects)
{
var text = obj as TMP_Text;
if (text != null)
{
values[TMP_EditorUtility.GetVerticalAlignmentGridValue((int)text.alignment)] = true;
}
}
}
position.width = k_AlignmentButtonWidth;
for (var i = 0; i < values.Length; i++)
{
var oldValue = values[i];
var newValue = TMP_EditorUtility.EditorToggle(position, oldValue, TMP_UIStyleManager.alignContentB[i], i == 0 ? TMP_UIStyleManager.alignmentButtonLeft : (i == 5 ? TMP_UIStyleManager.alignmentButtonRight : TMP_UIStyleManager.alignmentButtonMid));
if (newValue != oldValue)
{
selected = i;
}
position.x += position.width;
}
return selected;
}
}
[CustomPropertyDrawer(typeof(HorizontalAlignmentOptions))]
public class TMP_HorizontalAlignmentDrawer : PropertyDrawer
{
const int k_AlignmentButtonWidth = 24;
const int k_AlignmentButtonHeight = 20;
const int k_WideViewWidth = 504;
const int k_ControlsSpacing = 6;
const int k_GroupWidth = k_AlignmentButtonWidth * 6;
static readonly int k_TextAlignmentHash = "DoTextAligmentControl".GetHashCode();
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUIUtility.currentViewWidth > k_WideViewWidth ? k_AlignmentButtonHeight : k_AlignmentButtonHeight * 2 + 3;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var id = GUIUtility.GetControlID(k_TextAlignmentHash, FocusType.Keyboard, position);
EditorGUI.BeginProperty(position, label, property);
{
var controlArea = EditorGUI.PrefixLabel(position, id, label);
var horizontalAligment = new Rect(controlArea.x, controlArea.y, k_GroupWidth, k_AlignmentButtonHeight);
//var verticalAligment = new Rect(!(EditorGUIUtility.currentViewWidth > k_WideViewWidth) ? controlArea.x : horizontalAligment.xMax + k_ControlsSpacing, !(EditorGUIUtility.currentViewWidth > k_WideViewWidth) ? controlArea.y + k_AlignmentButtonHeight + 3 : controlArea.y, k_GroupWidth, k_AlignmentButtonHeight);
EditorGUI.BeginChangeCheck();
var selectedHorizontal = DoHorizontalAligmentControl(horizontalAligment, property);
if (EditorGUI.EndChangeCheck())
{
var value = 0x1 << selectedHorizontal;
property.intValue = value;
}
}
EditorGUI.EndProperty();
}
static int DoHorizontalAligmentControl(Rect position, SerializedProperty alignment)
{
var selected = TMP_EditorUtility.GetHorizontalAlignmentGridValue(alignment.intValue);
var values = new bool[6];
values[selected] = true;
if (alignment.hasMultipleDifferentValues)
{
foreach (var obj in alignment.serializedObject.targetObjects)
{
var text = obj as TMP_Text;
if (text != null)
{
values[TMP_EditorUtility.GetHorizontalAlignmentGridValue((int)text.horizontalAlignment)] = true;
}
}
}
position.width = k_AlignmentButtonWidth;
for (var i = 0; i < values.Length; i++)
{
var oldValue = values[i];
var newValue = TMP_EditorUtility.EditorToggle(position, oldValue, TMP_UIStyleManager.alignContentA[i], i == 0 ? TMP_UIStyleManager.alignmentButtonLeft : (i == 5 ? TMP_UIStyleManager.alignmentButtonRight : TMP_UIStyleManager.alignmentButtonMid));
if (newValue != oldValue)
{
selected = i;
}
position.x += position.width;
}
return selected;
}
}
[CustomPropertyDrawer(typeof(VerticalAlignmentOptions))]
public class TMP_VerticalAlignmentDrawer : PropertyDrawer
{
const int k_AlignmentButtonWidth = 24;
const int k_AlignmentButtonHeight = 20;
const int k_WideViewWidth = 504;
const int k_ControlsSpacing = 6;
const int k_GroupWidth = k_AlignmentButtonWidth * 6;
static readonly int k_TextAlignmentHash = "DoTextAligmentControl".GetHashCode();
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return EditorGUIUtility.currentViewWidth > k_WideViewWidth ? k_AlignmentButtonHeight : k_AlignmentButtonHeight * 2 + 3;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
var id = GUIUtility.GetControlID(k_TextAlignmentHash, FocusType.Keyboard, position);
EditorGUI.BeginProperty(position, label, property);
{
var controlArea = EditorGUI.PrefixLabel(position, id, label);
var horizontalAligment = new Rect(controlArea.x, controlArea.y, k_GroupWidth, k_AlignmentButtonHeight);
var verticalAligment = new Rect(!(EditorGUIUtility.currentViewWidth > k_WideViewWidth) ? controlArea.x : horizontalAligment.xMax + k_ControlsSpacing, !(EditorGUIUtility.currentViewWidth > k_WideViewWidth) ? controlArea.y + k_AlignmentButtonHeight + 3 : controlArea.y, k_GroupWidth, k_AlignmentButtonHeight);
EditorGUI.BeginChangeCheck();
//var selectedHorizontal = DoHorizontalAligmentControl(horizontalAligment, property);
var selectedVertical = DoVerticalAligmentControl(verticalAligment, property);
if (EditorGUI.EndChangeCheck())
{
var value = 0x100 << selectedVertical;
property.intValue = value;
}
}
EditorGUI.EndProperty();
}
static int DoVerticalAligmentControl(Rect position, SerializedProperty alignment)
{
var selected = TMP_EditorUtility.GetVerticalAlignmentGridValue(alignment.intValue);
var values = new bool[6];
values[selected] = true;
if (alignment.hasMultipleDifferentValues)
{
foreach (var obj in alignment.serializedObject.targetObjects)
{
var text = obj as TMP_Text;
if (text != null)
{
values[TMP_EditorUtility.GetVerticalAlignmentGridValue((int)text.verticalAlignment)] = true;
}
}
}
position.width = k_AlignmentButtonWidth;
for (var i = 0; i < values.Length; i++)
{
var oldValue = values[i];
var newValue = TMP_EditorUtility.EditorToggle(position, oldValue, TMP_UIStyleManager.alignContentB[i], i == 0 ? TMP_UIStyleManager.alignmentButtonLeft : (i == 5 ? TMP_UIStyleManager.alignmentButtonRight : TMP_UIStyleManager.alignmentButtonMid));
if (newValue != oldValue)
{
selected = i;
}
position.x += position.width;
}
return selected;
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: ea87c857d2c45f64ebe967330244a515
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 53dc282e104b7b3499778bb50cb28216
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,699 @@
using UnityEngine;
using UnityEngine.TextCore.Text;
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;
private int m_ShaderID;
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.
TextEventManager.ON_MATERIAL_PROPERTY_CHANGED(true, m_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())
{
TextEventManager.ON_MATERIAL_PROPERTY_CHANGED(true, m_Material);
}
DoDragAndDropEnd();
}
public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
{
base.AssignNewShaderToMaterial(material, oldShader, newShader);
TextEventManager.ON_MATERIAL_PROPERTY_CHANGED(true, material);
}
/// <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)
{
float objFieldSize = 60f;
bool smallLayout = EditorGUIUtility.currentViewWidth <= 330f && (withTilingOffset || speedNames != null);
float controlHeight = smallLayout ? objFieldSize * 2 : objFieldSize;
MaterialProperty property = FindProperty(name, m_Properties);
m_Editor.BeginAnimatedCheck(Rect.zero, property);
Rect rect = EditorGUILayout.GetControlRect(true, controlHeight);
float totalWidth = rect.width;
rect.width = EditorGUIUtility.labelWidth + objFieldSize;
rect.height = objFieldSize;
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;
}
float additionalHeight = controlHeight - objFieldSize;
float xOffset = smallLayout ? rect.width - objFieldSize : rect.width;
rect.y += additionalHeight;
rect.x += xOffset;
rect.width = totalWidth - xOffset;
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.40f);
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.40f);
s_TempLabel.text = "Speed";
rect = EditorGUI.PrefixLabel(rect, s_TempLabel);
EditorGUIUtility.labelWidth = 10f;
rect.width = rect.width * 0.5f - 2f;
if (names.Length == 1)
{
DoFloat2(rect, names[0]);
}
else
{
DoFloat(rect, names[0], "X");
rect.x += rect.width + 4f;
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;
}
}
void DoFloat2(Rect rect, string name)
{
MaterialProperty property = BeginProperty(name);
float x = EditorGUI.FloatField(rect, "X", property.vectorValue.x);
rect.x += rect.width + 4f;
float y = EditorGUI.FloatField(rect, "Y", property.vectorValue.y);
if (EndProperty())
{
property.vectorValue = new Vector2(x, y);
}
}
protected void DoOffset(string name, string label)
{
MaterialProperty property = BeginProperty(name);
s_TempLabel.text = label;
Vector2 value = EditorGUI.Vector2Field(EditorGUILayout.GetControlRect(), s_TempLabel, property.vectorValue);
if (EndProperty())
{
property.vectorValue = 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 DoSlider(string name, Vector2 range, string label)
{
MaterialProperty property = BeginProperty(name);
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 DoSlider(string propertyName, string propertyField, string label)
{
MaterialProperty property = BeginProperty(propertyName);
Vector2 range = property.rangeLimits;
s_TempLabel.text = label;
Vector4 value = property.vectorValue;
switch (propertyField)
{
case "X":
value.x = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.x, range.x, range.y);
break;
case "Y":
value.y = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.y, range.x, range.y);
break;
case "Z":
value.z = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.z, range.x, range.y);
break;
case "W":
value.w = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.w, range.x, range.y);
break;
}
if (EndProperty())
{
property.vectorValue = value;
}
}
protected void DoSlider(string propertyName, string propertyField, Vector2 range, string label)
{
MaterialProperty property = BeginProperty(propertyName);
s_TempLabel.text = label;
Vector4 value = property.vectorValue;
switch (propertyField)
{
case "X":
value.x = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.x, range.x, range.y);
break;
case "Y":
value.y = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.y, range.x, range.y);
break;
case "Z":
value.z = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.z, range.x, range.y);
break;
case "W":
value.w = EditorGUI.Slider(EditorGUILayout.GetControlRect(), s_TempLabel, value.w, range.x, range.y);
break;
}
if (EndProperty())
{
property.vectorValue = value;
}
}
protected void DoVector2(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 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;
}
}
bool IsNewShader()
{
if (m_Material == null)
return false;
int currentShaderID = m_Material.shader.GetInstanceID();
if (m_ShaderID == currentShaderID)
return false;
m_ShaderID = currentShaderID;
return true;
}
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);
}
}
else if (evt.type == EventType.DragExited)
{
if (IsNewShader())
TextEventManager.ON_MATERIAL_PROPERTY_CHANGED(true, m_Material);
}
}
void PerformDrop(Material droppedMaterial)
{
Texture droppedTex = droppedMaterial.GetTexture(ShaderUtilities.ID_MainTex);
if (!droppedTex)
{
return;
}
Texture currentTex = m_Material.GetTexture(ShaderUtilities.ID_MainTex);
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;
}
}
TextEventManager.ON_DRAG_AND_DROP_MATERIAL_CHANGED(o, m_Material, droppedMaterial);
EditorUtility.SetDirty(o);
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 5b568c26a0e77b24ea4badb24f550576
timeCreated: 1469844810
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,93 @@
using UnityEngine;
using UnityEditor;
namespace TMPro.EditorUtilities
{
public class TMP_BitmapShaderGUI : TMP_BaseShaderGUI
{
static bool s_Face = true;
protected override void DoGUI()
{
s_Face = BeginPanel("Face", s_Face);
if (s_Face)
{
DoFacePanel();
}
EndPanel();
s_DebugExtended = BeginPanel("Debug Settings", s_DebugExtended);
if (s_DebugExtended)
{
DoDebugPanel();
}
EndPanel();
}
void DoFacePanel()
{
EditorGUI.indentLevel += 1;
if (m_Material.HasProperty(ShaderUtilities.ID_FaceTex))
{
DoColor("_FaceColor", "Color");
DoTexture2D("_FaceTex", "Texture", true);
}
else
{
DoColor("_Color", "Color");
DoSlider("_DiffusePower", "Diffuse Power");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoDebugPanel()
{
EditorGUI.indentLevel += 1;
DoTexture2D("_MainTex", "Font Atlas");
if (m_Material.HasProperty(ShaderUtilities.ID_VertexOffsetX))
{
if (m_Material.HasProperty(ShaderUtilities.ID_Padding))
{
EditorGUILayout.Space();
DoFloat("_Padding", "Padding");
}
EditorGUILayout.Space();
DoFloat("_VertexOffsetX", "Offset X");
DoFloat("_VertexOffsetY", "Offset Y");
}
if (m_Material.HasProperty(ShaderUtilities.ID_MaskSoftnessX))
{
EditorGUILayout.Space();
DoFloat("_MaskSoftnessX", "Softness X");
DoFloat("_MaskSoftnessY", "Softness Y");
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
if (m_Material.HasProperty(ShaderUtilities.ID_StencilID))
{
EditorGUILayout.Space();
DoFloat("_Stencil", "Stencil ID");
DoFloat("_StencilComp", "Stencil Comp");
}
if (m_Material.HasProperty(ShaderUtilities.ShaderTag_CullMode))
{
EditorGUILayout.Space();
DoPopup("_CullMode", "Cull Mode", s_CullingTypeLabels);
}
EditorGUILayout.Space();
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: df3965f86289f794a967b4a8c6cfc6cb
timeCreated: 1469998850
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,48 @@
using System.IO;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEditor;
namespace TMPro.EditorUtilities
{
public static class TMP_ColorGradientAssetMenu
{
[MenuItem("Assets/Create/TextMeshPro/Text Color Gradient", false, 250)]
internal static void CreateColorGradient(MenuCommand context)
{
string filePath;
if (Selection.assetGUIDs.Length == 0)
filePath = "Assets/New Text Color Gradient.asset";
else
filePath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);
if (Directory.Exists(filePath))
{
filePath += "/New Text Color Gradient.asset";
}
else
{
filePath = Path.GetDirectoryName(filePath) + "/New Text Color Gradient.asset";
}
filePath = AssetDatabase.GenerateUniqueAssetPath(filePath);
// Create new Color Gradient Asset.
TextColorGradient colorGradient = ScriptableObject.CreateInstance<TextColorGradient>();
// Create Asset
AssetDatabase.CreateAsset(colorGradient, filePath);
//EditorUtility.SetDirty(colorGradient);
AssetDatabase.SaveAssets();
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(colorGradient));
EditorUtility.FocusProjectWindow();
EditorGUIUtility.PingObject(colorGradient);
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 7364ac159f2f5cc4dae5a5b262583afa
timeCreated: 1468187791
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,60 @@
using UnityEngine;
using UnityEditor;
using UnityEditor.UI;
using UnityEngine.UI;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TMP_Dropdown), true)]
[CanEditMultipleObjects]
public class DropdownEditor : SelectableEditor
{
SerializedProperty m_Template;
SerializedProperty m_CaptionText;
SerializedProperty m_CaptionImage;
SerializedProperty m_Placeholder;
SerializedProperty m_ItemText;
SerializedProperty m_ItemImage;
SerializedProperty m_OnSelectionChanged;
SerializedProperty m_Value;
SerializedProperty m_MultiSelect;
SerializedProperty m_AlphaFadeSpeed;
SerializedProperty m_Options;
protected override void OnEnable()
{
base.OnEnable();
m_Template = serializedObject.FindProperty("m_Template");
m_CaptionText = serializedObject.FindProperty("m_CaptionText");
m_CaptionImage = serializedObject.FindProperty("m_CaptionImage");
m_Placeholder = serializedObject.FindProperty("m_Placeholder");
m_ItemText = serializedObject.FindProperty("m_ItemText");
m_ItemImage = serializedObject.FindProperty("m_ItemImage");
m_OnSelectionChanged = serializedObject.FindProperty("m_OnValueChanged");
m_Value = serializedObject.FindProperty("m_Value");
m_MultiSelect = serializedObject.FindProperty("m_MultiSelect");
m_AlphaFadeSpeed = serializedObject.FindProperty("m_AlphaFadeSpeed");
m_Options = serializedObject.FindProperty("m_Options");
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.Space();
serializedObject.Update();
EditorGUILayout.PropertyField(m_Template);
EditorGUILayout.PropertyField(m_CaptionText);
EditorGUILayout.PropertyField(m_CaptionImage);
EditorGUILayout.PropertyField(m_Placeholder);
EditorGUILayout.PropertyField(m_ItemText);
EditorGUILayout.PropertyField(m_ItemImage);
EditorGUILayout.PropertyField(m_Value);
EditorGUILayout.PropertyField(m_MultiSelect);
EditorGUILayout.PropertyField(m_AlphaFadeSpeed);
EditorGUILayout.PropertyField(m_Options);
EditorGUILayout.PropertyField(m_OnSelectionChanged);
serializedObject.ApplyModifiedProperties();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: a2a8381dd0e0f344d8b8a5e83bd20b2b
timeCreated: 1446377461
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,96 @@
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace TMPro.EditorUtilities
{
/// <summary>
/// Simple implementation of coroutine working in the Unity Editor.
/// </summary>
public class TMP_EditorCoroutine
{
//private static Dictionary<int, EditorCoroutine> s_ActiveCoroutines;
readonly IEnumerator coroutine;
/// <summary>
/// Constructor
/// </summary>
/// <param name="routine"></param>
TMP_EditorCoroutine(IEnumerator routine)
{
this.coroutine = routine;
}
/// <summary>
/// Starts a new EditorCoroutine.
/// </summary>
/// <param name="newCoroutine">Coroutine</param>
/// <returns>new EditorCoroutine</returns>
public static TMP_EditorCoroutine StartCoroutine(IEnumerator routine)
{
TMP_EditorCoroutine coroutine = new TMP_EditorCoroutine(routine);
coroutine.Start();
// Add coroutine to tracking list
//if (s_ActiveCoroutines == null)
// s_ActiveCoroutines = new Dictionary<int, EditorCoroutine>();
// Add new instance of editor coroutine to dictionary.
//s_ActiveCoroutines.Add(coroutine.GetHashCode(), coroutine);
return coroutine;
}
/// <summary>
/// Clear delegate list
/// </summary>
//public static void StopAllEditorCoroutines()
//{
// EditorApplication.update = null;
//}
/// <summary>
/// Register callback for editor updates
/// </summary>
void Start()
{
EditorApplication.update += EditorUpdate;
}
/// <summary>
/// Unregister callback for editor updates.
/// </summary>
public void Stop()
{
if (EditorApplication.update != null)
EditorApplication.update -= EditorUpdate;
//s_ActiveCoroutines.Remove(this.GetHashCode());
}
/// <summary>
/// Delegate function called on editor updates.
/// </summary>
void EditorUpdate()
{
// Stop editor coroutine if it does not continue.
if (coroutine.MoveNext() == false)
Stop();
// Process the different types of EditorCoroutines.
if (coroutine.Current != null)
{
}
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f0dddddc28f728c42a1fed80ba8f95cc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,205 @@
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEditor;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TextMeshPro), true), CanEditMultipleObjects]
public class TMP_EditorPanel : TMP_BaseEditorPanel
{
static readonly GUIContent k_SortingLayerLabel = new GUIContent("Sorting Layer", "Name of the Renderer's sorting layer.");
static readonly GUIContent k_OrderInLayerLabel = new GUIContent("Order in Layer", "Renderer's order within a sorting layer.");
static readonly GUIContent k_OrthographicLabel = new GUIContent("Orthographic Mode", "Should be enabled when using an orthographic camera. Instructs the shader to not perform any perspective correction.");
static readonly GUIContent k_VolumetricLabel = new GUIContent("Volumetric Setup", "Use cubes rather than quads to render the text. Allows for volumetric rendering when combined with a compatible shader.");
private static string[] k_SortingLayerNames;
bool IsPreset;
SerializedProperty m_IsVolumetricTextProp;
SerializedProperty m_IsOrthographicProp;
Object[] m_Renderers;
SerializedObject m_RendererSerializedObject;
SerializedProperty m_RendererSortingLayerProp;
SerializedProperty m_RendererSortingLayerIDProp;
SerializedProperty m_RendererSortingOrderProp;
SerializedProperty m_TextSortingLayerProp;
SerializedProperty m_TextSortingLayerIDProp;
SerializedProperty m_TextSortingOrderProp;
protected override void OnEnable()
{
base.OnEnable();
// Determine if the inspected object is a Preset
IsPreset = (int)(target as Component).gameObject.hideFlags == 93;
m_IsOrthographicProp = serializedObject.FindProperty("m_isOrthographic");
m_IsVolumetricTextProp = serializedObject.FindProperty("m_isVolumetricText");
m_Renderers = new Object[targets.Length];
for (int i = 0; i < m_Renderers.Length; i++)
m_Renderers[i] = (targets[i] as TextMeshPro)?.GetComponent<Renderer>();
m_RendererSerializedObject = new SerializedObject(m_Renderers);
m_RendererSortingLayerProp = m_RendererSerializedObject.FindProperty("m_SortingLayer");
m_RendererSortingLayerIDProp = m_RendererSerializedObject.FindProperty("m_SortingLayerID");
m_RendererSortingOrderProp = m_RendererSerializedObject.FindProperty("m_SortingOrder");
m_TextSortingLayerProp = serializedObject.FindProperty("_SortingLayer");
m_TextSortingLayerIDProp = serializedObject.FindProperty("_SortingLayerID");
m_TextSortingOrderProp = serializedObject.FindProperty("_SortingOrder");
// Populate Sorting Layer Names
k_SortingLayerNames = SortingLayerHelper.sortingLayerNames;
}
protected override void DrawExtraSettings()
{
Rect rect = EditorGUILayout.GetControlRect(false, 24);
if (GUI.Button(rect, new GUIContent("<b>Extra Settings</b>"), TMP_UIStyleManager.sectionHeader))
Foldout.extraSettings = !Foldout.extraSettings;
GUI.Label(rect, (Foldout.extraSettings ? "" : k_UiStateLabel[1]), TMP_UIStyleManager.rightLabel);
if (Foldout.extraSettings)
{
//EditorGUI.indentLevel += 1;
DrawMargins();
DrawSortingLayer();
DrawGeometrySorting();
DrawIsTextObjectScaleStatic();
DrawOrthographicMode();
DrawRichText();
DrawParsing();
DrawSpriteAsset();
DrawStyleSheet();
//DrawVolumetricSetup();
DrawKerning();
DrawPadding();
//EditorGUI.indentLevel -= 1;
}
}
private void DrawSortingLayer()
{
m_RendererSerializedObject.Update();
Rect rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight);
// Special handling for Presets where the sorting layer, id and order is serialized with the text object instead of on the MeshRenderer.
SerializedProperty sortingLayerProp = IsPreset ? m_TextSortingLayerProp : m_RendererSortingLayerProp;
SerializedProperty sortingLayerIDProp = IsPreset ? m_TextSortingLayerIDProp : m_RendererSortingLayerIDProp;
EditorGUI.BeginProperty(rect, k_SortingLayerLabel, sortingLayerIDProp);
EditorGUI.BeginChangeCheck();
int currentLayerIndex = SortingLayerHelper.GetSortingLayerIndexFromSortingLayerID(sortingLayerIDProp.intValue);
int newLayerIndex = EditorGUI.Popup(rect, k_SortingLayerLabel, currentLayerIndex, k_SortingLayerNames);
if (EditorGUI.EndChangeCheck())
{
sortingLayerIDProp.intValue = SortingLayer.NameToID(k_SortingLayerNames[newLayerIndex]);
sortingLayerProp.intValue = SortingLayer.GetLayerValueFromName(k_SortingLayerNames[newLayerIndex]);
m_HavePropertiesChanged = true;
// Sync Sorting Layer ID change on potential sub text object.
TextMeshPro textComponent = m_TextComponent as TextMeshPro;
textComponent.UpdateSubMeshSortingLayerID(sortingLayerIDProp.intValue);
}
EditorGUI.EndProperty();
// Sorting Order
SerializedProperty sortingOrderLayerProp = IsPreset ? m_TextSortingOrderProp : m_RendererSortingOrderProp;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(sortingOrderLayerProp, k_OrderInLayerLabel);
if (EditorGUI.EndChangeCheck())
{
m_HavePropertiesChanged = true;
TextMeshPro textComponent = m_TextComponent as TextMeshPro;
textComponent.UpdateSubMeshSortingOrder(sortingOrderLayerProp.intValue);
}
m_RendererSerializedObject.ApplyModifiedProperties();
EditorGUILayout.Space();
}
private void DrawOrthographicMode()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_IsOrthographicProp, k_OrthographicLabel);
if (EditorGUI.EndChangeCheck())
m_HavePropertiesChanged = true;
}
protected void DrawVolumetricSetup()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_IsVolumetricTextProp, k_VolumetricLabel);
if (EditorGUI.EndChangeCheck())
{
m_HavePropertiesChanged = true;
m_TextComponent.textInfo.ResetVertexLayout(m_IsVolumetricTextProp.boolValue);
}
EditorGUILayout.Space();
}
// Method to handle multi object selection
protected override bool IsMixSelectionTypes()
{
GameObject[] objects = Selection.gameObjects;
if (objects.Length > 1)
{
for (int i = 0; i < objects.Length; i++)
{
if (objects[i].GetComponent<TextMeshPro>() == null)
return true;
}
}
return false;
}
protected override void OnUndoRedo()
{
int undoEventId = Undo.GetCurrentGroup();
int lastUndoEventId = s_EventId;
if (undoEventId != lastUndoEventId)
{
for (int i = 0; i < targets.Length; i++)
{
//Debug.Log("Undo & Redo Performed detected in Editor Panel. Event ID:" + Undo.GetCurrentGroup());
TextEventManager.ON_TEXTMESHPRO_PROPERTY_CHANGED(true, targets[i] as TextMeshPro);
s_EventId = undoEventId;
}
}
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 87553b56a6d8da547b76fc3c75a5a6f0
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,128 @@
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEngine.UI;
using UnityEditor;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TextMeshProUGUI), true), CanEditMultipleObjects]
public class TMP_EditorPanelUI : TMP_BaseEditorPanel
{
static readonly GUIContent k_RaycastTargetLabel = new GUIContent("Raycast Target", "Whether the text blocks raycasts from the Graphic Raycaster.");
static readonly GUIContent k_MaskableLabel = new GUIContent("Maskable", "Determines if the text object will be affected by UI Mask.");
SerializedProperty m_RaycastTargetProp;
private SerializedProperty m_MaskableProp;
protected override void OnEnable()
{
base.OnEnable();
m_RaycastTargetProp = serializedObject.FindProperty("m_RaycastTarget");
m_MaskableProp = serializedObject.FindProperty("m_Maskable");
}
protected override void DrawExtraSettings()
{
Rect rect = EditorGUILayout.GetControlRect(false, 24);
if (GUI.Button(rect, new GUIContent("<b>Extra Settings</b>"), TMP_UIStyleManager.sectionHeader))
Foldout.extraSettings = !Foldout.extraSettings;
GUI.Label(rect, (Foldout.extraSettings ? k_UiStateLabel[0] : k_UiStateLabel[1]), TMP_UIStyleManager.rightLabel);
if (Foldout.extraSettings)
{
//EditorGUI.indentLevel += 1;
DrawMargins();
DrawGeometrySorting();
DrawIsTextObjectScaleStatic();
DrawRichText();
DrawRaycastTarget();
DrawMaskable();
DrawParsing();
DrawSpriteAsset();
DrawStyleSheet();
DrawKerning();
DrawPadding();
//EditorGUI.indentLevel -= 1;
}
}
protected void DrawRaycastTarget()
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_RaycastTargetProp, k_RaycastTargetLabel);
if (EditorGUI.EndChangeCheck())
{
// Change needs to propagate to the child sub objects.
Graphic[] graphicComponents = m_TextComponent.GetComponentsInChildren<Graphic>();
for (int i = 1; i < graphicComponents.Length; i++)
graphicComponents[i].raycastTarget = m_RaycastTargetProp.boolValue;
m_HavePropertiesChanged = true;
}
}
protected void DrawMaskable()
{
if (m_MaskableProp == null)
return;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_MaskableProp, k_MaskableLabel);
if (EditorGUI.EndChangeCheck())
{
m_TextComponent.maskable = m_MaskableProp.boolValue;
// Change needs to propagate to the child sub objects.
MaskableGraphic[] maskableGraphics = m_TextComponent.GetComponentsInChildren<MaskableGraphic>();
for (int i = 1; i < maskableGraphics.Length; i++)
maskableGraphics[i].maskable = m_MaskableProp.boolValue;
m_HavePropertiesChanged = true;
}
}
// Method to handle multi object selection
protected override bool IsMixSelectionTypes()
{
GameObject[] objects = Selection.gameObjects;
if (objects.Length > 1)
{
for (int i = 0; i < objects.Length; i++)
{
if (objects[i].GetComponent<TextMeshProUGUI>() == null)
return true;
}
}
return false;
}
protected override void OnUndoRedo()
{
int undoEventId = Undo.GetCurrentGroup();
int lastUndoEventId = s_EventId;
if (undoEventId != lastUndoEventId)
{
for (int i = 0; i < targets.Length; i++)
{
//Debug.Log("Undo & Redo Performed detected in Editor Panel. Event ID:" + Undo.GetCurrentGroup());
TextEventManager.ON_TEXTMESHPRO_UGUI_PROPERTY_CHANGED(true, targets[i] as TextMeshProUGUI);
s_EventId = undoEventId;
}
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 115c3ac795553ef46a889d1af5ff4f10
timeCreated: 1443571501
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,448 @@
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEditor;
namespace TMPro.EditorUtilities
{
public static class TMP_EditorUtility
{
/// <summary>
/// Returns the relative path of the package.
/// </summary>
public static string packageRelativePath
{
get
{
if (string.IsNullOrEmpty(m_PackagePath))
m_PackagePath = GetPackageRelativePath();
return m_PackagePath;
}
}
[SerializeField]
private static string m_PackagePath;
/// <summary>
/// Returns the fully qualified path of the package.
/// </summary>
public static string packageFullPath
{
get
{
if (string.IsNullOrEmpty(m_PackageFullPath))
m_PackageFullPath = GetPackageFullPath();
return m_PackageFullPath;
}
}
[SerializeField]
private static string m_PackageFullPath;
// Static Fields Related to locating the TextMesh Pro Asset
private static string folderPath = "Not Found";
private static EditorWindow Gameview;
private static bool isInitialized = false;
private static void GetGameview()
{
System.Reflection.Assembly assembly = typeof(UnityEditor.EditorWindow).Assembly;
System.Type type = assembly.GetType("UnityEditor.GameView");
Gameview = EditorWindow.GetWindow(type);
}
internal static void RepaintAll()
{
if (isInitialized == false)
{
GetGameview();
isInitialized = true;
}
SceneView.RepaintAll();
Gameview.Repaint();
}
/// <summary>
/// Create and return a new asset in a smart location based on the current selection and then select it.
/// </summary>
/// <param name="name">
/// Name of the new asset. Do not include the .asset extension.
/// </param>
/// <returns>
/// The new asset.
/// </returns>
internal static T CreateAsset<T>(string name) where T : ScriptableObject
{
string path = AssetDatabase.GetAssetPath(Selection.activeObject);
if (path.Length == 0)
{
// no asset selected, place in asset root
path = "Assets/" + name + ".asset";
}
else if (Directory.Exists(path))
{
// place in currently selected directory
path += "/" + name + ".asset";
}
else {
// place in current selection's containing directory
path = Path.GetDirectoryName(path) + "/" + name + ".asset";
}
T asset = ScriptableObject.CreateInstance<T>();
AssetDatabase.CreateAsset(asset, AssetDatabase.GenerateUniqueAssetPath(path));
EditorUtility.FocusProjectWindow();
Selection.activeObject = asset;
return asset;
}
// Function used to find all materials which reference a font atlas so we can update all their references.
internal static Material[] FindMaterialReferences(FontAsset fontAsset)
{
List<Material> refs = new List<Material>();
Material mat = fontAsset.material;
refs.Add(mat);
// Get materials matching the search pattern.
string searchPattern = "t:Material" + " " + fontAsset.name.Split(new char[] { ' ' })[0];
string[] materialAssetGUIDs = AssetDatabase.FindAssets(searchPattern);
for (int i = 0; i < materialAssetGUIDs.Length; i++)
{
string materialPath = AssetDatabase.GUIDToAssetPath(materialAssetGUIDs[i]);
Material targetMaterial = AssetDatabase.LoadAssetAtPath<Material>(materialPath);
if (targetMaterial.HasProperty(ShaderUtilities.ID_MainTex) && targetMaterial.GetTexture(ShaderUtilities.ID_MainTex) != null && mat.GetTexture(ShaderUtilities.ID_MainTex) != null && targetMaterial.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID() == mat.GetTexture(ShaderUtilities.ID_MainTex).GetInstanceID())
{
if (!refs.Contains(targetMaterial))
refs.Add(targetMaterial);
}
else
{
// TODO: Find a more efficient method to unload resources.
//Resources.UnloadAsset(targetMaterial.GetTexture(ShaderUtilities.ID_MainTex));
}
}
return refs.ToArray();
}
// Function used to find the Font Asset which matches the given Material Preset and Font Atlas Texture.
internal static FontAsset FindMatchingFontAsset(Material mat)
{
if (mat.GetTexture(ShaderUtilities.ID_MainTex) == null) return null;
// Find the dependent assets of this material.
string[] dependentAssets = AssetDatabase.GetDependencies(AssetDatabase.GetAssetPath(mat), false);
for (int i = 0; i < dependentAssets.Length; i++)
{
FontAsset fontAsset = AssetDatabase.LoadAssetAtPath<FontAsset>(dependentAssets[i]);
if (fontAsset != null)
return fontAsset;
}
return null;
}
private static string GetPackageRelativePath()
{
// Check for potential UPM package
string packagePath = Path.GetFullPath("Packages/com.unity.textmeshpro");
if (Directory.Exists(packagePath))
{
return "Packages/com.unity.textmeshpro";
}
packagePath = Path.GetFullPath("Assets/..");
if (Directory.Exists(packagePath))
{
// Search default location for development package
if (Directory.Exists(packagePath + "/Assets/Packages/com.unity.TextMeshPro/Editor Resources"))
{
return "Assets/Packages/com.unity.TextMeshPro";
}
// Search for default location of normal TextMesh Pro AssetStore package
if (Directory.Exists(packagePath + "/Assets/TextMesh Pro/Editor Resources"))
{
return "Assets/TextMesh Pro";
}
// Search for potential alternative locations in the user project
string[] matchingPaths = Directory.GetDirectories(packagePath, "TextMesh Pro", SearchOption.AllDirectories);
packagePath = ValidateLocation(matchingPaths, packagePath);
if (packagePath != null) return packagePath;
}
return null;
}
private static string GetPackageFullPath()
{
// Check for potential UPM package
string packagePath = Path.GetFullPath("Packages/com.unity.textmeshpro");
if (Directory.Exists(packagePath))
{
return packagePath;
}
packagePath = Path.GetFullPath("Assets/..");
if (Directory.Exists(packagePath))
{
// Search default location for development package
if (Directory.Exists(packagePath + "/Assets/Packages/com.unity.TextMeshPro/Editor Resources"))
{
return packagePath + "/Assets/Packages/com.unity.TextMeshPro";
}
// Search for default location of normal TextMesh Pro AssetStore package
if (Directory.Exists(packagePath + "/Assets/TextMesh Pro/Editor Resources"))
{
return packagePath + "/Assets/TextMesh Pro";
}
// Search for potential alternative locations in the user project
string[] matchingPaths = Directory.GetDirectories(packagePath, "TextMesh Pro", SearchOption.AllDirectories);
string path = ValidateLocation(matchingPaths, packagePath);
if (path != null) return packagePath + path;
}
return null;
}
/// <summary>
/// Method to validate the location of the asset folder by making sure the GUISkins folder exists.
/// </summary>
/// <param name="paths"></param>
/// <returns></returns>
private static string ValidateLocation(string[] paths, string projectPath)
{
for (int i = 0; i < paths.Length; i++)
{
// Check if any of the matching directories contain a GUISkins directory.
if (Directory.Exists(paths[i] + "/Editor Resources"))
{
folderPath = paths[i].Replace(projectPath, "");
folderPath = folderPath.TrimStart('\\', '/');
return folderPath;
}
}
return null;
}
/// <summary>
/// Function which returns a string containing a sequence of Decimal character ranges.
/// </summary>
/// <param name="characterSet"></param>
/// <returns></returns>
internal static string GetDecimalCharacterSequence(int[] characterSet)
{
if (characterSet == null || characterSet.Length == 0)
return string.Empty;
string characterSequence = string.Empty;
int count = characterSet.Length;
int first = characterSet[0];
int last = first;
for (int i = 1; i < count; i++)
{
if (characterSet[i - 1] + 1 == characterSet[i])
{
last = characterSet[i];
}
else
{
if (first == last)
characterSequence += first + ",";
else
characterSequence += first + "-" + last + ",";
first = last = characterSet[i];
}
}
// handle the final group
if (first == last)
characterSequence += first;
else
characterSequence += first + "-" + last;
return characterSequence;
}
/// <summary>
/// Function which returns a string containing a sequence of Unicode (Hex) character ranges.
/// </summary>
/// <param name="characterSet"></param>
/// <returns></returns>
internal static string GetUnicodeCharacterSequence(int[] characterSet)
{
if (characterSet == null || characterSet.Length == 0)
return string.Empty;
string characterSequence = string.Empty;
int count = characterSet.Length;
int first = characterSet[0];
int last = first;
for (int i = 1; i < count; i++)
{
if (characterSet[i - 1] + 1 == characterSet[i])
{
last = characterSet[i];
}
else
{
if (first == last)
characterSequence += first.ToString("X2") + ",";
else
characterSequence += first.ToString("X2") + "-" + last.ToString("X2") + ",";
first = last = characterSet[i];
}
}
// handle the final group
if (first == last)
characterSequence += first.ToString("X2");
else
characterSequence += first.ToString("X2") + "-" + last.ToString("X2");
return characterSequence;
}
/// <summary>
///
/// </summary>
/// <param name="rect"></param>
/// <param name="thickness"></param>
/// <param name="color"></param>
internal static void DrawBox(Rect rect, float thickness, Color color)
{
EditorGUI.DrawRect(new Rect(rect.x - thickness, rect.y + thickness, rect.width + thickness * 2, thickness), color);
EditorGUI.DrawRect(new Rect(rect.x - thickness, rect.y + thickness, thickness, rect.height - thickness * 2), color);
EditorGUI.DrawRect(new Rect(rect.x - thickness, rect.y + rect.height - thickness * 2, rect.width + thickness * 2, thickness), color);
EditorGUI.DrawRect(new Rect(rect.x + rect.width, rect.y + thickness, thickness, rect.height - thickness * 2), color);
}
/// <summary>
/// Function to return the horizontal alignment grid value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
internal static int GetHorizontalAlignmentGridValue(int value)
{
if ((value & 0x1) == 0x1)
return 0;
else if ((value & 0x2) == 0x2)
return 1;
else if ((value & 0x4) == 0x4)
return 2;
else if ((value & 0x8) == 0x8)
return 3;
else if ((value & 0x10) == 0x10)
return 4;
else if ((value & 0x20) == 0x20)
return 5;
return 0;
}
/// <summary>
/// Function to return the vertical alignment grid value.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
internal static int GetVerticalAlignmentGridValue(int value)
{
if ((value & 0x100) == 0x100)
return 0;
if ((value & 0x200) == 0x200)
return 1;
if ((value & 0x400) == 0x400)
return 2;
if ((value & 0x800) == 0x800)
return 3;
if ((value & 0x1000) == 0x1000)
return 4;
if ((value & 0x2000) == 0x2000)
return 5;
return 0;
}
internal static void DrawColorProperty(Rect rect, SerializedProperty property)
{
int oldIndent = EditorGUI.indentLevel;
EditorGUI.indentLevel = 0;
if (EditorGUIUtility.wideMode)
{
EditorGUI.PropertyField(new Rect(rect.x, rect.y, 50f, rect.height), property, GUIContent.none);
rect.x += 50f;
rect.width = Mathf.Min(100f, rect.width - 55f);
}
else
{
rect.height /= 2f;
rect.width = Mathf.Min(100f, rect.width - 5f);
EditorGUI.PropertyField(rect, property, GUIContent.none);
rect.y += rect.height;
}
EditorGUI.BeginChangeCheck();
string colorString = EditorGUI.TextField(rect, string.Format("#{0}", ColorUtility.ToHtmlStringRGBA(property.colorValue)));
if (EditorGUI.EndChangeCheck())
{
Color color;
if (ColorUtility.TryParseHtmlString(colorString, out color))
{
property.colorValue = color;
}
}
EditorGUI.indentLevel = oldIndent;
}
internal static bool EditorToggle(Rect position, bool value, GUIContent content, GUIStyle style)
{
var id = GUIUtility.GetControlID(content, FocusType.Keyboard, position);
var evt = Event.current;
// Toggle selected toggle on space or return key
if (GUIUtility.keyboardControl == id && evt.type == EventType.KeyDown && (evt.keyCode == KeyCode.Space || evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter))
{
value = !value;
evt.Use();
GUI.changed = true;
}
if (evt.type == EventType.MouseDown && position.Contains(Event.current.mousePosition))
{
GUIUtility.keyboardControl = id;
EditorGUIUtility.editingTextField = false;
HandleUtility.Repaint();
}
return GUI.Toggle(position, id, value, content, style);
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 8c86041acbae1bb4a823635abfeb5c5d
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,267 @@
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.TextCore;
using UnityEngine.TextCore.LowLevel;
using UnityEngine.TextCore.Text;
using UnityEditor;
namespace TMPro
{
public static class TMP_FontAsset_CreationMenu
{
[MenuItem("Assets/Create/TextMeshPro/Font Asset Variant", false, 105)]
public static void CreateFontAssetVariant()
{
Object target = Selection.activeObject;
// Make sure the selection is a font file
if (target == null || target.GetType() != typeof(FontAsset))
{
Debug.LogWarning("A Font file must first be selected in order to create a Font Asset.");
return;
}
// Make sure TMP Essential Resources have been imported in the user project.
if (TMP_Settings.instance == null)
{
Debug.Log("Unable to create font asset. Please import the TMP Essential Resources.");
return;
}
FontAsset sourceFontAsset = (FontAsset)target;
string sourceFontFilePath = AssetDatabase.GetAssetPath(target);
string folderPath = Path.GetDirectoryName(sourceFontFilePath);
string assetName = Path.GetFileNameWithoutExtension(sourceFontFilePath);
string newAssetFilePathWithName = AssetDatabase.GenerateUniqueAssetPath(folderPath + "/" + assetName + " - Variant.asset");
// Set Texture and Material reference to the source font asset.
FontAsset fontAsset = ScriptableObject.Instantiate<FontAsset>(sourceFontAsset);
AssetDatabase.CreateAsset(fontAsset, newAssetFilePathWithName);
fontAsset.atlasPopulationMode = UnityEngine.TextCore.Text.AtlasPopulationMode.Static;
// Initialize array for the font atlas textures.
fontAsset.atlasTextures = sourceFontAsset.atlasTextures;
fontAsset.material = sourceFontAsset.material;
// Not sure if this is still necessary in newer versions of Unity.
EditorUtility.SetDirty(fontAsset);
AssetDatabase.SaveAssets();
}
/*
[MenuItem("Assets/Create/TextMeshPro/Font Asset Fallback", false, 105)]
public static void CreateFallbackFontAsset()
{
Object target = Selection.activeObject;
// Make sure the selection is a font file
if (target == null || target.GetType() != typeof(TMP_FontAsset))
{
Debug.LogWarning("A Font file must first be selected in order to create a Font Asset.");
return;
}
TMP_FontAsset sourceFontAsset = (TMP_FontAsset)target;
string sourceFontFilePath = AssetDatabase.GetAssetPath(target);
string folderPath = Path.GetDirectoryName(sourceFontFilePath);
string assetName = Path.GetFileNameWithoutExtension(sourceFontFilePath);
string newAssetFilePathWithName = AssetDatabase.GenerateUniqueAssetPath(folderPath + "/" + assetName + " - Fallback.asset");
//// Create new TM Font Asset.
TMP_FontAsset fontAsset = ScriptableObject.CreateInstance<TMP_FontAsset>();
AssetDatabase.CreateAsset(fontAsset, newAssetFilePathWithName);
fontAsset.version = "1.1.0";
fontAsset.faceInfo = sourceFontAsset.faceInfo;
fontAsset.m_SourceFontFileGUID = sourceFontAsset.m_SourceFontFileGUID;
fontAsset.m_SourceFontFile_EditorRef = sourceFontAsset.m_SourceFontFile_EditorRef;
fontAsset.atlasPopulationMode = TMP_FontAsset.AtlasPopulationMode.Dynamic;
int atlasWidth = fontAsset.atlasWidth = sourceFontAsset.atlasWidth;
int atlasHeight = fontAsset.atlasHeight = sourceFontAsset.atlasHeight;
int atlasPadding = fontAsset.atlasPadding = sourceFontAsset.atlasPadding;
fontAsset.atlasRenderMode = sourceFontAsset.atlasRenderMode;
// Initialize array for the font atlas textures.
fontAsset.atlasTextures = new Texture2D[1];
// Create and add font atlas texture
Texture2D texture = new Texture2D(atlasWidth, atlasHeight, TextureFormat.Alpha8, false);
Color32[] colors = new Color32[atlasWidth * atlasHeight];
texture.SetPixels32(colors);
texture.name = assetName + " Atlas";
fontAsset.atlasTextures[0] = texture;
AssetDatabase.AddObjectToAsset(texture, fontAsset);
// Add free rectangle of the size of the texture.
int packingModifier = ((GlyphRasterModes)fontAsset.atlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
fontAsset.m_FreeGlyphRects = new List<GlyphRect>() { new GlyphRect(0, 0, atlasWidth - packingModifier, atlasHeight - packingModifier) };
fontAsset.m_UsedGlyphRects = new List<GlyphRect>();
// Create new Material and Add it as Sub-Asset
Material tmp_material = new Material(sourceFontAsset.material);
tmp_material.name = texture.name + " Material";
tmp_material.SetTexture(ShaderUtilities.ID_MainTex, texture);
tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, atlasWidth);
tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, atlasHeight);
tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, atlasPadding + packingModifier);
tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.normalStyle);
tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyle);
fontAsset.material = tmp_material;
AssetDatabase.AddObjectToAsset(tmp_material, fontAsset);
// Add Font Asset Creation Settings
// TODO
// Not sure if this is still necessary in newer versions of Unity.
EditorUtility.SetDirty(fontAsset);
AssetDatabase.SaveAssets();
}
*/
//[MenuItem("Assets/Create/TextMeshPro/Font Asset #%F12", true)]
//public static bool CreateFontAssetMenuValidation()
//{
// return false;
//}
[MenuItem("Assets/Create/TextMeshPro/Font Asset #%F12", false, 100)]
public static void CreateFontAsset()
{
Object[] targets = Selection.objects;
if (targets == null)
{
Debug.LogWarning("A Font file must first be selected in order to create a Font Asset.");
return;
}
// Make sure TMP Essential Resources have been imported in the user project.
if (TMP_Settings.instance == null)
{
Debug.Log("Unable to create font asset. Please import the TMP Essential Resources.");
// Show Window to Import TMP Essential Resources
return;
}
for (int i = 0; i < targets.Length; i++)
{
Object target = targets[i];
// Make sure the selection is a font file
if (target == null || target.GetType() != typeof(Font))
{
Debug.LogWarning("Selected Object [" + target.name + "] is not a Font file. A Font file must be selected in order to create a Font Asset.", target);
continue;
}
CreateFontAssetFromSelectedObject(target);
}
}
static void CreateFontAssetFromSelectedObject(Object target)
{
Font font = (Font)target;
string sourceFontFilePath = AssetDatabase.GetAssetPath(target);
string folderPath = Path.GetDirectoryName(sourceFontFilePath);
string assetName = Path.GetFileNameWithoutExtension(sourceFontFilePath);
string newAssetFilePathWithName = AssetDatabase.GenerateUniqueAssetPath(folderPath + "/" + assetName + " SDF.asset");
// Initialize FontEngine
FontEngine.InitializeFontEngine();
// Load Font Face
if (FontEngine.LoadFontFace(font, 90) != FontEngineError.Success)
{
Debug.LogWarning("Unable to load font face for [" + font.name + "]. Make sure \"Include Font Data\" is enabled in the Font Import Settings.", font);
return;
}
// Create new Font Asset
FontAsset fontAsset = ScriptableObject.CreateInstance<FontAsset>();
AssetDatabase.CreateAsset(fontAsset, newAssetFilePathWithName);
fontAsset.version = "1.1.0";
fontAsset.faceInfo = FontEngine.GetFaceInfo();
// Set font reference and GUID
fontAsset.sourceFontFile = font;
fontAsset.m_SourceFontFileGUID = AssetDatabase.AssetPathToGUID(sourceFontFilePath);
fontAsset.m_SourceFontFile_EditorRef = font;
fontAsset.atlasPopulationMode = UnityEngine.TextCore.Text.AtlasPopulationMode.Dynamic;
fontAsset.clearDynamicDataOnBuild = TMP_Settings.clearDynamicDataOnBuild;
// Default atlas resolution is 1024 x 1024.
int atlasWidth = fontAsset.atlasWidth = 1024;
int atlasHeight = fontAsset.atlasHeight = 1024;
int atlasPadding = fontAsset.atlasPadding = 9;
fontAsset.atlasRenderMode = GlyphRenderMode.SDFAA;
// Initialize array for the font atlas textures.
fontAsset.atlasTextures = new Texture2D[1];
// Create atlas texture of size zero.
Texture2D texture = new Texture2D(0, 0, TextureFormat.Alpha8, false);
texture.name = assetName + " Atlas";
fontAsset.atlasTextures[0] = texture;
AssetDatabase.AddObjectToAsset(texture, fontAsset);
// Add free rectangle of the size of the texture.
int packingModifier = ((GlyphRasterModes)fontAsset.atlasRenderMode & GlyphRasterModes.RASTER_MODE_BITMAP) == GlyphRasterModes.RASTER_MODE_BITMAP ? 0 : 1;
fontAsset.freeGlyphRects = new List<GlyphRect>() { new GlyphRect(0, 0, atlasWidth - packingModifier, atlasHeight - packingModifier) };
fontAsset.usedGlyphRects = new List<GlyphRect>();
// Create new Material and Add it as Sub-Asset
Shader default_Shader = Shader.Find("TextMeshPro/Distance Field");
Material tmp_material = new Material(default_Shader);
tmp_material.name = texture.name + " Material";
tmp_material.SetTexture(ShaderUtilities.ID_MainTex, texture);
tmp_material.SetFloat(ShaderUtilities.ID_TextureWidth, atlasWidth);
tmp_material.SetFloat(ShaderUtilities.ID_TextureHeight, atlasHeight);
tmp_material.SetFloat(ShaderUtilities.ID_GradientScale, atlasPadding + packingModifier);
tmp_material.SetFloat(ShaderUtilities.ID_WeightNormal, fontAsset.regularStyleWeight);
tmp_material.SetFloat(ShaderUtilities.ID_WeightBold, fontAsset.boldStyleWeight);
fontAsset.material = tmp_material;
AssetDatabase.AddObjectToAsset(tmp_material, fontAsset);
// Add Font Asset Creation Settings
fontAsset.fontAssetCreationEditorSettings = new FontAssetCreationEditorSettings(fontAsset.m_SourceFontFileGUID, fontAsset.faceInfo.pointSize, 0, atlasPadding, 0, 1024, 1024, 7, string.Empty, (int)GlyphRenderMode.SDFAA);
// Not sure if this is still necessary in newer versions of Unity.
//EditorUtility.SetDirty(fontAsset);
AssetDatabase.SaveAssets();
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4f85302336d038c4da80ea264d185657
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,296 @@
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEditor;
using UnityEditor.UI;
using UnityEditor.AnimatedValues;
namespace TMPro.EditorUtilities
{
[CanEditMultipleObjects]
[CustomEditor(typeof(TMP_InputField), true)]
public class TMP_InputFieldEditor : SelectableEditor
{
private struct m_foldout
{ // Track Inspector foldout panel states, globally.
public static bool textInput = true;
public static bool fontSettings = true;
public static bool extraSettings = true;
//public static bool shadowSetting = false;
//public static bool materialEditor = true;
}
SerializedProperty m_TextViewport;
SerializedProperty m_TextComponent;
SerializedProperty m_Text;
SerializedProperty m_ContentType;
SerializedProperty m_LineType;
SerializedProperty m_LineLimit;
SerializedProperty m_InputType;
SerializedProperty m_CharacterValidation;
SerializedProperty m_InputValidator;
SerializedProperty m_RegexValue;
SerializedProperty m_KeyboardType;
SerializedProperty m_CharacterLimit;
SerializedProperty m_CaretBlinkRate;
SerializedProperty m_CaretWidth;
SerializedProperty m_CaretColor;
SerializedProperty m_CustomCaretColor;
SerializedProperty m_SelectionColor;
SerializedProperty m_HideMobileKeyboard;
SerializedProperty m_HideMobileInput;
SerializedProperty m_Placeholder;
SerializedProperty m_VerticalScrollbar;
SerializedProperty m_ScrollbarScrollSensitivity;
SerializedProperty m_OnValueChanged;
SerializedProperty m_OnEndEdit;
SerializedProperty m_OnSelect;
SerializedProperty m_OnDeselect;
SerializedProperty m_ReadOnly;
SerializedProperty m_RichText;
SerializedProperty m_RichTextEditingAllowed;
SerializedProperty m_ResetOnDeActivation;
SerializedProperty m_KeepTextSelectionVisible;
SerializedProperty m_RestoreOriginalTextOnEscape;
SerializedProperty m_ShouldActivateOnSelect;
SerializedProperty m_OnFocusSelectAll;
SerializedProperty m_GlobalPointSize;
SerializedProperty m_GlobalFontAsset;
AnimBool m_CustomColor;
//TMP_InputValidator m_ValidationScript;
protected override void OnEnable()
{
base.OnEnable();
m_TextViewport = serializedObject.FindProperty("m_TextViewport");
m_TextComponent = serializedObject.FindProperty("m_TextComponent");
m_Text = serializedObject.FindProperty("m_Text");
m_ContentType = serializedObject.FindProperty("m_ContentType");
m_LineType = serializedObject.FindProperty("m_LineType");
m_LineLimit = serializedObject.FindProperty("m_LineLimit");
m_InputType = serializedObject.FindProperty("m_InputType");
m_CharacterValidation = serializedObject.FindProperty("m_CharacterValidation");
m_InputValidator = serializedObject.FindProperty("m_InputValidator");
m_RegexValue = serializedObject.FindProperty("m_RegexValue");
m_KeyboardType = serializedObject.FindProperty("m_KeyboardType");
m_CharacterLimit = serializedObject.FindProperty("m_CharacterLimit");
m_CaretBlinkRate = serializedObject.FindProperty("m_CaretBlinkRate");
m_CaretWidth = serializedObject.FindProperty("m_CaretWidth");
m_CaretColor = serializedObject.FindProperty("m_CaretColor");
m_CustomCaretColor = serializedObject.FindProperty("m_CustomCaretColor");
m_SelectionColor = serializedObject.FindProperty("m_SelectionColor");
m_HideMobileKeyboard = serializedObject.FindProperty("m_HideSoftKeyboard");
m_HideMobileInput = serializedObject.FindProperty("m_HideMobileInput");
m_Placeholder = serializedObject.FindProperty("m_Placeholder");
m_VerticalScrollbar = serializedObject.FindProperty("m_VerticalScrollbar");
m_ScrollbarScrollSensitivity = serializedObject.FindProperty("m_ScrollSensitivity");
m_OnValueChanged = serializedObject.FindProperty("m_OnValueChanged");
m_OnEndEdit = serializedObject.FindProperty("m_OnEndEdit");
m_OnSelect = serializedObject.FindProperty("m_OnSelect");
m_OnDeselect = serializedObject.FindProperty("m_OnDeselect");
m_ReadOnly = serializedObject.FindProperty("m_ReadOnly");
m_RichText = serializedObject.FindProperty("m_RichText");
m_RichTextEditingAllowed = serializedObject.FindProperty("m_isRichTextEditingAllowed");
m_ResetOnDeActivation = serializedObject.FindProperty("m_ResetOnDeActivation");
m_KeepTextSelectionVisible = serializedObject.FindProperty("m_KeepTextSelectionVisible");
m_RestoreOriginalTextOnEscape = serializedObject.FindProperty("m_RestoreOriginalTextOnEscape");
m_OnFocusSelectAll = serializedObject.FindProperty("m_OnFocusSelectAll");
m_ShouldActivateOnSelect = serializedObject.FindProperty("m_ShouldActivateOnSelect");
m_GlobalPointSize = serializedObject.FindProperty("m_GlobalPointSize");
m_GlobalFontAsset = serializedObject.FindProperty("m_GlobalFontAsset");
m_CustomColor = new AnimBool(m_CustomCaretColor.boolValue);
m_CustomColor.valueChanged.AddListener(Repaint);
}
protected override void OnDisable()
{
base.OnDisable();
m_CustomColor.valueChanged.RemoveListener(Repaint);
}
public override void OnInspectorGUI()
{
serializedObject.Update();
base.OnInspectorGUI();
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_TextViewport);
EditorGUILayout.PropertyField(m_TextComponent);
TextMeshProUGUI text = null;
if (m_TextComponent != null && m_TextComponent.objectReferenceValue != null)
{
text = m_TextComponent.objectReferenceValue as TextMeshProUGUI;
//if (text.supportRichText)
//{
// EditorGUILayout.HelpBox("Using Rich Text with input is unsupported.", MessageType.Warning);
//}
}
EditorGUI.BeginDisabledGroup(m_TextComponent == null || m_TextComponent.objectReferenceValue == null);
// TEXT INPUT BOX
EditorGUILayout.PropertyField(m_Text);
// INPUT FIELD SETTINGS
#region INPUT FIELD SETTINGS
m_foldout.fontSettings = EditorGUILayout.Foldout(m_foldout.fontSettings, "Input Field Settings", true, TMP_UIStyleManager.boldFoldout);
if (m_foldout.fontSettings)
{
EditorGUI.indentLevel++;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_GlobalFontAsset, new GUIContent("Font Asset", "Set the Font Asset for both Placeholder and Input Field text object."));
if (EditorGUI.EndChangeCheck())
{
TMP_InputField inputField = target as TMP_InputField;
inputField.SetGlobalFontAsset(m_GlobalFontAsset.objectReferenceValue as FontAsset);
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_GlobalPointSize, new GUIContent("Point Size", "Set the point size of both Placeholder and Input Field text object."));
if (EditorGUI.EndChangeCheck())
{
TMP_InputField inputField = target as TMP_InputField;
inputField.SetGlobalPointSize(m_GlobalPointSize.floatValue);
}
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_CharacterLimit);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_ContentType);
if (!m_ContentType.hasMultipleDifferentValues)
{
EditorGUI.indentLevel++;
if (m_ContentType.enumValueIndex == (int)TMP_InputField.ContentType.Standard ||
m_ContentType.enumValueIndex == (int)TMP_InputField.ContentType.Autocorrected ||
m_ContentType.enumValueIndex == (int)TMP_InputField.ContentType.Custom)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_LineType);
if (EditorGUI.EndChangeCheck())
{
if (text != null)
{
if (m_LineType.enumValueIndex == (int)TMP_InputField.LineType.SingleLine)
text.textWrappingMode = TextWrappingModes.PreserveWhitespaceNoWrap;
else
{
text.textWrappingMode = TextWrappingModes.Normal;
}
}
}
if (m_LineType.enumValueIndex != (int)TMP_InputField.LineType.SingleLine)
{
EditorGUILayout.PropertyField(m_LineLimit);
}
}
if (m_ContentType.enumValueIndex == (int)TMP_InputField.ContentType.Custom)
{
EditorGUILayout.PropertyField(m_InputType);
EditorGUILayout.PropertyField(m_KeyboardType);
EditorGUILayout.PropertyField(m_CharacterValidation);
if (m_CharacterValidation.enumValueIndex == (int)TMP_InputField.CharacterValidation.Regex)
{
EditorGUILayout.PropertyField(m_RegexValue);
}
else if (m_CharacterValidation.enumValueIndex == (int)TMP_InputField.CharacterValidation.CustomValidator)
{
EditorGUILayout.PropertyField(m_InputValidator);
}
}
EditorGUI.indentLevel--;
}
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_Placeholder);
EditorGUILayout.PropertyField(m_VerticalScrollbar);
if (m_VerticalScrollbar.objectReferenceValue != null)
EditorGUILayout.PropertyField(m_ScrollbarScrollSensitivity);
EditorGUILayout.PropertyField(m_CaretBlinkRate);
EditorGUILayout.PropertyField(m_CaretWidth);
EditorGUILayout.PropertyField(m_CustomCaretColor);
m_CustomColor.target = m_CustomCaretColor.boolValue;
if (EditorGUILayout.BeginFadeGroup(m_CustomColor.faded))
{
EditorGUILayout.PropertyField(m_CaretColor);
}
EditorGUILayout.EndFadeGroup();
EditorGUILayout.PropertyField(m_SelectionColor);
EditorGUI.indentLevel--;
}
#endregion
// CONTROL SETTINGS
#region CONTROL SETTINGS
m_foldout.extraSettings = EditorGUILayout.Foldout(m_foldout.extraSettings, "Control Settings", true, TMP_UIStyleManager.boldFoldout);
if (m_foldout.extraSettings)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_OnFocusSelectAll, new GUIContent("OnFocus - Select All", "Should all the text be selected when the Input Field is selected?"));
EditorGUILayout.PropertyField(m_ResetOnDeActivation, new GUIContent("Reset On Deactivation", "Should the Text and Caret position be reset when Input Field looses focus and is Deactivated?"));
EditorGUI.indentLevel++;
GUI.enabled = !m_ResetOnDeActivation.boolValue;
EditorGUILayout.PropertyField(m_KeepTextSelectionVisible, new GUIContent("Keep Text Selection Visible", "Should the text selection remain visible when the input field looses focus and is deactivated?"));
GUI.enabled = true;
EditorGUI.indentLevel--;
EditorGUILayout.PropertyField(m_RestoreOriginalTextOnEscape, new GUIContent("Restore On ESC Key", "Should the original text be restored when pressing ESC?"));
EditorGUILayout.PropertyField(m_ShouldActivateOnSelect, new GUIContent("Should Activate On Select", "Determines if the Input Field will be activated when selected."));
EditorGUILayout.PropertyField(m_HideMobileKeyboard, new GUIContent("Hide Soft Keyboard", "Controls the visibility of the mobile virtual keyboard."));
EditorGUILayout.PropertyField(m_HideMobileInput, new GUIContent("Hide Mobile Input", "Controls the visibility of the editable text field above the mobile virtual keyboard."));
EditorGUILayout.PropertyField(m_ReadOnly);
EditorGUILayout.PropertyField(m_RichText);
EditorGUILayout.PropertyField(m_RichTextEditingAllowed, new GUIContent("Allow Rich Text Editing"));
EditorGUI.indentLevel--;
}
#endregion
EditorGUILayout.Space();
EditorGUILayout.PropertyField(m_OnValueChanged);
EditorGUILayout.PropertyField(m_OnEndEdit);
EditorGUILayout.PropertyField(m_OnSelect);
EditorGUILayout.PropertyField(m_OnDeselect);
EditorGUI.EndDisabledGroup();
serializedObject.ApplyModifiedProperties();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 93f8eb123b3a5584788171226e3095ff
timeCreated: 1457861621
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,282 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
internal class TMP_MarkupTagUpdateUtility
{
struct MarkupTagDescriptor
{
public string name;
public string tag;
public string description;
public MarkupTagDescriptor(string name, string tag, string description)
{
this.name = name;
this.tag = tag;
this.description = description;
}
public MarkupTagDescriptor(string name)
{
this.name = name;
this.tag = null;
this.description = null;
}
public static MarkupTagDescriptor linefeed = new MarkupTagDescriptor("\n");
}
private static MarkupTagDescriptor[] m_MarkupTags =
{
new MarkupTagDescriptor("BOLD", "b", "// <b>"),
new MarkupTagDescriptor("SLASH_BOLD", "/b", "// </b>"),
new MarkupTagDescriptor("ITALIC", "i", "// <i>"),
new MarkupTagDescriptor("SLASH_ITALIC", "/i", "// </i>"),
new MarkupTagDescriptor("UNDERLINE", "u", "// <u>"),
new MarkupTagDescriptor("SLASH_UNDERLINE", "/u", "// </u>"),
new MarkupTagDescriptor("STRIKETHROUGH", "s", "// <s>"),
new MarkupTagDescriptor("SLASH_STRIKETHROUGH", "/s", "// </s>"),
new MarkupTagDescriptor("SUBSCRIPT", "sub", "// <sub>"),
new MarkupTagDescriptor("SLASH_SUBSCRIPT", "/sub", "// </sub>"),
new MarkupTagDescriptor("SUPERSCRIPT", "sup", "// <sup>"),
new MarkupTagDescriptor("SLASH_SUPERSCRIPT", "/sup", "// </sup>"),
new MarkupTagDescriptor("MARK", "mark", "// <mark>"),
new MarkupTagDescriptor("SLASH_MARK", "/mark", "// </mark>"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("COLOR", "color", "// <color>"),
new MarkupTagDescriptor("SLASH_COLOR", "/color", "// </color>"),
new MarkupTagDescriptor("ALPHA", "alpha", "// <alpha>"),
new MarkupTagDescriptor("SLASH_ALPHA", "/alpha", "// </alpha>"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("FONT", "font", "// <font=\"Name of Font Asset\"> or <font family=\"Arial\" style=\"Regular\">" ),
new MarkupTagDescriptor("SLASH_FONT", "/font", "// </font>"),
new MarkupTagDescriptor("MATERIAL", "material", "// <material=\"Name of Material Preset\"> or as attribute <font=\"Name of font asset\" material=\"Name of material\">"),
new MarkupTagDescriptor("SLASH_MATERIAL", "/material", "// </material>"),
new MarkupTagDescriptor("SIZE", "size", "// <size>"),
new MarkupTagDescriptor("SLASH_SIZE", "/size", "// </size>"),
new MarkupTagDescriptor("FONT_WEIGHT", "font-weight", "// <font-weight>"),
new MarkupTagDescriptor("SLASH_FONT_WEIGHT", "/font-weight", "// </font-weight>"),
new MarkupTagDescriptor("SCALE", "scale", "// <scale>"),
new MarkupTagDescriptor("SLASH_SCALE", "/scale", "// </scale>"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("SPRITE", "sprite", "// <sprite>"),
new MarkupTagDescriptor("STYLE", "style", "// <style>"),
new MarkupTagDescriptor("SLASH_STYLE", "/style", "// </style>"),
new MarkupTagDescriptor("GRADIENT", "gradient", "// <gradient>"),
new MarkupTagDescriptor("SLASH_GRADIENT", "/gradient", "// </gradient>"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("A", "a", "// <a>"),
new MarkupTagDescriptor("SLASH_A", "/a", "// </a>"),
new MarkupTagDescriptor("LINK", "link", "// <link>"),
new MarkupTagDescriptor("SLASH_LINK", "/link", "// </link>"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("POSITION", "pos", "// <pos>"),
new MarkupTagDescriptor("SLASH_POSITION", "/pos", "// </pos>"),
new MarkupTagDescriptor("VERTICAL_OFFSET", "voffset","// <voffset>"),
new MarkupTagDescriptor("SLASH_VERTICAL_OFFSET", "/voffset", "// </voffset>"),
new MarkupTagDescriptor("ROTATE", "rotate", "// <rotate>"),
new MarkupTagDescriptor("SLASH_ROTATE", "/rotate", "// </rotate>"),
new MarkupTagDescriptor("TRANSFORM", "transform","// <transform=\"position, rotation, scale\">"),
new MarkupTagDescriptor("SLASH_TRANSFORM", "/transform", "// </transform>"),
new MarkupTagDescriptor("SPACE", "space", "// <space>"),
new MarkupTagDescriptor("SLASH_SPACE", "/space", "// </space>"),
new MarkupTagDescriptor("CHARACTER_SPACE", "cspace", "// <cspace>"),
new MarkupTagDescriptor("SLASH_CHARACTER_SPACE", "/cspace", "// </cspace>"),
new MarkupTagDescriptor("MONOSPACE", "mspace", "// <mspace>"),
new MarkupTagDescriptor("SLASH_MONOSPACE", "/mspace", "// </mspace>"),
new MarkupTagDescriptor("CHARACTER_SPACING", "character-spacing", "// <character-spacing>"),
new MarkupTagDescriptor("SLASH_CHARACTER_SPACING", "/character-spacing", "// </character-spacing>"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("ALIGN", "align", "// <align>"),
new MarkupTagDescriptor("SLASH_ALIGN", "/align", "// </align>"),
new MarkupTagDescriptor("WIDTH", "width", "// <width>"),
new MarkupTagDescriptor("SLASH_WIDTH", "/width", "// </width>"),
new MarkupTagDescriptor("MARGIN", "margin", "// <margin>"),
new MarkupTagDescriptor("SLASH_MARGIN", "/margin", "// </margin>"),
new MarkupTagDescriptor("MARGIN_LEFT", "margin-left", "// <margin-left>"),
new MarkupTagDescriptor("MARGIN_RIGHT", "margin-right", "// <margin-right>"),
new MarkupTagDescriptor("INDENT", "indent", "// <indent>"),
new MarkupTagDescriptor("SLASH_INDENT", "/indent", "// </indent>"),
new MarkupTagDescriptor("LINE_INDENT", "line-indent", "// <line-indent>"),
new MarkupTagDescriptor("SLASH_LINE_INDENT", "/line-indent", "// </line-indent>"),
new MarkupTagDescriptor("LINE_HEIGHT", "line-height", "// <line-height>"),
new MarkupTagDescriptor("SLASH_LINE_HEIGHT", "/line-height", "// </line-height>"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("NO_BREAK", "nobr", "// <nobr>"),
new MarkupTagDescriptor("SLASH_NO_BREAK", "/nobr", "// </nobr>"),
new MarkupTagDescriptor("NO_PARSE", "noparse","// <noparse>"),
new MarkupTagDescriptor("SLASH_NO_PARSE", "/noparse", "// </noparse>"),
new MarkupTagDescriptor("PAGE", "page", "// <page>"),
new MarkupTagDescriptor("SLASH_PAGE", "/page", "// </page>"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("ACTION", "action", "// <action>"),
new MarkupTagDescriptor("SLASH_ACTION", "/action", "// </action>"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("CLASS", "class", "// <class>"),
new MarkupTagDescriptor("TABLE", "table", "// <table>"),
new MarkupTagDescriptor("SLASH_TABLE", "/table", "// </table>"),
new MarkupTagDescriptor("TH", "th", "// <th>"),
new MarkupTagDescriptor("SLASH_TH", "/th", "// </th>"),
new MarkupTagDescriptor("TR", "tr", "// <tr>"),
new MarkupTagDescriptor("SLASH_TR", "/tr", "// </tr>"),
new MarkupTagDescriptor("TD", "td", "// <td>"),
new MarkupTagDescriptor("SLASH_TD", "/td", "// </td>"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("// Text Styles"),
new MarkupTagDescriptor("LOWERCASE", "lowercase", "// <lowercase>"),
new MarkupTagDescriptor("SLASH_LOWERCASE", "/lowercase", "// </lowercase>"),
new MarkupTagDescriptor("ALLCAPS", "allcaps", "// <allcaps>"),
new MarkupTagDescriptor("SLASH_ALLCAPS", "/allcaps", "// </allcaps>"),
new MarkupTagDescriptor("UPPERCASE", "uppercase", "// <uppercase>"),
new MarkupTagDescriptor("SLASH_UPPERCASE", "/uppercase", "// </uppercase>"),
new MarkupTagDescriptor("SMALLCAPS", "smallcaps", "// <smallcaps>"),
new MarkupTagDescriptor("SLASH_SMALLCAPS", "/smallcaps", "// </smallcaps>"),
new MarkupTagDescriptor("CAPITALIZE", "capitalize", "// <capitalize>"),
new MarkupTagDescriptor("SLASH_CAPITALIZE", "/capitalize", "// </capitalize>"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("// Font Features"),
new MarkupTagDescriptor("LIGA", "liga", "// <liga>"),
new MarkupTagDescriptor("SLASH_LIGA", "/liga", "// </liga>"),
new MarkupTagDescriptor("FRAC", "frac", "// <frac>"),
new MarkupTagDescriptor("SLASH_FRAC", "/frac", "// </frac>"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("// Attributes"),
new MarkupTagDescriptor("NAME", "name", "// <sprite name=\"Name of Sprite\">"),
new MarkupTagDescriptor("INDEX", "index", "// <sprite index=7>"),
new MarkupTagDescriptor("TINT", "tint", "// <tint=bool>"),
new MarkupTagDescriptor("ANIM", "anim", "// <anim=\"first frame, last frame, frame rate\">"),
new MarkupTagDescriptor("HREF", "href", "// <a href=\"url\">text to be displayed.</a>"),
new MarkupTagDescriptor("ANGLE", "angle", "// <i angle=\"40\">Italic Slant Angle</i>"),
new MarkupTagDescriptor("FAMILY", "family", "// <font family=\"Arial\">"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("// Named Colors"),
new MarkupTagDescriptor("RED", "red",""),
new MarkupTagDescriptor("GREEN", "green", ""),
new MarkupTagDescriptor("BLUE", "blue", ""),
new MarkupTagDescriptor("WHITE", "white", ""),
new MarkupTagDescriptor("BLACK", "black", ""),
new MarkupTagDescriptor("CYAN", "cyna", ""),
new MarkupTagDescriptor("MAGENTA", "magenta", ""),
new MarkupTagDescriptor("YELLOW", "yellow", ""),
new MarkupTagDescriptor("ORANGE", "orange", ""),
new MarkupTagDescriptor("PURPLE", "purple", ""),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("// Unicode Characters"),
new MarkupTagDescriptor("BR", "br", "// <br> Line Feed (LF) \\u0A"),
new MarkupTagDescriptor("ZWSP", "zwsp", "// <zwsp> Zero Width Space \\u200B"),
new MarkupTagDescriptor("NBSP", "nbsp", "// <nbsp> Non Breaking Space \\u00A0"),
new MarkupTagDescriptor("SHY", "shy", "// <shy> Soft Hyphen \\u00AD"),
new MarkupTagDescriptor("ZWJ", "zwj", "// <zwj> Zero Width Joiner \\u200D"),
new MarkupTagDescriptor("WJ", "wj", "// <wj> Word Joiner \\u2060"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("// Alignment"),
new MarkupTagDescriptor("LEFT", "left", "// <align=left>"),
new MarkupTagDescriptor("RIGHT", "right", "// <align=right>"),
new MarkupTagDescriptor("CENTER", "center", "// <align=center>"),
new MarkupTagDescriptor("JUSTIFIED", "justified", "// <align=justified>"),
new MarkupTagDescriptor("FLUSH", "flush", "// <align=flush>"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("// Prefix and Unit suffix"),
new MarkupTagDescriptor("NONE", "none", ""),
new MarkupTagDescriptor("PLUS", "+", ""),
new MarkupTagDescriptor("MINUS", "-", ""),
new MarkupTagDescriptor("PX", "px", ""),
new MarkupTagDescriptor("PLUS_PX", "+px", ""),
new MarkupTagDescriptor("MINUS_PX", "-px", ""),
new MarkupTagDescriptor("EM", "em", ""),
new MarkupTagDescriptor("PLUS_EM", "+em", ""),
new MarkupTagDescriptor("MINUS_EM", "-em", ""),
new MarkupTagDescriptor("PCT", "pct", ""),
new MarkupTagDescriptor("PLUS_PCT", "+pct", ""),
new MarkupTagDescriptor("MINUS_PCT", "-pct", ""),
new MarkupTagDescriptor("PERCENTAGE", "%", ""),
new MarkupTagDescriptor("PLUS_PERCENTAGE", "+%", ""),
new MarkupTagDescriptor("MINUS_PERCENTAGE", "-%", ""),
new MarkupTagDescriptor("HASH", "#", "// #"),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("TRUE", "true", ""),
new MarkupTagDescriptor("FALSE", "false", ""),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("INVALID", "invalid", ""),
MarkupTagDescriptor.linefeed,
new MarkupTagDescriptor("NORMAL", "normal", "// <style=\"Normal\">"),
new MarkupTagDescriptor("DEFAULT", "default", "// <font=\"Default\">"),
};
[MenuItem("Window/TextMeshPro/Internal/Update Markup Tag Hash Codes", false, 2200, true)]
static void UpdateMarkupTagHashCodes()
{
Dictionary<int, MarkupTagDescriptor> markupHashCodes = new Dictionary<int, MarkupTagDescriptor>();
string output = string.Empty;
for (int i = 0; i < m_MarkupTags.Length; i++)
{
MarkupTagDescriptor descriptor = m_MarkupTags[i];
int hashCode = descriptor.tag == null ? 0 : GetHashCodeCaseInSensitive(descriptor.tag);
if (descriptor.name == "\n")
output += "\n";
else if (hashCode == 0)
output += descriptor.name + "\n";
else
{
output += descriptor.name + " = " + hashCode + ",\t" + descriptor.description + "\n";
if (markupHashCodes.ContainsKey(hashCode) == false)
markupHashCodes.Add(hashCode, descriptor);
else
Debug.Log("[" + descriptor.name + "] with HashCode [" + hashCode + "] collides with [" + markupHashCodes[hashCode].name + "].");
}
}
Debug.Log(output);
}
/// <summary>
/// Table used to convert character to uppercase.
/// </summary>
const string k_lookupStringU = "-------------------------------- !-#$%&-()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[-]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~-";
/// <summary>
/// Get uppercase version of this ASCII character.
/// </summary>
public static char ToUpperFast(char c)
{
if (c > k_lookupStringU.Length - 1)
return c;
return k_lookupStringU[c];
}
public static int GetHashCodeCaseInSensitive(string s)
{
int hashCode = 5381;
for (int i = 0; i < s.Length; i++)
hashCode = (hashCode << 5) + hashCode ^ ToUpperFast(s[i]);
return hashCode;
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 225b67dcce9247b4c806e435b34695d2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 04722392050a47c49b7b361cdbab4617
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,29 @@
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.IO;
namespace TMPro
{
public class TMP_PostBuildProcessHandler
{
[PostProcessBuildAttribute(10000)]
public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
{
if (target == BuildTarget.iOS)
{
// Try loading the TMP Settings
TMP_Settings settings = Resources.Load<TMP_Settings>("TMP Settings");
if (settings == null || TMP_Settings.enableEmojiSupport == false)
return;
string file = Path.Combine(pathToBuiltProject, "Classes/UI/Keyboard.mm");
string content = File.ReadAllText(file);
content = content.Replace("FILTER_EMOJIS_IOS_KEYBOARD 1", "FILTER_EMOJIS_IOS_KEYBOARD 0");
File.WriteAllText(file, content);
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 70339e75bf6d99c41beb541646e89717
timeCreated: 1479886230
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,43 @@
#if !UNITY_2018_3_OR_NEWER
using UnityEditor;
namespace TMPro
{
public static class TMP_ProjectTextSettings
{
// Open Project Text Settings
[MenuItem("Edit/Project Settings/TextMeshPro Settings", false, 309)]
public static void SelectProjectTextSettings()
{
TMP_Settings textSettings = TMP_Settings.instance;
if (textSettings)
{
Selection.activeObject = textSettings;
// TODO: Do we want to ping the Project Text Settings asset in the Project Inspector
EditorUtility.FocusProjectWindow();
EditorGUIUtility.PingObject(textSettings);
}
else
TMPro_EventManager.RESOURCE_LOAD_EVENT.Add(ON_RESOURCES_LOADED);
}
// Event received when TMP resources have been loaded.
static void ON_RESOURCES_LOADED()
{
TMPro_EventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
TMP_Settings textSettings = TMP_Settings.instance;
Selection.activeObject = textSettings;
// TODO: Do we want to ping the Project Text Settings asset in the Project Inspector
EditorUtility.FocusProjectWindow();
EditorGUIUtility.PingObject(textSettings);
}
}
}
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cc2cdafa31541b5419ed60bdde4c0c6d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,159 @@
using System.Collections;
using UnityEditor;
using UnityEngine;
using UnityEngine.TextCore.Text;
namespace TMPro.EditorUtilities
{
/*[InitializeOnLoad]
class EssentialResourcesManager
{
private const string s_TMP_API_UpdaterGUID = "bde53ab20f68be04b816a9e44ae1bba2";
//const string k_EssentialResourcesShaderVersionCheckKey = "TMP.EssentialResources.ShaderVersionCheck";
static EssentialResourcesManager()
{
string currentBuildSettings = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
//Check for and inject TMP_INSTALLED
if (!currentBuildSettings.Contains("TMP_API_UPDATER_ENABLED"))
{
//PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, currentBuildSettings + ";TMP_PRESENT");
Debug.Log(currentBuildSettings + " " + EditorUserBuildSettings.selectedBuildTargetGroup);
}
}
/*static void CheckShaderVersions()
{
// Get path to TMP shader include file.
string assetPath = AssetDatabase.GUIDToAssetPath(s_TMPShaderIncludeGUID);
if (string.IsNullOrEmpty(assetPath))
return;
AssetImporter importer = AssetImporter.GetAtPath(assetPath);
if (importer != null && string.IsNullOrEmpty(importer.userData))
{
// Show Shader Import Window
TMP_EditorCoroutine.StartCoroutine(ShowShaderPackageImporterWindow());
}
SessionState.SetBool(k_EssentialResourcesShaderVersionCheckKey, true);
}
static IEnumerator ShowShaderPackageImporterWindow()
{
yield return new WaitForSeconds(5.0f);
TMP_ShaderPackageImporterWindow.ShowPackageImporterWindow();
}#1#
}*/
/*
[InitializeOnLoad]
class EssentialResourcesManager
{
private const string s_TMPShaderIncludeGUID = "407bc68d299748449bbf7f48ee690f8d";
const string k_EssentialResourcesShaderVersionCheckKey = "TMP.EssentialResources.ShaderVersionCheck";
static EssentialResourcesManager()
{
bool shaderSearched = SessionState.GetBool(k_EssentialResourcesShaderVersionCheckKey, false);
if (!EditorApplication.isPlayingOrWillChangePlaymode && !shaderSearched)
CheckShaderVersions();
}
static void CheckShaderVersions()
{
// Get path to TMP shader include file.
string assetPath = AssetDatabase.GUIDToAssetPath(s_TMPShaderIncludeGUID);
if (string.IsNullOrEmpty(assetPath))
return;
AssetImporter importer = AssetImporter.GetAtPath(assetPath);
if (importer != null && string.IsNullOrEmpty(importer.userData))
{
// Show Shader Import Window
TMP_EditorCoroutine.StartCoroutine(ShowShaderPackageImporterWindow());
}
SessionState.SetBool(k_EssentialResourcesShaderVersionCheckKey, true);
}
static IEnumerator ShowShaderPackageImporterWindow()
{
yield return new WaitForSeconds(5.0f);
TMP_ShaderPackageImporterWindow.ShowPackageImporterWindow();
}
}
*/
/*
//[InitializeOnLoad]
class TMP_ResourcesLoader
{
/// <summary>
/// Function to pre-load the TMP Resources
/// </summary>
public static void LoadTextMeshProResources()
{
//TMP_Settings.LoadDefaultSettings();
//TMP_StyleSheet.LoadDefaultStyleSheet();
}
static TMP_ResourcesLoader()
{
//Debug.Log("Loading TMP Resources...");
// Get current targetted platform
//string Settings = PlayerSettings.GetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone);
//TMPro.TMP_Settings.LoadDefaultSettings();
//TMPro.TMP_StyleSheet.LoadDefaultStyleSheet();
}
//[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
//static void OnBeforeSceneLoaded()
//{
//Debug.Log("Before scene is loaded.");
// //TMPro.TMP_Settings.LoadDefaultSettings();
// //TMPro.TMP_StyleSheet.LoadDefaultStyleSheet();
// //ShaderVariantCollection collection = new ShaderVariantCollection();
// //Shader s0 = Shader.Find("TextMeshPro/Mobile/Distance Field");
// //ShaderVariantCollection.ShaderVariant tmp_Variant = new ShaderVariantCollection.ShaderVariant(s0, UnityEngine.Rendering.PassType.Normal, string.Empty);
// //collection.Add(tmp_Variant);
// //collection.WarmUp();
//}
}
//static class TMP_ProjectSettings
//{
// [InitializeOnLoadMethod]
// static void SetProjectDefineSymbols()
// {
// string currentBuildSettings = PlayerSettings.GetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup);
// //Check for and inject TMP_INSTALLED
// if (!currentBuildSettings.Contains("TMP_PRESENT"))
// {
// PlayerSettings.SetScriptingDefineSymbolsForGroup(EditorUserBuildSettings.selectedBuildTargetGroup, currentBuildSettings + ";TMP_PRESENT");
// }
// }
//}
*/
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: fa98276813a22a34d86255568892b322
timeCreated: 1465441092
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,789 @@
using UnityEngine;
using UnityEditor;
namespace TMPro.EditorUtilities
{
public class TMP_SDFShaderGUI : TMP_BaseShaderGUI
{
static ShaderFeature s_OutlineFeature, s_UnderlayFeature, s_BevelFeature, s_GlowFeature, s_MaskFeature;
static bool s_Face = true, s_Outline = true, s_Outline2 = true, s_Outline3 = true, s_Underlay = true, s_Lighting = true, s_Glow, s_Bevel, s_Light, s_Bump, s_Env;
static string[]
s_FaceUVSpeedName = { "_FaceUVSpeed" },
s_FaceUvSpeedNames = { "_FaceUVSpeedX", "_FaceUVSpeedY" },
s_OutlineUvSpeedNames = { "_OutlineUVSpeedX", "_OutlineUVSpeedY" },
s_OutlineUvSpeedName = { "_OutlineUVSpeed" };
static TMP_SDFShaderGUI()
{
s_OutlineFeature = new ShaderFeature()
{
undoLabel = "Outline",
keywords = new[] { "OUTLINE_ON" }
};
s_UnderlayFeature = new ShaderFeature()
{
undoLabel = "Underlay",
keywords = new[] { "UNDERLAY_ON", "UNDERLAY_INNER" },
label = new GUIContent("Underlay Type"),
keywordLabels = new[]
{
new GUIContent("None"), new GUIContent("Normal"), new GUIContent("Inner")
}
};
s_BevelFeature = new ShaderFeature()
{
undoLabel = "Bevel",
keywords = new[] { "BEVEL_ON" }
};
s_GlowFeature = new ShaderFeature()
{
undoLabel = "Glow",
keywords = new[] { "GLOW_ON" }
};
s_MaskFeature = new ShaderFeature()
{
undoLabel = "Mask",
keywords = new[] { "MASK_HARD", "MASK_SOFT" },
label = new GUIContent("Mask"),
keywordLabels = new[]
{
new GUIContent("Mask Off"), new GUIContent("Mask Hard"), new GUIContent("Mask Soft")
}
};
}
protected override void DoGUI()
{
bool isSRPMaterial = m_Material.HasProperty(ShaderUtilities.ID_IsoPerimeter);
s_Face = BeginPanel("Face", s_Face);
if (s_Face)
{
DoFacePanel();
}
EndPanel();
// Outline panels
if (isSRPMaterial)
{
DoOutlinePanels();
}
else
{
s_Outline = m_Material.HasProperty(ShaderUtilities.ID_OutlineTex) ? BeginPanel("Outline", s_Outline) : BeginPanel("Outline", s_OutlineFeature, s_Outline);
if (s_Outline)
{
DoOutlinePanel();
}
EndPanel();
if (m_Material.HasProperty(ShaderUtilities.ID_Outline2Color))
{
s_Outline2 = BeginPanel("Outline 2", s_OutlineFeature, s_Outline2);
if (s_Outline2)
{
DoOutline2Panel();
}
EndPanel();
}
}
// Underlay panel
if (m_Material.HasProperty(ShaderUtilities.ID_UnderlayColor))
{
if (isSRPMaterial)
{
s_Underlay = BeginPanel("Underlay", s_Underlay);
if (s_Underlay)
{
DoUnderlayPanel();
}
EndPanel();
}
else
{
s_Underlay = BeginPanel("Underlay", s_UnderlayFeature, s_Underlay);
if (s_Underlay)
{
DoUnderlayPanel();
}
EndPanel();
}
}
// Lighting panel
if (m_Material.HasProperty("_SpecularColor"))
{
if (isSRPMaterial)
DrawLightingPanelSRP();
else
DrawLightingPanelLegacy();
}
else if (m_Material.HasProperty("_SpecColor"))
{
s_Bevel = BeginPanel("Bevel", s_Bevel);
if (s_Bevel)
{
DoBevelPanel();
}
EndPanel();
s_Light = BeginPanel("Surface Lighting", s_Light);
if (s_Light)
{
DoSurfaceLightingPanel();
}
EndPanel();
s_Bump = BeginPanel("Bump Map", s_Bump);
if (s_Bump)
{
DoBumpMapPanel();
}
EndPanel();
s_Env = BeginPanel("Environment Map", s_Env);
if (s_Env)
{
DoEnvMapPanel();
}
EndPanel();
}
if (m_Material.HasProperty(ShaderUtilities.ID_GlowColor))
{
s_Glow = BeginPanel("Glow", s_GlowFeature, s_Glow);
if (s_Glow)
{
DoGlowPanel();
}
EndPanel();
}
s_DebugExtended = BeginPanel("Debug Settings", s_DebugExtended);
if (s_DebugExtended)
{
if (isSRPMaterial)
DoDebugPanelSRP();
else
DoDebugPanel();
}
EndPanel();
EditorGUILayout.Space();
EditorGUILayout.Space();
if (isSRPMaterial)
{
m_Editor.RenderQueueField();
m_Editor.EnableInstancingField();
m_Editor.DoubleSidedGIField();
m_Editor.EmissionEnabledProperty();
}
}
private void DrawLightingPanelSRP()
{
s_Lighting = BeginPanel("Lighting", s_Lighting);
if (s_Lighting)
{
s_Bevel = BeginPanel("Bevel", s_Bevel);
if (s_Bevel)
{
DoBevelPanelSRP();
}
EndPanel();
s_Light = BeginPanel("Local Lighting", s_Light);
if (s_Light)
{
DoLocalLightingPanel();
}
EndPanel();
}
EndPanel();
}
private void DrawLightingPanelLegacy()
{
s_Lighting = BeginPanel("Lighting", s_BevelFeature, s_Lighting);
if (s_Lighting)
{
s_Bevel = BeginPanel("Bevel", s_Bevel);
if (s_Bevel)
{
DoBevelPanel();
}
EndPanel();
s_Light = BeginPanel("Local Lighting", s_Light);
if (s_Light)
{
DoLocalLightingPanel();
}
EndPanel();
s_Bump = BeginPanel("Bump Map", s_Bump);
if (s_Bump)
{
DoBumpMapPanel();
}
EndPanel();
s_Env = BeginPanel("Environment Map", s_Env);
if (s_Env)
{
DoEnvMapPanel();
}
EndPanel();
}
EndPanel();
}
void DoFacePanel()
{
EditorGUI.indentLevel += 1;
DoColor("_FaceColor", "Color");
if (m_Material.HasProperty(ShaderUtilities.ID_FaceTex))
{
if (m_Material.HasProperty("_FaceUVSpeedX"))
{
DoTexture2D("_FaceTex", "Texture", true, s_FaceUvSpeedNames);
}
else if (m_Material.HasProperty("_FaceUVSpeed"))
{
DoTexture2D("_FaceTex", "Texture", true, s_FaceUVSpeedName);
}
else
{
DoTexture2D("_FaceTex", "Texture", true);
}
}
if (m_Material.HasProperty("_Softness"))
{
DoSlider("_Softness", "X", new Vector2(0, 1), "Softness");
}
if (m_Material.HasProperty("_OutlineSoftness"))
{
DoSlider("_OutlineSoftness", "Softness");
}
if (m_Material.HasProperty(ShaderUtilities.ID_FaceDilate))
{
DoSlider("_FaceDilate", "Dilate");
if (m_Material.HasProperty(ShaderUtilities.ID_Shininess))
{
DoSlider("_FaceShininess", "Gloss");
}
}
if (m_Material.HasProperty(ShaderUtilities.ID_IsoPerimeter))
{
DoSlider("_IsoPerimeter", "X", new Vector2(-1, 1), "Dilate");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoOutlinePanel()
{
EditorGUI.indentLevel += 1;
DoColor("_OutlineColor", "Color");
if (m_Material.HasProperty(ShaderUtilities.ID_OutlineTex))
{
if (m_Material.HasProperty("_OutlineUVSpeedX"))
{
DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedNames);
}
else if (m_Material.HasProperty("_OutlineUVSpeed"))
{
DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedName);
}
else
{
DoTexture2D("_OutlineTex", "Texture", true);
}
}
DoSlider("_OutlineWidth", "Thickness");
if (m_Material.HasProperty("_OutlineShininess"))
{
DoSlider("_OutlineShininess", "Gloss");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoOutlinePanel(int outlineID, string propertyField, string label)
{
EditorGUI.indentLevel += 1;
DoColor("_OutlineColor" + outlineID, label);
if (outlineID != 3)
DoOffset("_OutlineOffset" + outlineID, "Offset");
else
{
if (m_Material.GetFloat(ShaderUtilities.ID_OutlineMode) == 0)
DoOffset("_OutlineOffset" + outlineID, "Offset");
}
DoSlider("_Softness", propertyField, new Vector2(0, 1), "Softness");
DoSlider("_IsoPerimeter", propertyField, new Vector2(-1, 1), "Dilate");
if (outlineID == 3)
{
DoToggle("_OutlineMode", "Outline Mode");
}
if (m_Material.HasProperty("_OutlineShininess"))
{
//DoSlider("_OutlineShininess", "Gloss");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoOutlinePanelWithTexture(int outlineID, string propertyField, string label)
{
EditorGUI.indentLevel += 1;
DoColor("_OutlineColor" + outlineID, label);
if (m_Material.HasProperty(ShaderUtilities.ID_OutlineTex))
{
if (m_Material.HasProperty("_OutlineUVSpeedX"))
{
DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedNames);
}
else if (m_Material.HasProperty("_OutlineUVSpeed"))
{
DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedName);
}
else
{
DoTexture2D("_OutlineTex", "Texture", true);
}
}
DoOffset("_OutlineOffset" + outlineID, "Offset");
DoSlider("_Softness", propertyField, new Vector2(0, 1), "Softness");
DoSlider("_IsoPerimeter", propertyField, new Vector2(-1, 1), "Dilate");
if (m_Material.HasProperty("_OutlineShininess"))
{
//DoSlider("_OutlineShininess", "Gloss");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoOutline2Panel()
{
EditorGUI.indentLevel += 1;
DoColor("_Outline2Color", "Color");
//if (m_Material.HasProperty(ShaderUtilities.ID_OutlineTex))
//{
// if (m_Material.HasProperty("_OutlineUVSpeedX"))
// {
// DoTexture2D("_OutlineTex", "Texture", true, s_OutlineUvSpeedNames);
// }
// else
// {
// DoTexture2D("_OutlineTex", "Texture", true);
// }
//}
DoSlider("_Outline2Width", "Thickness");
//if (m_Material.HasProperty("_OutlineShininess"))
//{
// DoSlider("_OutlineShininess", "Gloss");
//}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoOutlinePanels()
{
s_Outline = BeginPanel("Outline 1", s_Outline);
if (s_Outline)
DoOutlinePanelWithTexture(1, "Y", "Color");
EndPanel();
s_Outline2 = BeginPanel("Outline 2", s_Outline2);
if (s_Outline2)
DoOutlinePanel(2, "Z", "Color");
EndPanel();
s_Outline3 = BeginPanel("Outline 3", s_Outline3);
if (s_Outline3)
DoOutlinePanel(3, "W", "Color");
EndPanel();
}
void DoUnderlayPanel()
{
EditorGUI.indentLevel += 1;
if (m_Material.HasProperty(ShaderUtilities.ID_IsoPerimeter))
{
DoColor("_UnderlayColor", "Color");
DoSlider("_UnderlayOffset", "X", new Vector2(-1, 1), "Offset X");
DoSlider("_UnderlayOffset", "Y", new Vector2(-1, 1), "Offset Y");
DoSlider("_UnderlayDilate", new Vector2(-1, 1), "Dilate");
DoSlider("_UnderlaySoftness", new Vector2(0, 1), "Softness");
}
else
{
s_UnderlayFeature.DoPopup(m_Editor, m_Material);
DoColor("_UnderlayColor", "Color");
DoSlider("_UnderlayOffsetX", "Offset X");
DoSlider("_UnderlayOffsetY", "Offset Y");
DoSlider("_UnderlayDilate", "Dilate");
DoSlider("_UnderlaySoftness", "Softness");
}
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
static GUIContent[] s_BevelTypeLabels =
{
new GUIContent("Outer Bevel"),
new GUIContent("Inner Bevel")
};
void DoBevelPanel()
{
EditorGUI.indentLevel += 1;
DoPopup("_ShaderFlags", "Type", s_BevelTypeLabels);
DoSlider("_Bevel", "Amount");
DoSlider("_BevelOffset", "Offset");
DoSlider("_BevelWidth", "Width");
DoSlider("_BevelRoundness", "Roundness");
DoSlider("_BevelClamp", "Clamp");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoBevelPanelSRP()
{
EditorGUI.indentLevel += 1;
DoPopup("_BevelType", "Type", s_BevelTypeLabels);
DoSlider("_BevelAmount", "Amount");
DoSlider("_BevelOffset", "Offset");
DoSlider("_BevelWidth", "Width");
DoSlider("_BevelRoundness", "Roundness");
DoSlider("_BevelClamp", "Clamp");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoLocalLightingPanel()
{
EditorGUI.indentLevel += 1;
DoSlider("_LightAngle", "Light Angle");
DoColor("_SpecularColor", "Specular Color");
DoSlider("_SpecularPower", "Specular Power");
DoSlider("_Reflectivity", "Reflectivity Power");
DoSlider("_Diffuse", "Diffuse Shadow");
DoSlider("_Ambient", "Ambient Shadow");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoSurfaceLightingPanel()
{
EditorGUI.indentLevel += 1;
DoColor("_SpecColor", "Specular Color");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoBumpMapPanel()
{
EditorGUI.indentLevel += 1;
DoTexture2D("_BumpMap", "Texture");
DoSlider("_BumpFace", "Face");
DoSlider("_BumpOutline", "Outline");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoEnvMapPanel()
{
EditorGUI.indentLevel += 1;
DoColor("_ReflectFaceColor", "Face Color");
DoColor("_ReflectOutlineColor", "Outline Color");
DoCubeMap("_Cube", "Texture");
DoVector3("_EnvMatrixRotation", "Rotation");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoGlowPanel()
{
EditorGUI.indentLevel += 1;
DoColor("_GlowColor", "Color");
DoSlider("_GlowOffset", "Offset");
DoSlider("_GlowInner", "Inner");
DoSlider("_GlowOuter", "Outer");
DoSlider("_GlowPower", "Power");
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoDebugPanel()
{
EditorGUI.indentLevel += 1;
DoTexture2D("_MainTex", "Font Atlas");
DoFloat("_GradientScale", "Gradient Scale");
DoFloat("_TextureWidth", "Texture Width");
DoFloat("_TextureHeight", "Texture Height");
EditorGUILayout.Space();
DoFloat("_ScaleX", "Scale X");
DoFloat("_ScaleY", "Scale Y");
if (m_Material.HasProperty(ShaderUtilities.ID_Sharpness))
DoSlider("_Sharpness", "Sharpness");
DoSlider("_PerspectiveFilter", "Perspective Filter");
EditorGUILayout.Space();
DoFloat("_VertexOffsetX", "Offset X");
DoFloat("_VertexOffsetY", "Offset Y");
if (m_Material.HasProperty(ShaderUtilities.ID_MaskCoord))
{
EditorGUILayout.Space();
s_MaskFeature.ReadState(m_Material);
s_MaskFeature.DoPopup(m_Editor, m_Material);
if (s_MaskFeature.Active)
{
DoMaskSubgroup();
}
EditorGUILayout.Space();
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
else if (m_Material.HasProperty("_MaskTex"))
{
DoMaskTexSubgroup();
}
else if (m_Material.HasProperty(ShaderUtilities.ID_MaskSoftnessX))
{
EditorGUILayout.Space();
DoFloat("_MaskSoftnessX", "Softness X");
DoFloat("_MaskSoftnessY", "Softness Y");
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
if (m_Material.HasProperty(ShaderUtilities.ID_StencilID))
{
EditorGUILayout.Space();
DoFloat("_Stencil", "Stencil ID");
DoFloat("_StencilComp", "Stencil Comp");
}
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
bool useRatios = EditorGUILayout.Toggle("Use Ratios", !m_Material.IsKeywordEnabled("RATIOS_OFF"));
if (EditorGUI.EndChangeCheck())
{
m_Editor.RegisterPropertyChangeUndo("Use Ratios");
if (useRatios)
{
m_Material.DisableKeyword("RATIOS_OFF");
}
else
{
m_Material.EnableKeyword("RATIOS_OFF");
}
}
if (m_Material.HasProperty(ShaderUtilities.ShaderTag_CullMode))
{
EditorGUILayout.Space();
DoPopup("_CullMode", "Cull Mode", s_CullingTypeLabels);
}
EditorGUILayout.Space();
EditorGUI.BeginDisabledGroup(true);
DoFloat("_ScaleRatioA", "Scale Ratio A");
DoFloat("_ScaleRatioB", "Scale Ratio B");
DoFloat("_ScaleRatioC", "Scale Ratio C");
EditorGUI.EndDisabledGroup();
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoDebugPanelSRP()
{
EditorGUI.indentLevel += 1;
DoTexture2D("_MainTex", "Font Atlas");
DoFloat("_GradientScale", "Gradient Scale");
//DoFloat("_TextureWidth", "Texture Width");
//DoFloat("_TextureHeight", "Texture Height");
EditorGUILayout.Space();
/*
DoFloat("_ScaleX", "Scale X");
DoFloat("_ScaleY", "Scale Y");
if (m_Material.HasProperty(ShaderUtilities.ID_Sharpness))
DoSlider("_Sharpness", "Sharpness");
DoSlider("_PerspectiveFilter", "Perspective Filter");
EditorGUILayout.Space();
DoFloat("_VertexOffsetX", "Offset X");
DoFloat("_VertexOffsetY", "Offset Y");
if (m_Material.HasProperty(ShaderUtilities.ID_MaskCoord))
{
EditorGUILayout.Space();
s_MaskFeature.ReadState(m_Material);
s_MaskFeature.DoPopup(m_Editor, m_Material);
if (s_MaskFeature.Active)
{
DoMaskSubgroup();
}
EditorGUILayout.Space();
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
else if (m_Material.HasProperty("_MaskTex"))
{
DoMaskTexSubgroup();
}
else if (m_Material.HasProperty(ShaderUtilities.ID_MaskSoftnessX))
{
EditorGUILayout.Space();
DoFloat("_MaskSoftnessX", "Softness X");
DoFloat("_MaskSoftnessY", "Softness Y");
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
if (m_Material.HasProperty(ShaderUtilities.ID_StencilID))
{
EditorGUILayout.Space();
DoFloat("_Stencil", "Stencil ID");
DoFloat("_StencilComp", "Stencil Comp");
}
EditorGUILayout.Space();
EditorGUI.BeginChangeCheck();
bool useRatios = EditorGUILayout.Toggle("Use Ratios", !m_Material.IsKeywordEnabled("RATIOS_OFF"));
if (EditorGUI.EndChangeCheck())
{
m_Editor.RegisterPropertyChangeUndo("Use Ratios");
if (useRatios)
{
m_Material.DisableKeyword("RATIOS_OFF");
}
else
{
m_Material.EnableKeyword("RATIOS_OFF");
}
}
*/
if (m_Material.HasProperty(ShaderUtilities.ShaderTag_CullMode))
{
EditorGUILayout.Space();
DoPopup("_CullMode", "Cull Mode", s_CullingTypeLabels);
}
EditorGUILayout.Space();
/*
EditorGUI.BeginDisabledGroup(true);
DoFloat("_ScaleRatioA", "Scale Ratio A");
DoFloat("_ScaleRatioB", "Scale Ratio B");
DoFloat("_ScaleRatioC", "Scale Ratio C");
EditorGUI.EndDisabledGroup();
*/
EditorGUI.indentLevel -= 1;
EditorGUILayout.Space();
}
void DoMaskSubgroup()
{
DoVector("_MaskCoord", "Mask Bounds", s_XywhVectorLabels);
if (Selection.activeGameObject != null)
{
Renderer renderer = Selection.activeGameObject.GetComponent<Renderer>();
if (renderer != null)
{
Rect rect = EditorGUILayout.GetControlRect();
rect.x += EditorGUIUtility.labelWidth;
rect.width -= EditorGUIUtility.labelWidth;
if (GUI.Button(rect, "Match Renderer Bounds"))
{
FindProperty("_MaskCoord", m_Properties).vectorValue = new Vector4(
0,
0,
Mathf.Round(renderer.bounds.extents.x * 1000) / 1000,
Mathf.Round(renderer.bounds.extents.y * 1000) / 1000
);
}
}
}
if (s_MaskFeature.State == 1)
{
DoFloat("_MaskSoftnessX", "Softness X");
DoFloat("_MaskSoftnessY", "Softness Y");
}
}
void DoMaskTexSubgroup()
{
EditorGUILayout.Space();
DoTexture2D("_MaskTex", "Mask Texture");
DoToggle("_MaskInverse", "Inverse Mask");
DoColor("_MaskEdgeColor", "Edge Color");
DoSlider("_MaskEdgeSoftness", "Edge Softness");
DoSlider("_MaskWipeControl", "Wipe Position");
DoFloat("_MaskSoftnessX", "Softness X");
DoFloat("_MaskSoftnessY", "Softness Y");
DoVector("_ClipRect", "Clip Rect", s_LbrtVectorLabels);
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: fe0610393aaf569459bdbeac92ecb1b0
timeCreated: 1469844718
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,15 @@
using UnityEngine;
using UnityEngine.TextCore.Text;
namespace TMPro
{
class TMP_SerializedPropertyHolder : ScriptableObject
{
public FontAsset fontAsset;
public uint firstCharacter;
public uint secondCharacter;
public TMP_GlyphPairAdjustmentRecord glyphPairAdjustmentRecord = new TMP_GlyphPairAdjustmentRecord(new TMP_GlyphAdjustmentRecord(), new TMP_GlyphAdjustmentRecord());
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6cb70951b63cb5a47b9a3db630ee8c3b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,410 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEditor;
using UnityEditorInternal;
#pragma warning disable 0414 // Disabled a few warnings for not yet implemented features.
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TMP_Settings))]
public class TMP_SettingsEditor : Editor
{
internal class Styles
{
public static readonly GUIContent defaultFontAssetLabel = new GUIContent("Default Font Asset", "The Font Asset that will be assigned by default to newly created text objects when no Font Asset is specified.");
public static readonly GUIContent defaultFontAssetPathLabel = new GUIContent("Path: Resources/", "The relative path to a Resources folder where the Font Assets and Material Presets are located.\nExample \"Fonts & Materials/\"");
public static readonly GUIContent fallbackFontAssetsLabel = new GUIContent("Fallback Font Assets", "The Font Assets that will be searched to locate and replace missing characters from a given Font Asset.");
public static readonly GUIContent fallbackFontAssetsListLabel = new GUIContent("Fallback Font Assets List", "The Font Assets that will be searched to locate and replace missing characters from a given Font Asset.");
public static readonly GUIContent fallbackMaterialSettingsLabel = new GUIContent("Fallback Material Settings");
public static readonly GUIContent matchMaterialPresetLabel = new GUIContent("Match Material Presets");
public static readonly GUIContent hideSubTextObjectsPresetLabel = new GUIContent("Hide Sub Text Objects", "Determines if sub text objects will be hidden in the scene hierarchy. Property change will only take effect after entering or existing play mode.");
public static readonly GUIContent containerDefaultSettingsLabel = new GUIContent("Text Container Default Settings");
public static readonly GUIContent textMeshProLabel = new GUIContent("TextMeshPro");
public static readonly GUIContent textMeshProUiLabel = new GUIContent("TextMeshPro UI");
public static readonly GUIContent enableRaycastTarget = new GUIContent("Enable Raycast Target");
public static readonly GUIContent autoSizeContainerLabel = new GUIContent("Auto Size Text Container", "Set the size of the text container to match the text.");
public static readonly GUIContent isTextObjectScaleStaticLabel = new GUIContent("Is Object Scale Static", "Disables calling InternalUpdate() when enabled. This can improve performance when text object scale is static.");
public static readonly GUIContent textComponentDefaultSettingsLabel = new GUIContent("Text Component Default Settings");
public static readonly GUIContent defaultFontSize = new GUIContent("Default Font Size");
public static readonly GUIContent autoSizeRatioLabel = new GUIContent("Text Auto Size Ratios");
public static readonly GUIContent minLabel = new GUIContent("Min");
public static readonly GUIContent maxLabel = new GUIContent("Max");
public static readonly GUIContent textWrappingModeLabel = new GUIContent("Text Wrapping Mode");
public static readonly GUIContent kerningLabel = new GUIContent("Kerning");
public static readonly GUIContent extraPaddingLabel = new GUIContent("Extra Padding");
public static readonly GUIContent tintAllSpritesLabel = new GUIContent("Tint All Sprites");
public static readonly GUIContent parseEscapeCharactersLabel = new GUIContent("Parse Escape Sequence");
public static readonly GUIContent dynamicFontSystemSettingsLabel = new GUIContent("Dynamic Font System Settings");
public static readonly GUIContent getFontFeaturesAtRuntime = new GUIContent("Get Font Features at Runtime", "Determines if Glyph Adjustment Data will be retrieved from font files at runtime when new characters and glyphs are added to font assets.");
public static readonly GUIContent dynamicAtlasTextureGroup = new GUIContent("Dynamic Atlas Texture Group");
public static readonly GUIContent missingGlyphLabel = new GUIContent("Missing Character Unicode", "The character to be displayed when the requested character is not found in any font asset or fallbacks.");
public static readonly GUIContent clearDynamicDataOnBuildLabel = new GUIContent("Clear Dynamic Data On Build", "Determines if the \"Clear Dynamic Data on Build\" property will be set to true or false on newly created dynamic font assets.");
public static readonly GUIContent disableWarningsLabel = new GUIContent("Disable warnings", "Disable warning messages in the Console.");
public static readonly GUIContent defaultSpriteAssetLabel = new GUIContent("Default Sprite Asset", "The Sprite Asset that will be assigned by default when using the <sprite> tag when no Sprite Asset is specified.");
public static readonly GUIContent missingSpriteCharacterUnicodeLabel = new GUIContent("Missing Sprite Unicode", "The unicode value for the sprite character to be displayed when the requested sprite character is not found in any sprite assets or fallbacks.");
public static readonly GUIContent enableEmojiSupportLabel = new GUIContent("iOS Emoji Support", "Enables Emoji support for Touch Screen Keyboards on target devices.");
//public static readonly GUIContent spriteRelativeScale = new GUIContent("Relative Scaling", "Determines if the sprites will be scaled relative to the primary font asset assigned to the text object or relative to the current font asset.");
public static readonly GUIContent spriteAssetsPathLabel = new GUIContent("Path: Resources/", "The relative path to a Resources folder where the Sprite Assets are located.\nExample \"Sprite Assets/\"");
public static readonly GUIContent defaultStyleSheetLabel = new GUIContent("Default Style Sheet", "The Style Sheet that will be used for all text objects in this project.");
public static readonly GUIContent styleSheetResourcePathLabel = new GUIContent("Path: Resources/", "The relative path to a Resources folder where the Style Sheets are located.\nExample \"Style Sheets/\"");
public static readonly GUIContent colorGradientPresetsLabel = new GUIContent("Color Gradient Presets", "The relative path to a Resources folder where the Color Gradient Presets are located.\nExample \"Color Gradient Presets/\"");
public static readonly GUIContent colorGradientsPathLabel = new GUIContent("Path: Resources/", "The relative path to a Resources folder where the Color Gradient Presets are located.\nExample \"Color Gradient Presets/\"");
public static readonly GUIContent lineBreakingLabel = new GUIContent("Line Breaking for Asian languages", "The text assets that contain the Leading and Following characters which define the rules for line breaking with Asian languages.");
public static readonly GUIContent koreanSpecificRules = new GUIContent("Korean Language Options");
}
SerializedProperty m_PropFontAsset;
SerializedProperty m_PropDefaultFontAssetPath;
SerializedProperty m_PropDefaultFontSize;
SerializedProperty m_PropDefaultAutoSizeMinRatio;
SerializedProperty m_PropDefaultAutoSizeMaxRatio;
SerializedProperty m_PropDefaultTextMeshProTextContainerSize;
SerializedProperty m_PropDefaultTextMeshProUITextContainerSize;
SerializedProperty m_PropAutoSizeTextContainer;
SerializedProperty m_PropEnableRaycastTarget;
SerializedProperty m_PropIsTextObjectScaleStatic;
SerializedProperty m_PropSpriteAsset;
SerializedProperty m_PropMissingSpriteCharacterUnicode;
//SerializedProperty m_PropSpriteRelativeScaling;
SerializedProperty m_PropEnableEmojiSupport;
SerializedProperty m_PropSpriteAssetPath;
SerializedProperty m_PropStyleSheet;
SerializedProperty m_PropStyleSheetsResourcePath;
ReorderableList m_GlobalFallbackFontAssetList;
SerializedProperty m_PropColorGradientPresetsPath;
SerializedProperty m_PropMatchMaterialPreset;
SerializedProperty m_PropHideSubTextObjects;
SerializedProperty m_PropTextWrappingMode;
SerializedProperty m_PropKerning;
SerializedProperty m_PropExtraPadding;
SerializedProperty m_PropTintAllSprites;
SerializedProperty m_PropParseEscapeCharacters;
SerializedProperty m_PropMissingGlyphCharacter;
SerializedProperty m_PropClearDynamicDataOnBuild;
//SerializedProperty m_DynamicAtlasTextureManager;
SerializedProperty m_GetFontFeaturesAtRuntime;
SerializedProperty m_PropWarningsDisabled;
SerializedProperty m_PropLeadingCharacters;
SerializedProperty m_PropFollowingCharacters;
SerializedProperty m_PropUseModernHangulLineBreakingRules;
private const string k_UndoRedo = "UndoRedoPerformed";
private bool m_IsFallbackGlyphCacheDirty;
public void OnEnable()
{
if (target == null)
return;
m_PropFontAsset = serializedObject.FindProperty("m_defaultFontAsset");
m_PropDefaultFontAssetPath = serializedObject.FindProperty("m_defaultFontAssetPath");
m_PropDefaultFontSize = serializedObject.FindProperty("m_defaultFontSize");
m_PropDefaultAutoSizeMinRatio = serializedObject.FindProperty("m_defaultAutoSizeMinRatio");
m_PropDefaultAutoSizeMaxRatio = serializedObject.FindProperty("m_defaultAutoSizeMaxRatio");
m_PropDefaultTextMeshProTextContainerSize = serializedObject.FindProperty("m_defaultTextMeshProTextContainerSize");
m_PropDefaultTextMeshProUITextContainerSize = serializedObject.FindProperty("m_defaultTextMeshProUITextContainerSize");
m_PropAutoSizeTextContainer = serializedObject.FindProperty("m_autoSizeTextContainer");
m_PropEnableRaycastTarget = serializedObject.FindProperty("m_EnableRaycastTarget");
m_PropIsTextObjectScaleStatic = serializedObject.FindProperty("m_IsTextObjectScaleStatic");
m_PropSpriteAsset = serializedObject.FindProperty("m_defaultSpriteAsset");
m_PropMissingSpriteCharacterUnicode = serializedObject.FindProperty("m_MissingCharacterSpriteUnicode");
//m_PropSpriteRelativeScaling = serializedObject.FindProperty("m_SpriteRelativeScaling");
m_PropEnableEmojiSupport = serializedObject.FindProperty("m_enableEmojiSupport");
m_PropSpriteAssetPath = serializedObject.FindProperty("m_defaultSpriteAssetPath");
m_PropStyleSheet = serializedObject.FindProperty("m_defaultStyleSheet");
m_PropStyleSheetsResourcePath = serializedObject.FindProperty("m_StyleSheetsResourcePath");
m_PropColorGradientPresetsPath = serializedObject.FindProperty("m_defaultColorGradientPresetsPath");
m_GlobalFallbackFontAssetList = new ReorderableList(serializedObject, serializedObject.FindProperty("m_fallbackFontAssets"), true, true, true, true);
m_GlobalFallbackFontAssetList.drawHeaderCallback = rect =>
{
EditorGUI.LabelField(rect, Styles.fallbackFontAssetsListLabel);
};
m_GlobalFallbackFontAssetList.drawElementCallback = (rect, index, isActive, isFocused) =>
{
var element = m_GlobalFallbackFontAssetList.serializedProperty.GetArrayElementAtIndex(index);
rect.y += 2;
EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), element, GUIContent.none);
};
m_GlobalFallbackFontAssetList.onChangedCallback = itemList =>
{
m_IsFallbackGlyphCacheDirty = true;
};
m_PropMatchMaterialPreset = serializedObject.FindProperty("m_matchMaterialPreset");
m_PropHideSubTextObjects = serializedObject.FindProperty("m_HideSubTextObjects");
m_PropTextWrappingMode = serializedObject.FindProperty("m_TextWrappingMode");
m_PropKerning = serializedObject.FindProperty("m_enableKerning");
m_PropExtraPadding = serializedObject.FindProperty("m_enableExtraPadding");
m_PropTintAllSprites = serializedObject.FindProperty("m_enableTintAllSprites");
m_PropParseEscapeCharacters = serializedObject.FindProperty("m_enableParseEscapeCharacters");
m_PropMissingGlyphCharacter = serializedObject.FindProperty("m_missingGlyphCharacter");
m_PropClearDynamicDataOnBuild = serializedObject.FindProperty("m_ClearDynamicDataOnBuild");
m_PropWarningsDisabled = serializedObject.FindProperty("m_warningsDisabled");
//m_DynamicAtlasTextureManager = serializedObject.FindProperty("m_DynamicAtlasTextureGroup");
m_GetFontFeaturesAtRuntime = serializedObject.FindProperty("m_GetFontFeaturesAtRuntime");
m_PropLeadingCharacters = serializedObject.FindProperty("m_leadingCharacters");
m_PropFollowingCharacters = serializedObject.FindProperty("m_followingCharacters");
m_PropUseModernHangulLineBreakingRules = serializedObject.FindProperty("m_UseModernHangulLineBreakingRules");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
string evt_cmd = Event.current.commandName;
m_IsFallbackGlyphCacheDirty = false;
float labelWidth = EditorGUIUtility.labelWidth;
float fieldWidth = EditorGUIUtility.fieldWidth;
// TextMeshPro Font Info Panel
EditorGUI.indentLevel = 0;
// FONT ASSET
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label(Styles.defaultFontAssetLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel = 1;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_PropFontAsset, Styles.defaultFontAssetLabel);
if (EditorGUI.EndChangeCheck())
m_IsFallbackGlyphCacheDirty = true;
EditorGUILayout.PropertyField(m_PropDefaultFontAssetPath, Styles.defaultFontAssetPathLabel);
EditorGUI.indentLevel = 0;
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
// FALLBACK FONT ASSETs
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label(Styles.fallbackFontAssetsLabel, EditorStyles.boldLabel);
EditorGUI.BeginChangeCheck();
m_GlobalFallbackFontAssetList.DoLayoutList();
if (EditorGUI.EndChangeCheck())
m_IsFallbackGlyphCacheDirty = true;
GUILayout.Label(Styles.fallbackMaterialSettingsLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel = 1;
EditorGUILayout.PropertyField(m_PropMatchMaterialPreset, Styles.matchMaterialPresetLabel);
EditorGUILayout.PropertyField(m_PropHideSubTextObjects, Styles.hideSubTextObjectsPresetLabel);
EditorGUI.indentLevel = 0;
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
// MISSING GLYPHS
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label(Styles.dynamicFontSystemSettingsLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel = 1;
EditorGUILayout.PropertyField(m_GetFontFeaturesAtRuntime, Styles.getFontFeaturesAtRuntime);
EditorGUILayout.PropertyField(m_PropMissingGlyphCharacter, Styles.missingGlyphLabel);
EditorGUILayout.PropertyField(m_PropClearDynamicDataOnBuild, Styles.clearDynamicDataOnBuildLabel);
EditorGUILayout.PropertyField(m_PropWarningsDisabled, Styles.disableWarningsLabel);
//EditorGUILayout.PropertyField(m_DynamicAtlasTextureManager, Styles.dynamicAtlasTextureManager);
EditorGUI.indentLevel = 0;
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
// TEXT OBJECT DEFAULT PROPERTIES
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label(Styles.containerDefaultSettingsLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel = 1;
EditorGUILayout.PropertyField(m_PropDefaultTextMeshProTextContainerSize, Styles.textMeshProLabel);
EditorGUILayout.PropertyField(m_PropDefaultTextMeshProUITextContainerSize, Styles.textMeshProUiLabel);
EditorGUILayout.PropertyField(m_PropEnableRaycastTarget, Styles.enableRaycastTarget);
EditorGUILayout.PropertyField(m_PropAutoSizeTextContainer, Styles.autoSizeContainerLabel);
EditorGUILayout.PropertyField(m_PropIsTextObjectScaleStatic, Styles.isTextObjectScaleStaticLabel);
EditorGUI.indentLevel = 0;
EditorGUILayout.Space();
GUILayout.Label(Styles.textComponentDefaultSettingsLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel = 1;
EditorGUILayout.PropertyField(m_PropDefaultFontSize, Styles.defaultFontSize);
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.PrefixLabel(Styles.autoSizeRatioLabel);
EditorGUIUtility.labelWidth = 32;
EditorGUIUtility.fieldWidth = 10;
EditorGUI.indentLevel = 0;
EditorGUILayout.PropertyField(m_PropDefaultAutoSizeMinRatio, Styles.minLabel);
EditorGUILayout.PropertyField(m_PropDefaultAutoSizeMaxRatio, Styles.maxLabel);
EditorGUI.indentLevel = 1;
}
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = labelWidth;
EditorGUIUtility.fieldWidth = fieldWidth;
EditorGUILayout.PropertyField(m_PropTextWrappingMode, Styles.textWrappingModeLabel);
EditorGUILayout.PropertyField(m_PropKerning, Styles.kerningLabel);
EditorGUILayout.PropertyField(m_PropExtraPadding, Styles.extraPaddingLabel);
EditorGUILayout.PropertyField(m_PropTintAllSprites, Styles.tintAllSpritesLabel);
EditorGUILayout.PropertyField(m_PropParseEscapeCharacters, Styles.parseEscapeCharactersLabel);
EditorGUI.indentLevel = 0;
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
// SPRITE ASSET
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label(Styles.defaultSpriteAssetLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel = 1;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_PropSpriteAsset, Styles.defaultSpriteAssetLabel);
if (EditorGUI.EndChangeCheck())
m_IsFallbackGlyphCacheDirty = true;
EditorGUILayout.PropertyField(m_PropMissingSpriteCharacterUnicode, Styles.missingSpriteCharacterUnicodeLabel);
EditorGUILayout.PropertyField(m_PropEnableEmojiSupport, Styles.enableEmojiSupportLabel);
//EditorGUILayout.PropertyField(m_PropSpriteRelativeScaling, Styles.spriteRelativeScale);
EditorGUILayout.PropertyField(m_PropSpriteAssetPath, Styles.spriteAssetsPathLabel);
EditorGUI.indentLevel = 0;
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
// STYLE SHEET
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label(Styles.defaultStyleSheetLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel = 1;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_PropStyleSheet, Styles.defaultStyleSheetLabel);
if (EditorGUI.EndChangeCheck())
{
serializedObject.ApplyModifiedProperties();
UnityEngine.TextCore.Text.TextStyleSheet styleSheet = m_PropStyleSheet.objectReferenceValue as UnityEngine.TextCore.Text.TextStyleSheet;
if (styleSheet != null)
styleSheet.RefreshStyles();
}
EditorGUILayout.PropertyField(m_PropStyleSheetsResourcePath, Styles.styleSheetResourcePathLabel);
EditorGUI.indentLevel = 0;
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
// COLOR GRADIENT PRESETS
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label(Styles.colorGradientPresetsLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel = 1;
EditorGUILayout.PropertyField(m_PropColorGradientPresetsPath, Styles.colorGradientsPathLabel);
EditorGUI.indentLevel = 0;
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
// LINE BREAKING RULE
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
GUILayout.Label(Styles.lineBreakingLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel = 1;
EditorGUILayout.PropertyField(m_PropLeadingCharacters);
EditorGUILayout.PropertyField(m_PropFollowingCharacters);
EditorGUILayout.Space();
GUILayout.Label(Styles.koreanSpecificRules, EditorStyles.boldLabel);
EditorGUILayout.PropertyField(m_PropUseModernHangulLineBreakingRules, new GUIContent("Use Modern Line Breaking", "Determines if traditional or modern line breaking rules will be used to control line breaking. Traditional line breaking rules use the Leading and Following Character rules whereas Modern uses spaces for line breaking."));
EditorGUI.indentLevel = 0;
EditorGUILayout.Space();
EditorGUILayout.EndVertical();
if (m_IsFallbackGlyphCacheDirty || evt_cmd == k_UndoRedo)
TextResourceManager.RebuildFontAssetCache();
if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo)
{
EditorUtility.SetDirty(target);
TextEventManager.ON_TMP_SETTINGS_CHANGED();
}
}
}
#if UNITY_2018_3_OR_NEWER
class TMP_ResourceImporterProvider : SettingsProvider
{
TMP_PackageResourceImporter m_ResourceImporter;
public TMP_ResourceImporterProvider()
: base("Project/TextMesh Pro", SettingsScope.Project)
{
}
public override void OnGUI(string searchContext)
{
// Lazy creation that supports domain reload
if (m_ResourceImporter == null)
m_ResourceImporter = new TMP_PackageResourceImporter();
m_ResourceImporter.OnGUI();
}
public override void OnDeactivate()
{
if (m_ResourceImporter != null)
m_ResourceImporter.OnDestroy();
}
static UnityEngine.Object GetTMPSettings()
{
return Resources.Load<TMP_Settings>("TMP Settings");
}
[SettingsProviderGroup]
static SettingsProvider[] CreateTMPSettingsProvider()
{
var providers = new List<SettingsProvider> { new TMP_ResourceImporterProvider() };
if (GetTMPSettings() != null)
{
var provider = new AssetSettingsProvider("Project/TextMesh Pro/Settings", GetTMPSettings);
provider.PopulateSearchKeywordsFromGUIContentProperties<TMP_SettingsEditor.Styles>();
providers.Add(provider);
}
return providers.ToArray();
}
}
#endif
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: e5265d75dc6716c48a9b42547608c44e
timeCreated: 1436658550
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,19 @@
using UnityEngine;
using UnityEditor;
using UnityEditor.TextCore.Text;
namespace TMPro
{
internal class TMP_SpriteAssetImporter : EditorWindow
{
// Create Sprite Asset Editor Window
[MenuItem("Window/TextMeshPro/Sprite Importer", false, 2026)]
public static void ShowSpriteImporterWindow()
{
var window = GetWindow<SpriteAssetImporter>();
window.titleContent = new GUIContent("Sprite Importer");
window.Focus();
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 42c628ae579d4334d9dc7899c6f288c2
timeCreated: 1480023525
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,215 @@
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using UnityEngine;
using UnityEngine.TextCore;
using UnityEngine.TextCore.Text;
using UnityEngine.U2D;
using UnityEditor;
namespace TMPro.EditorUtilities
{
public static class TMP_SpriteAssetMenu
{
[MenuItem("Assets/Create/TextMeshPro/Sprite Asset", false, 150)]
static void CreateSpriteAsset()
{
Object[] targets = Selection.objects;
if (targets == null)
{
Debug.LogWarning("A Sprite Texture must first be selected in order to create a Sprite Asset.");
return;
}
// Make sure TMP Essential Resources have been imported in the user project.
if (TMP_Settings.instance == null)
{
Debug.Log("Unable to create sprite asset. Please import the TMP Essential Resources.");
// Show Window to Import TMP Essential Resources
return;
}
for (int i = 0; i < targets.Length; i++)
{
Object target = targets[i];
// Make sure the selection is a font file
if (target == null || target.GetType() != typeof(Texture2D))
{
Debug.LogWarning("Selected Object [" + target.name + "] is not a Sprite Texture. A Sprite Texture must be selected in order to create a Sprite Asset.", target);
continue;
}
CreateSpriteAssetFromSelectedObject(target);
}
}
static void CreateSpriteAssetFromSelectedObject(Object target)
{
// Get the path to the selected asset.
string filePathWithName = AssetDatabase.GetAssetPath(target);
string fileNameWithExtension = Path.GetFileName(filePathWithName);
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filePathWithName);
string filePath = filePathWithName.Replace(fileNameWithExtension, "");
string uniquePath = AssetDatabase.GenerateUniqueAssetPath(filePath + fileNameWithoutExtension + ".asset");
// Create new Sprite Asset
SpriteAsset spriteAsset = ScriptableObject.CreateInstance<SpriteAsset>();
AssetDatabase.CreateAsset(spriteAsset, uniquePath);
spriteAsset.version = "1.1.0";
// Compute the hash code for the sprite asset.
spriteAsset.hashCode = TMP_TextUtilities.GetSimpleHashCode(spriteAsset.name);
List<SpriteGlyph> spriteGlyphTable = new List<SpriteGlyph>();
List<SpriteCharacter> spriteCharacterTable = new List<SpriteCharacter>();
if (target.GetType() == typeof(Texture2D))
{
Texture2D sourceTex = target as Texture2D;
// Assign new Sprite Sheet texture to the Sprite Asset.
spriteAsset.spriteSheet = sourceTex;
PopulateSpriteTables(sourceTex, ref spriteCharacterTable, ref spriteGlyphTable);
spriteAsset.spriteCharacterTable = spriteCharacterTable;
spriteAsset.spriteGlyphTable = spriteGlyphTable;
// Add new default material for sprite asset.
AddDefaultMaterial(spriteAsset);
}
else if (target.GetType() == typeof(SpriteAtlas))
{
//SpriteAtlas spriteAtlas = target as SpriteAtlas;
//PopulateSpriteTables(spriteAtlas, ref spriteCharacterTable, ref spriteGlyphTable);
//spriteAsset.spriteCharacterTable = spriteCharacterTable;
//spriteAsset.spriteGlyphTable = spriteGlyphTable;
//spriteAsset.spriteSheet = spriteGlyphTable[0].sprite.texture;
//// Add new default material for sprite asset.
//AddDefaultMaterial(spriteAsset);
}
// Update Lookup tables.
spriteAsset.UpdateLookupTables();
// Get the Sprites contained in the Sprite Sheet
EditorUtility.SetDirty(spriteAsset);
//spriteAsset.sprites = sprites;
// Set source texture back to Not Readable.
//texImporter.isReadable = false;
AssetDatabase.SaveAssets();
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(spriteAsset)); // Re-import font asset to get the new updated version.
//AssetDatabase.Refresh();
}
static void PopulateSpriteTables(Texture source, ref List<SpriteCharacter> spriteCharacterTable, ref List<SpriteGlyph> spriteGlyphTable)
{
//Debug.Log("Creating new Sprite Asset.");
string filePath = AssetDatabase.GetAssetPath(source);
// Get all the Sprites sorted by Index
Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath(filePath).Select(x => x as Sprite).Where(x => x != null).OrderByDescending(x => x.rect.y).ThenBy(x => x.rect.x).ToArray();
for (int i = 0; i < sprites.Length; i++)
{
Sprite sprite = sprites[i];
SpriteGlyph spriteGlyph = new SpriteGlyph();
spriteGlyph.index = (uint)i;
spriteGlyph.metrics = new GlyphMetrics(sprite.rect.width, sprite.rect.height, -sprite.pivot.x, sprite.rect.height - sprite.pivot.y, sprite.rect.width);
spriteGlyph.glyphRect = new GlyphRect(sprite.rect);
spriteGlyph.scale = 1.0f;
spriteGlyph.sprite = sprite;
spriteGlyphTable.Add(spriteGlyph);
SpriteCharacter spriteCharacter = new SpriteCharacter(0xFFFE, spriteGlyph);
// Special handling for .notdef sprite name.
string fileNameToLowerInvariant = sprite.name.ToLowerInvariant();
if (fileNameToLowerInvariant == ".notdef" || fileNameToLowerInvariant == "notdef")
{
spriteCharacter.unicode = 0;
spriteCharacter.name = fileNameToLowerInvariant;
}
else
{
if (!string.IsNullOrEmpty(sprite.name) && sprite.name.Length > 2 && sprite.name[0] == '0' && (sprite.name[1] == 'x' || sprite.name[1] == 'X'))
{
spriteCharacter.unicode = (uint)TMP_TextUtilities.StringHexToInt(sprite.name.Remove(0, 2));
}
spriteCharacter.name = sprite.name;
}
spriteCharacter.scale = 1.0f;
spriteCharacterTable.Add(spriteCharacter);
}
}
static void PopulateSpriteTables(SpriteAtlas spriteAtlas, ref List<SpriteCharacter> spriteCharacterTable, ref List<SpriteGlyph> spriteGlyphTable)
{
// Get number of sprites contained in the sprite atlas.
int spriteCount = spriteAtlas.spriteCount;
Sprite[] sprites = new Sprite[spriteCount];
// Get all the sprites
spriteAtlas.GetSprites(sprites);
for (int i = 0; i < sprites.Length; i++)
{
Sprite sprite = sprites[i];
SpriteGlyph spriteGlyph = new SpriteGlyph();
spriteGlyph.index = (uint)i;
spriteGlyph.metrics = new GlyphMetrics(sprite.textureRect.width, sprite.textureRect.height, -sprite.pivot.x, sprite.textureRect.height - sprite.pivot.y, sprite.textureRect.width);
spriteGlyph.glyphRect = new GlyphRect(sprite.textureRect);
spriteGlyph.scale = 1.0f;
spriteGlyph.sprite = sprite;
spriteGlyphTable.Add(spriteGlyph);
SpriteCharacter spriteCharacter = new SpriteCharacter(0xFFFE, spriteGlyph);
spriteCharacter.name = sprite.name;
spriteCharacter.scale = 1.0f;
spriteCharacterTable.Add(spriteCharacter);
}
}
/// <summary>
/// Create and add new default material to sprite asset.
/// </summary>
/// <param name="spriteAsset"></param>
static void AddDefaultMaterial(SpriteAsset spriteAsset)
{
Shader shader = Shader.Find("TextMeshPro/Sprite");
Material material = new Material(shader);
material.SetTexture(ShaderUtilities.ID_MainTex, spriteAsset.spriteSheet);
spriteAsset.material = material;
material.name = spriteAsset.name + " Material";
AssetDatabase.AddObjectToAsset(material, spriteAsset);
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 1482c8f1088021247b8288de150cd286
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,54 @@
using System.IO;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEditor;
namespace TMPro.EditorUtilities
{
public static class TMP_StyleAssetMenu
{
[MenuItem("Assets/Create/TextMeshPro/Style Sheet", false, 200)]
internal static void CreateTextMeshProObjectPerform()
{
string filePath;
if (Selection.assetGUIDs.Length == 0)
{
// No asset selected.
filePath = "Assets";
}
else
{
// Get the path of the selected folder or asset.
filePath = AssetDatabase.GUIDToAssetPath(Selection.assetGUIDs[0]);
// Get the file extension of the selected asset as it might need to be removed.
string fileExtension = Path.GetExtension(filePath);
if (fileExtension != "")
{
filePath = Path.GetDirectoryName(filePath);
}
}
string filePathWithName = AssetDatabase.GenerateUniqueAssetPath(filePath + "/Text StyleSheet.asset");
//// Create new Style Sheet Asset.
TextStyleSheet styleSheet = ScriptableObject.CreateInstance<TextStyleSheet>();
// Create Normal default style
TextStyle style = new TextStyle("Normal", string.Empty, string.Empty);
styleSheet.styles.Add(style);
AssetDatabase.CreateAsset(styleSheet, filePathWithName);
EditorUtility.SetDirty(styleSheet);
AssetDatabase.SaveAssets();
EditorUtility.FocusProjectWindow();
EditorGUIUtility.PingObject(styleSheet);
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 5fdf1a778783f1143abbbcb77d7ba724
timeCreated: 1432690168
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,104 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TMP_SubMeshUI)), CanEditMultipleObjects]
public class TMP_SubMeshUI_Editor : Editor
{
private struct m_foldout
{ // Track Inspector foldout panel states, globally.
//public static bool textInput = true;
public static bool fontSettings = true;
//public static bool extraSettings = false;
//public static bool shadowSetting = false;
//public static bool materialEditor = true;
}
private SerializedProperty fontAsset_prop;
private SerializedProperty spriteAsset_prop;
//private TMP_SubMeshUI m_SubMeshComponent;
//private CanvasRenderer m_canvasRenderer;
private Editor m_materialEditor;
private Material m_targetMaterial;
public void OnEnable()
{
fontAsset_prop = serializedObject.FindProperty("m_fontAsset");
spriteAsset_prop = serializedObject.FindProperty("m_spriteAsset");
//m_SubMeshComponent = target as TMP_SubMeshUI;
//m_rectTransform = m_SubMeshComponent.rectTransform;
//m_canvasRenderer = m_SubMeshComponent.canvasRenderer;
// Create new Material Editor if one does not exists
/*
if (m_canvasRenderer != null && m_canvasRenderer.GetMaterial() != null)
{
m_materialEditor = Editor.CreateEditor(m_canvasRenderer.GetMaterial());
m_targetMaterial = m_canvasRenderer.GetMaterial();
}
*/
}
public void OnDisable()
{
// Destroy material editor if one exists
/*
if (m_materialEditor != null)
{
//Debug.Log("Destroying Inline Material Editor.");
DestroyImmediate(m_materialEditor);
}
*/
}
public override void OnInspectorGUI()
{
GUI.enabled = false;
EditorGUILayout.PropertyField(fontAsset_prop);
EditorGUILayout.PropertyField(spriteAsset_prop);
GUI.enabled = true;
EditorGUILayout.Space();
// If a Custom Material Editor exists, we use it.
/*
if (m_canvasRenderer != null && m_canvasRenderer.GetMaterial() != null)
{
Material mat = m_canvasRenderer.GetMaterial();
//Debug.Log(mat + " " + m_targetMaterial);
if (mat != m_targetMaterial)
{
// Destroy previous Material Instance
//Debug.Log("New Material has been assigned.");
m_targetMaterial = mat;
DestroyImmediate(m_materialEditor);
}
if (m_materialEditor == null)
{
m_materialEditor = Editor.CreateEditor(mat);
}
m_materialEditor.DrawHeader();
m_materialEditor.OnInspectorGUI();
}
*/
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: b6e27efdddf82ea45bcea289192e8e3a
timeCreated: 1452757501
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,71 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
[CustomEditor(typeof(TMP_SubMesh)), CanEditMultipleObjects]
public class TMP_SubMesh_Editor : Editor
{
private struct m_foldout
{ // Track Inspector foldout panel states, globally.
//public static bool textInput = true;
public static bool fontSettings = true;
//public static bool extraSettings = false;
//public static bool shadowSetting = false;
//public static bool materialEditor = true;
}
private SerializedProperty fontAsset_prop;
private SerializedProperty spriteAsset_prop;
private TMP_SubMesh m_SubMeshComponent;
private Renderer m_Renderer;
private string[] m_SortingLayerNames;
public void OnEnable()
{
fontAsset_prop = serializedObject.FindProperty("m_fontAsset");
spriteAsset_prop = serializedObject.FindProperty("m_spriteAsset");
m_SubMeshComponent = target as TMP_SubMesh;
m_Renderer = m_SubMeshComponent.renderer;
m_SortingLayerNames = SortingLayerHelper.sortingLayerNames;
}
public override void OnInspectorGUI()
{
EditorGUI.indentLevel = 0;
GUI.enabled = false;
EditorGUILayout.PropertyField(fontAsset_prop);
EditorGUILayout.PropertyField(spriteAsset_prop);
GUI.enabled = true;
EditorGUI.BeginChangeCheck();
// Look up the layer name using the current layer ID
string oldName = SortingLayer.IDToName(m_Renderer.sortingLayerID);
// Use the name to look up our array index into the names list
int oldLayerIndex = System.Array.IndexOf(m_SortingLayerNames, oldName);
// Show the pop-up for the names
int newLayerIndex = EditorGUILayout.Popup("Sorting Layer", oldLayerIndex, m_SortingLayerNames);
// If the index changes, look up the ID for the new index to store as the new ID
if (newLayerIndex != oldLayerIndex)
m_Renderer.sortingLayerID = SortingLayer.NameToID(m_SortingLayerNames[newLayerIndex]);
// Expose the manual sorting order
int newSortingLayerOrder = EditorGUILayout.IntField("Order in Layer", m_Renderer.sortingOrder);
if (newSortingLayerOrder != m_Renderer.sortingOrder)
m_Renderer.sortingOrder = newSortingLayerOrder;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 011b7ef66d3d30d40871bc6b61410f78
timeCreated: 1456189048
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,134 @@
using UnityEngine;
using UnityEditor;
using System.Collections;
namespace TMPro.EditorUtilities
{
public static class TMP_UIStyleManager
{
public static GUIStyle label;
public static GUIStyle textAreaBoxWindow;
public static GUIStyle boldFoldout;
public static GUIStyle panelTitle;
public static GUIStyle sectionHeader;
public static GUIStyle centeredLabel;
public static GUIStyle rightLabel;
public static GUIStyle wrappingTextArea;
public static GUIStyle alignmentButtonLeft;
public static GUIStyle alignmentButtonMid;
public static GUIStyle alignmentButtonRight;
// Alignment Button Textures
public static Texture2D alignLeft;
public static Texture2D alignCenter;
public static Texture2D alignRight;
public static Texture2D alignJustified;
public static Texture2D alignFlush;
public static Texture2D alignGeoCenter;
public static Texture2D alignTop;
public static Texture2D alignMiddle;
public static Texture2D alignBottom;
public static Texture2D alignBaseline;
public static Texture2D alignMidline;
public static Texture2D alignCapline;
public static Texture2D sectionHeaderTexture;
public static GUIContent[] alignContentA;
public static GUIContent[] alignContentB;
static TMP_UIStyleManager()
{
// Find to location of the TextMesh Pro Asset Folder (as users may have moved it)
var tmproAssetFolderPath = TMP_EditorUtility.packageRelativePath;
if (EditorGUIUtility.isProSkin)
{
alignLeft = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignLeft.psd", typeof(Texture2D)) as Texture2D;
alignCenter = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignCenter.psd", typeof(Texture2D)) as Texture2D;
alignRight = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignRight.psd", typeof(Texture2D)) as Texture2D;
alignJustified = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignJustified.psd", typeof(Texture2D)) as Texture2D;
alignFlush = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignFlush.psd", typeof(Texture2D)) as Texture2D;
alignGeoCenter = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignCenterGeo.psd", typeof(Texture2D)) as Texture2D;
alignTop = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignTop.psd", typeof(Texture2D)) as Texture2D;
alignMiddle = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignMiddle.psd", typeof(Texture2D)) as Texture2D;
alignBottom = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignBottom.psd", typeof(Texture2D)) as Texture2D;
alignBaseline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignBaseLine.psd", typeof(Texture2D)) as Texture2D;
alignMidline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignMidLine.psd", typeof(Texture2D)) as Texture2D;
alignCapline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignCapLine.psd", typeof(Texture2D)) as Texture2D;
sectionHeaderTexture = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/SectionHeader_Dark.psd", typeof(Texture2D)) as Texture2D;
}
else
{
alignLeft = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignLeft_Light.psd", typeof(Texture2D)) as Texture2D;
alignCenter = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignCenter_Light.psd", typeof(Texture2D)) as Texture2D;
alignRight = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignRight_Light.psd", typeof(Texture2D)) as Texture2D;
alignJustified = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignJustified_Light.psd", typeof(Texture2D)) as Texture2D;
alignFlush = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignFlush_Light.psd", typeof(Texture2D)) as Texture2D;
alignGeoCenter = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignCenterGeo_Light.psd", typeof(Texture2D)) as Texture2D;
alignTop = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignTop_Light.psd", typeof(Texture2D)) as Texture2D;
alignMiddle = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignMiddle_Light.psd", typeof(Texture2D)) as Texture2D;
alignBottom = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignBottom_Light.psd", typeof(Texture2D)) as Texture2D;
alignBaseline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignBaseLine_Light.psd", typeof(Texture2D)) as Texture2D;
alignMidline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignMidLine_Light.psd", typeof(Texture2D)) as Texture2D;
alignCapline = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/btn_AlignCapLine_Light.psd", typeof(Texture2D)) as Texture2D;
sectionHeaderTexture = AssetDatabase.LoadAssetAtPath(tmproAssetFolderPath + "/Editor Resources/Textures/SectionHeader_Light.psd", typeof(Texture2D)) as Texture2D;
}
label = new GUIStyle(EditorStyles.label) { richText = true, wordWrap = true, stretchWidth = true };
textAreaBoxWindow = new GUIStyle(EditorStyles.textArea) { richText = true };
boldFoldout = new GUIStyle(EditorStyles.foldout) { fontStyle = FontStyle.Bold };
panelTitle = new GUIStyle(EditorStyles.label) { fontStyle = FontStyle.Bold };
sectionHeader = new GUIStyle(EditorStyles.label) { fixedHeight = 22, richText = true, border = new RectOffset(9, 9, 0, 0), overflow = new RectOffset(9, 0, 0, 0), padding = new RectOffset(0, 0, 4, 0) };
sectionHeader.normal.background = sectionHeaderTexture;
centeredLabel = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.MiddleCenter};
rightLabel = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.MiddleRight, richText = true };
alignmentButtonLeft = new GUIStyle(EditorStyles.miniButtonLeft);
alignmentButtonLeft.padding.left = 4;
alignmentButtonLeft.padding.right = 4;
alignmentButtonLeft.padding.top = 2;
alignmentButtonLeft.padding.bottom = 2;
alignmentButtonMid = new GUIStyle(EditorStyles.miniButtonMid);
alignmentButtonMid.padding.left = 4;
alignmentButtonMid.padding.right = 4;
alignmentButtonLeft.padding.top = 2;
alignmentButtonLeft.padding.bottom = 2;
alignmentButtonRight = new GUIStyle(EditorStyles.miniButtonRight);
alignmentButtonRight.padding.left = 4;
alignmentButtonRight.padding.right = 4;
alignmentButtonLeft.padding.top = 2;
alignmentButtonLeft.padding.bottom = 2;
wrappingTextArea = new GUIStyle(EditorStyles.textArea);
wrappingTextArea.wordWrap = true;
alignContentA = new []
{
new GUIContent(alignLeft, "Left"),
new GUIContent(alignCenter, "Center"),
new GUIContent(alignRight, "Right"),
new GUIContent(alignJustified, "Justified"),
new GUIContent(alignFlush, "Flush"),
new GUIContent(alignGeoCenter, "Geometry Center")
};
alignContentB = new []
{
new GUIContent(alignTop, "Top"),
new GUIContent(alignMiddle, "Middle"),
new GUIContent(alignBottom, "Bottom"),
new GUIContent(alignBaseline, "Baseline"),
new GUIContent(alignMidline, "Midline"),
new GUIContent(alignCapline, "Capline")
};
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 8733984551d9f6a4e887affa0a8122ae
timeCreated: 1426454127
licenseType: Store
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,404 @@
using System.IO;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEditor;
namespace TMPro.EditorUtilities
{
public class TMP_ContextMenus : Editor
{
private static Texture m_copiedTexture;
private static Material m_copiedProperties;
private static Material m_copiedAtlasProperties;
// Add a Context Menu to the Texture Editor Panel to allow Copy / Paste of Texture.
#if !TEXTCORE_1_0_OR_NEWER
[MenuItem("CONTEXT/Texture/Copy", false, 2000)]
static void CopyTexture(MenuCommand command)
{
m_copiedTexture = command.context as Texture;
}
// Select the currently assigned material or material preset.
[MenuItem("CONTEXT/Material/Select Material", false, 500)]
static void SelectMaterial(MenuCommand command)
{
Material mat = command.context as Material;
// Select current material
EditorUtility.FocusProjectWindow();
EditorGUIUtility.PingObject(mat);
}
#endif
// Add a Context Menu to allow easy duplication of the Material.
[MenuItem("CONTEXT/Material/Create Material Preset", false)]
static void DuplicateMaterial(MenuCommand command)
{
// Get the type of text object
// If material is not a base material, we get material leaks...
Material source_Mat = (Material)command.context;
if (!EditorUtility.IsPersistent(source_Mat))
{
Debug.LogWarning("Material is an instance and cannot be converted into a persistent asset.");
return;
}
string assetPath = AssetDatabase.GetAssetPath(source_Mat).Split('.')[0];
if (assetPath.IndexOf("Assets/", System.StringComparison.InvariantCultureIgnoreCase) == -1)
{
Debug.LogWarning("Material Preset cannot be created from a material that is located outside the project.");
return;
}
Material duplicate = new Material(source_Mat);
// Need to manually copy the shader keywords
duplicate.shaderKeywords = source_Mat.shaderKeywords;
AssetDatabase.CreateAsset(duplicate, AssetDatabase.GenerateUniqueAssetPath(assetPath + ".mat"));
GameObject[] selectedObjects = Selection.gameObjects;
// Assign new Material Preset to selected text objects.
for (int i = 0; i < selectedObjects.Length; i++)
{
TMP_Text textObject = selectedObjects[i].GetComponent<TMP_Text>();
if (textObject != null)
{
textObject.fontSharedMaterial = duplicate;
}
else
{
TMP_SubMesh subMeshObject = selectedObjects[i].GetComponent<TMP_SubMesh>();
if (subMeshObject != null)
subMeshObject.sharedMaterial = duplicate;
else
{
TMP_SubMeshUI subMeshUIObject = selectedObjects[i].GetComponent<TMP_SubMeshUI>();
if (subMeshUIObject != null)
subMeshUIObject.sharedMaterial = duplicate;
}
}
}
// Ping newly created Material Preset.
EditorUtility.FocusProjectWindow();
EditorGUIUtility.PingObject(duplicate);
}
// COPY MATERIAL PROPERTIES
#if !TEXTCORE_1_0_OR_NEWER
[MenuItem("CONTEXT/Material/Copy Material Properties", false)]
static void CopyMaterialProperties(MenuCommand command)
{
Material mat = null;
if (command.context.GetType() == typeof(Material))
mat = (Material)command.context;
else
{
mat = Selection.activeGameObject.GetComponent<CanvasRenderer>().GetMaterial();
}
m_copiedProperties = new Material(mat);
m_copiedProperties.shaderKeywords = mat.shaderKeywords;
m_copiedProperties.hideFlags = HideFlags.DontSave;
}
// PASTE MATERIAL PROPERTIES
[MenuItem("CONTEXT/Material/Paste Material Properties", true)]
static bool PasteMaterialPropertiesValidate(MenuCommand command)
{
if (m_copiedProperties == null)
return false;
return AssetDatabase.IsOpenForEdit(command.context);
}
[MenuItem("CONTEXT/Material/Paste Material Properties", false)]
static void PasteMaterialProperties(MenuCommand command)
{
if (m_copiedProperties == null)
{
Debug.LogWarning("No Material Properties to Paste. Use Copy Material Properties first.");
return;
}
Material mat = null;
if (command.context.GetType() == typeof(Material))
mat = (Material)command.context;
else
{
mat = Selection.activeGameObject.GetComponent<CanvasRenderer>().GetMaterial();
}
Undo.RecordObject(mat, "Paste Material");
ShaderUtilities.GetShaderPropertyIDs(); // Make sure we have valid Property IDs
if (mat.HasProperty(ShaderUtilities.ID_GradientScale))
{
// Preserve unique SDF properties from destination material.
m_copiedProperties.SetTexture(ShaderUtilities.ID_MainTex, mat.GetTexture(ShaderUtilities.ID_MainTex));
m_copiedProperties.SetFloat(ShaderUtilities.ID_GradientScale, mat.GetFloat(ShaderUtilities.ID_GradientScale));
m_copiedProperties.SetFloat(ShaderUtilities.ID_TextureWidth, mat.GetFloat(ShaderUtilities.ID_TextureWidth));
m_copiedProperties.SetFloat(ShaderUtilities.ID_TextureHeight, mat.GetFloat(ShaderUtilities.ID_TextureHeight));
}
EditorShaderUtilities.CopyMaterialProperties(m_copiedProperties, mat);
// Copy ShaderKeywords from one material to the other.
mat.shaderKeywords = m_copiedProperties.shaderKeywords;
// Let TextMeshPro Objects that this mat has changed.
TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, mat);
}
// Enable Resetting of Material properties without losing unique properties of the font atlas.
[MenuItem("CONTEXT/Material/Reset", true, 2100)]
static bool ResetSettingsValidate(MenuCommand command)
{
return AssetDatabase.IsOpenForEdit(command.context);
}
[MenuItem("CONTEXT/Material/Reset", false, 2100)]
static void ResetSettings(MenuCommand command)
{
Material mat = null;
if (command.context.GetType() == typeof(Material))
mat = (Material)command.context;
else
{
mat = Selection.activeGameObject.GetComponent<CanvasRenderer>().GetMaterial();
}
Undo.RecordObject(mat, "Reset Material");
ShaderUtilities.GetShaderPropertyIDs(); // Make sure we have valid Property IDs
if (mat.HasProperty(ShaderUtilities.ID_GradientScale))
{
bool isSRPShader = mat.HasProperty(ShaderUtilities.ID_IsoPerimeter);
// Copy unique properties of the SDF Material
var texture = mat.GetTexture(ShaderUtilities.ID_MainTex);
var gradientScale = mat.GetFloat(ShaderUtilities.ID_GradientScale);
float texWidth = 0, texHeight = 0;
float normalWeight = 0, boldWeight = 0;
if (!isSRPShader)
{
texWidth = mat.GetFloat(ShaderUtilities.ID_TextureWidth);
texHeight = mat.GetFloat(ShaderUtilities.ID_TextureHeight);
normalWeight = mat.GetFloat(ShaderUtilities.ID_WeightNormal);
boldWeight = mat.GetFloat(ShaderUtilities.ID_WeightBold);
}
var stencilId = 0.0f;
var stencilComp = 0.0f;
if (mat.HasProperty(ShaderUtilities.ID_StencilID))
{
stencilId = mat.GetFloat(ShaderUtilities.ID_StencilID);
stencilComp = mat.GetFloat(ShaderUtilities.ID_StencilComp);
}
// Reset the material
Unsupported.SmartReset(mat);
// Reset ShaderKeywords
mat.shaderKeywords = new string[0]; // { "BEVEL_OFF", "GLOW_OFF", "UNDERLAY_OFF" };
// Copy unique material properties back to the material.
mat.SetTexture(ShaderUtilities.ID_MainTex, texture);
mat.SetFloat(ShaderUtilities.ID_GradientScale, gradientScale);
if (!isSRPShader)
{
mat.SetFloat(ShaderUtilities.ID_TextureWidth, texWidth);
mat.SetFloat(ShaderUtilities.ID_TextureHeight, texHeight);
mat.SetFloat(ShaderUtilities.ID_WeightNormal, normalWeight);
mat.SetFloat(ShaderUtilities.ID_WeightBold, boldWeight);
}
if (mat.HasProperty(ShaderUtilities.ID_StencilID))
{
mat.SetFloat(ShaderUtilities.ID_StencilID, stencilId);
mat.SetFloat(ShaderUtilities.ID_StencilComp, stencilComp);
}
}
else
{
Unsupported.SmartReset(mat);
}
TMPro_EventManager.ON_MATERIAL_PROPERTY_CHANGED(true, mat);
}
//This function is used for debugging and fixing potentially broken font atlas links.
[MenuItem("CONTEXT/Material/Copy Atlas", false, 2000)]
static void CopyAtlas(MenuCommand command)
{
Material mat = command.context as Material;
m_copiedAtlasProperties = new Material(mat);
m_copiedAtlasProperties.hideFlags = HideFlags.DontSave;
}
// This function is used for debugging and fixing potentially broken font atlas links
[MenuItem("CONTEXT/Material/Paste Atlas", true, 2001)]
static bool PasteAtlasValidate(MenuCommand command)
{
if (m_copiedAtlasProperties == null && m_copiedTexture == null)
return false;
return AssetDatabase.IsOpenForEdit(command.context);
}
[MenuItem("CONTEXT/Material/Paste Atlas", false, 2001)]
static void PasteAtlas(MenuCommand command)
{
Material mat = command.context as Material;
if (mat == null)
return;
if (m_copiedAtlasProperties != null)
{
Undo.RecordObject(mat, "Paste Texture");
ShaderUtilities.GetShaderPropertyIDs(); // Make sure we have valid Property IDs
if (m_copiedAtlasProperties.HasProperty(ShaderUtilities.ID_MainTex))
mat.SetTexture(ShaderUtilities.ID_MainTex, m_copiedAtlasProperties.GetTexture(ShaderUtilities.ID_MainTex));
if (m_copiedAtlasProperties.HasProperty(ShaderUtilities.ID_GradientScale))
{
mat.SetFloat(ShaderUtilities.ID_GradientScale, m_copiedAtlasProperties.GetFloat(ShaderUtilities.ID_GradientScale));
mat.SetFloat(ShaderUtilities.ID_TextureWidth, m_copiedAtlasProperties.GetFloat(ShaderUtilities.ID_TextureWidth));
mat.SetFloat(ShaderUtilities.ID_TextureHeight, m_copiedAtlasProperties.GetFloat(ShaderUtilities.ID_TextureHeight));
}
}
else if (m_copiedTexture != null)
{
Undo.RecordObject(mat, "Paste Texture");
mat.SetTexture(ShaderUtilities.ID_MainTex, m_copiedTexture);
}
}
#endif
/*
// Context Menus for TMPro Font Assets
//This function is used for debugging and fixing potentially broken font atlas links.
[MenuItem("CONTEXT/TMP_FontAsset/Extract Atlas", false, 2100)]
static void ExtractAtlas(MenuCommand command)
{
FontAsset font = command.context as FontAsset;
string fontPath = AssetDatabase.GetAssetPath(font);
string texPath = Path.GetDirectoryName(fontPath) + "/" + Path.GetFileNameWithoutExtension(fontPath) + " Atlas.png";
// Create a Serialized Object of the texture to allow us to make it readable.
SerializedObject texprop = new SerializedObject(font.material.GetTexture(ShaderUtilities.ID_MainTex));
texprop.FindProperty("m_IsReadable").boolValue = true;
texprop.ApplyModifiedProperties();
// Create a copy of the texture.
Texture2D tex = Instantiate(font.material.GetTexture(ShaderUtilities.ID_MainTex)) as Texture2D;
// Set the texture to not readable again.
texprop.FindProperty("m_IsReadable").boolValue = false;
texprop.ApplyModifiedProperties();
Debug.Log(texPath);
// Saving File for Debug
var pngData = tex.EncodeToPNG();
File.WriteAllBytes(texPath, pngData);
AssetDatabase.Refresh();
DestroyImmediate(tex);
}
*/
/*
/// <summary>
///
/// </summary>
/// <param name="command"></param>
[MenuItem("CONTEXT/TMP_FontAsset/Update Atlas Texture...", false, 2000)]
static void RegenerateFontAsset(MenuCommand command)
{
FontAsset fontAsset = command.context as FontAsset;
if (fontAsset != null)
{
TMPro_FontAssetCreatorWindow.ShowFontAtlasCreatorWindow(fontAsset);
}
}
/// <summary>
/// Clear Dynamic Font Asset data such as glyph, character and font features.
/// </summary>
/// <param name="command"></param>
[MenuItem("CONTEXT/TMP_FontAsset/Reset", true, 100)]
static bool ClearFontAssetDataValidate(MenuCommand command)
{
return AssetDatabase.IsOpenForEdit(command.context);
}
[MenuItem("CONTEXT/TMP_FontAsset/Reset", false, 100)]
static void ClearFontAssetData(MenuCommand command)
{
FontAsset fontAsset = command.context as FontAsset;
if (fontAsset == null)
return;
if (Selection.activeObject != fontAsset)
Selection.activeObject = fontAsset;
fontAsset.ClearFontAssetData(true);
TextResourceManager.RebuildFontAssetCache();
TextEventManager.ON_FONT_PROPERTY_CHANGED(true, fontAsset);
}
*/
/*
[MenuItem("CONTEXT/TrueTypeFontImporter/Create Font Asset...", false, 200)]
static void CreateFontAsset(MenuCommand command)
{
TrueTypeFontImporter importer = command.context as TrueTypeFontImporter;
if (importer != null)
{
Font sourceFontFile = AssetDatabase.LoadAssetAtPath<Font>(importer.assetPath);
if (sourceFontFile)
TMPro_FontAssetCreatorWindow.ShowFontAtlasCreatorWindow(sourceFontFile);
}
}
*/
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 15f9ccf306ee7834a83366dd92746abc
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,417 @@
using UnityEngine;
using UnityEditor;
using UnityEditor.Presets;
using UnityEditor.SceneManagement;
using UnityEditor.Experimental.SceneManagement;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.EventSystems;
namespace TMPro.EditorUtilities
{
public static class TMPro_CreateObjectMenu
{
/// <summary>
/// Create a TextMeshPro object that works with the Mesh Renderer
/// </summary>
/// <param name="command"></param>
[MenuItem("GameObject/3D Object/Text - TextMeshPro", false, 30)]
static void CreateTextMeshProObjectPerform(MenuCommand command)
{
GameObject go = ObjectFactory.CreateGameObject("Text (TMP)");
// Add support for new prefab mode
StageUtility.PlaceGameObjectInCurrentStage(go);
TextMeshPro textComponent = ObjectFactory.AddComponent<TextMeshPro>(go);
if (textComponent.m_isWaitingOnResourceLoad == false)
{
// Get reference to potential Presets for <TextMeshPro> component
#if UNITY_2019_3_OR_NEWER
Preset[] presets = Preset.GetDefaultPresetsForObject(textComponent);
if (presets == null || presets.Length == 0)
{
textComponent.text = "Sample text";
textComponent.alignment = TextAlignmentOptions.TopLeft;
}
else
{
textComponent.renderer.sortingLayerID = textComponent._SortingLayerID;
textComponent.renderer.sortingOrder = textComponent._SortingOrder;
}
#else
if (Preset.GetDefaultForObject(textComponent) == null)
{
textComponent.text = "Sample text";
textComponent.alignment = TextAlignmentOptions.TopLeft;
}
else
{
textComponent.renderer.sortingLayerID = textComponent._SortingLayerID;
textComponent.renderer.sortingOrder = textComponent._SortingOrder;
}
#endif
if (TMP_Settings.autoSizeTextContainer)
{
Vector2 size = textComponent.GetPreferredValues(TMP_Math.FLOAT_MAX, TMP_Math.FLOAT_MAX);
textComponent.rectTransform.sizeDelta = size;
}
else
{
textComponent.rectTransform.sizeDelta = TMP_Settings.defaultTextMeshProTextContainerSize;
}
}
else
{
textComponent.text = "Sample text";
textComponent.alignment = TextAlignmentOptions.TopLeft;
}
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
GameObject contextObject = command.context as GameObject;
if (contextObject != null)
{
GameObjectUtility.SetParentAndAlign(go, contextObject);
Undo.SetTransformParent(go.transform, contextObject.transform, "Parent " + go.name);
}
Selection.activeGameObject = go;
}
/// <summary>
/// Create a TextMeshPro object that works with the CanvasRenderer
/// </summary>
/// <param name="command"></param>
[MenuItem("GameObject/UI/Text - TextMeshPro", false, 2001)]
static void CreateTextMeshProGuiObjectPerform(MenuCommand menuCommand)
{
GameObject go = TMP_DefaultControls.CreateText(GetStandardResources());
// Override text color and font size
TextMeshProUGUI textComponent = go.GetComponent<TextMeshProUGUI>();
if (textComponent.m_isWaitingOnResourceLoad == false)
{
// Get reference to potential Presets for <TextMeshProUGUI> component
#if UNITY_2019_3_OR_NEWER
Preset[] presets = Preset.GetDefaultPresetsForObject(textComponent);
if (presets == null || presets.Length == 0)
{
textComponent.fontSize = TMP_Settings.defaultFontSize;
textComponent.color = Color.white;
textComponent.text = "New Text";
}
#else
if (Preset.GetDefaultForObject(textComponent) == null)
{
textComponent.fontSize = TMP_Settings.defaultFontSize;
textComponent.color = Color.white;
textComponent.text = "New Text";
}
#endif
if (TMP_Settings.autoSizeTextContainer)
{
Vector2 size = textComponent.GetPreferredValues(TMP_Math.FLOAT_MAX, TMP_Math.FLOAT_MAX);
textComponent.rectTransform.sizeDelta = size;
}
else
{
textComponent.rectTransform.sizeDelta = TMP_Settings.defaultTextMeshProUITextContainerSize;
}
}
else
{
textComponent.fontSize = -99;
textComponent.color = Color.white;
textComponent.text = "New Text";
}
PlaceUIElementRoot(go, menuCommand);
}
[MenuItem("GameObject/UI/Button - TextMeshPro", false, 2031)]
public static void AddButton(MenuCommand menuCommand)
{
GameObject go = TMP_DefaultControls.CreateButton(GetStandardResources());
// Override font size
TMP_Text textComponent = go.GetComponentInChildren<TMP_Text>();
textComponent.fontSize = 24;
PlaceUIElementRoot(go, menuCommand);
}
[MenuItem("GameObject/UI/Input Field - TextMeshPro", false, 2037)]
static void AddTextMeshProInputField(MenuCommand menuCommand)
{
GameObject go = TMP_DefaultControls.CreateInputField(GetStandardResources());
PlaceUIElementRoot(go, menuCommand);
}
[MenuItem("GameObject/UI/Dropdown - TextMeshPro", false, 2036)]
public static void AddDropdown(MenuCommand menuCommand)
{
GameObject go = TMP_DefaultControls.CreateDropdown(GetStandardResources());
PlaceUIElementRoot(go, menuCommand);
}
private const string kUILayerName = "UI";
private const string kStandardSpritePath = "UI/Skin/UISprite.psd";
private const string kBackgroundSpritePath = "UI/Skin/Background.psd";
private const string kInputFieldBackgroundPath = "UI/Skin/InputFieldBackground.psd";
private const string kKnobPath = "UI/Skin/Knob.psd";
private const string kCheckmarkPath = "UI/Skin/Checkmark.psd";
private const string kDropdownArrowPath = "UI/Skin/DropdownArrow.psd";
private const string kMaskPath = "UI/Skin/UIMask.psd";
private static TMP_DefaultControls.Resources s_StandardResources;
private static TMP_DefaultControls.Resources GetStandardResources()
{
if (s_StandardResources.standard == null)
{
s_StandardResources.standard = AssetDatabase.GetBuiltinExtraResource<Sprite>(kStandardSpritePath);
s_StandardResources.background = AssetDatabase.GetBuiltinExtraResource<Sprite>(kBackgroundSpritePath);
s_StandardResources.inputField = AssetDatabase.GetBuiltinExtraResource<Sprite>(kInputFieldBackgroundPath);
s_StandardResources.knob = AssetDatabase.GetBuiltinExtraResource<Sprite>(kKnobPath);
s_StandardResources.checkmark = AssetDatabase.GetBuiltinExtraResource<Sprite>(kCheckmarkPath);
s_StandardResources.dropdown = AssetDatabase.GetBuiltinExtraResource<Sprite>(kDropdownArrowPath);
s_StandardResources.mask = AssetDatabase.GetBuiltinExtraResource<Sprite>(kMaskPath);
}
return s_StandardResources;
}
private static void SetPositionVisibleinSceneView(RectTransform canvasRTransform, RectTransform itemTransform)
{
// Find the best scene view
SceneView sceneView = SceneView.lastActiveSceneView;
if (sceneView == null && SceneView.sceneViews.Count > 0)
sceneView = SceneView.sceneViews[0] as SceneView;
// Couldn't find a SceneView. Don't set position.
if (sceneView == null || sceneView.camera == null)
return;
// Create world space Plane from canvas position.
Camera camera = sceneView.camera;
Vector3 position = Vector3.zero;
Vector2 localPlanePosition;
if (RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRTransform, new Vector2(camera.pixelWidth / 2, camera.pixelHeight / 2), camera, out localPlanePosition))
{
// Adjust for canvas pivot
localPlanePosition.x = localPlanePosition.x + canvasRTransform.sizeDelta.x * canvasRTransform.pivot.x;
localPlanePosition.y = localPlanePosition.y + canvasRTransform.sizeDelta.y * canvasRTransform.pivot.y;
localPlanePosition.x = Mathf.Clamp(localPlanePosition.x, 0, canvasRTransform.sizeDelta.x);
localPlanePosition.y = Mathf.Clamp(localPlanePosition.y, 0, canvasRTransform.sizeDelta.y);
// Adjust for anchoring
position.x = localPlanePosition.x - canvasRTransform.sizeDelta.x * itemTransform.anchorMin.x;
position.y = localPlanePosition.y - canvasRTransform.sizeDelta.y * itemTransform.anchorMin.y;
Vector3 minLocalPosition;
minLocalPosition.x = canvasRTransform.sizeDelta.x * (0 - canvasRTransform.pivot.x) + itemTransform.sizeDelta.x * itemTransform.pivot.x;
minLocalPosition.y = canvasRTransform.sizeDelta.y * (0 - canvasRTransform.pivot.y) + itemTransform.sizeDelta.y * itemTransform.pivot.y;
Vector3 maxLocalPosition;
maxLocalPosition.x = canvasRTransform.sizeDelta.x * (1 - canvasRTransform.pivot.x) - itemTransform.sizeDelta.x * itemTransform.pivot.x;
maxLocalPosition.y = canvasRTransform.sizeDelta.y * (1 - canvasRTransform.pivot.y) - itemTransform.sizeDelta.y * itemTransform.pivot.y;
position.x = Mathf.Clamp(position.x, minLocalPosition.x, maxLocalPosition.x);
position.y = Mathf.Clamp(position.y, minLocalPosition.y, maxLocalPosition.y);
}
itemTransform.anchoredPosition = position;
itemTransform.localRotation = Quaternion.identity;
itemTransform.localScale = Vector3.one;
}
private static void PlaceUIElementRoot(GameObject element, MenuCommand menuCommand)
{
GameObject parent = menuCommand.context as GameObject;
bool explicitParentChoice = true;
if (parent == null)
{
parent = GetOrCreateCanvasGameObject();
explicitParentChoice = false;
// If in Prefab Mode, Canvas has to be part of Prefab contents,
// otherwise use Prefab root instead.
PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null && !prefabStage.IsPartOfPrefabContents(parent))
parent = prefabStage.prefabContentsRoot;
}
if (parent.GetComponentsInParent<Canvas>(true).Length == 0)
{
// Create canvas under context GameObject,
// and make that be the parent which UI element is added under.
GameObject canvas = CreateNewUI();
Undo.SetTransformParent(canvas.transform, parent.transform, "");
parent = canvas;
}
GameObjectUtility.EnsureUniqueNameForSibling(element);
SetParentAndAlign(element, parent);
if (!explicitParentChoice) // not a context click, so center in sceneview
SetPositionVisibleinSceneView(parent.GetComponent<RectTransform>(), element.GetComponent<RectTransform>());
// This call ensure any change made to created Objects after they where registered will be part of the Undo.
Undo.RegisterFullObjectHierarchyUndo(parent == null ? element : parent, "");
// We have to fix up the undo name since the name of the object was only known after reparenting it.
Undo.SetCurrentGroupName("Create " + element.name);
Selection.activeGameObject = element;
}
private static void SetParentAndAlign(GameObject child, GameObject parent)
{
if (parent == null)
return;
Undo.SetTransformParent(child.transform, parent.transform, "");
RectTransform rectTransform = child.transform as RectTransform;
if (rectTransform)
{
rectTransform.anchoredPosition = Vector2.zero;
Vector3 localPosition = rectTransform.localPosition;
localPosition.z = 0;
rectTransform.localPosition = localPosition;
}
else
{
child.transform.localPosition = Vector3.zero;
}
child.transform.localRotation = Quaternion.identity;
child.transform.localScale = Vector3.one;
SetLayerRecursively(child, parent.layer);
}
private static void SetLayerRecursively(GameObject go, int layer)
{
go.layer = layer;
Transform t = go.transform;
for (int i = 0; i < t.childCount; i++)
SetLayerRecursively(t.GetChild(i).gameObject, layer);
}
public static GameObject CreateNewUI()
{
// Root for the UI
var root = new GameObject("Canvas");
root.layer = LayerMask.NameToLayer(kUILayerName);
Canvas canvas = root.AddComponent<Canvas>();
canvas.renderMode = RenderMode.ScreenSpaceOverlay;
root.AddComponent<CanvasScaler>();
root.AddComponent<GraphicRaycaster>();
// Works for all stages.
StageUtility.PlaceGameObjectInCurrentStage(root);
bool customScene = false;
PrefabStage prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
if (prefabStage != null)
{
root.transform.SetParent(prefabStage.prefabContentsRoot.transform, false);
customScene = true;
}
Undo.RegisterCreatedObjectUndo(root, "Create " + root.name);
// If there is no event system add one...
// No need to place event system in custom scene as these are temporary anyway.
// It can be argued for or against placing it in the user scenes,
// but let's not modify scene user is not currently looking at.
if (!customScene)
CreateEventSystem(false);
return root;
}
private static void CreateEventSystem(bool select)
{
CreateEventSystem(select, null);
}
private static void CreateEventSystem(bool select, GameObject parent)
{
var esys = Object.FindObjectOfType<EventSystem>();
if (esys == null)
{
var eventSystem = new GameObject("EventSystem");
GameObjectUtility.SetParentAndAlign(eventSystem, parent);
esys = eventSystem.AddComponent<EventSystem>();
eventSystem.AddComponent<StandaloneInputModule>();
Undo.RegisterCreatedObjectUndo(eventSystem, "Create " + eventSystem.name);
}
if (select && esys != null)
{
Selection.activeGameObject = esys.gameObject;
}
}
// Helper function that returns a Canvas GameObject; preferably a parent of the selection, or other existing Canvas.
public static GameObject GetOrCreateCanvasGameObject()
{
GameObject selectedGo = Selection.activeGameObject;
// Try to find a gameobject that is the selected GO or one if its parents.
Canvas canvas = (selectedGo != null) ? selectedGo.GetComponentInParent<Canvas>() : null;
if (IsValidCanvas(canvas))
return canvas.gameObject;
// No canvas in selection or its parents? Then use any valid canvas.
// We have to find all loaded Canvases, not just the ones in main scenes.
Canvas[] canvasArray = StageUtility.GetCurrentStageHandle().FindComponentsOfType<Canvas>();
for (int i = 0; i < canvasArray.Length; i++)
if (IsValidCanvas(canvasArray[i]))
return canvasArray[i].gameObject;
// No canvas in the scene at all? Then create a new one.
return CreateNewUI();
}
static bool IsValidCanvas(Canvas canvas)
{
if (canvas == null || !canvas.gameObject.activeInHierarchy)
return false;
// It's important that the non-editable canvas from a prefab scene won't be rejected,
// but canvases not visible in the Hierarchy at all do. Don't check for HideAndDontSave.
if (EditorUtility.IsPersistent(canvas) || (canvas.hideFlags & HideFlags.HideInHierarchy) != 0)
return false;
if (StageUtility.GetStageHandle(canvas.gameObject) != StageUtility.GetCurrentStageHandle())
return false;
return true;
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: ee91e53d72bfe904fa18e41b4c9b7b48
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,53 @@
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.Collections;
namespace TMPro.EditorUtilities
{
public static class EditorShaderUtilities
{
/// <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;
}
}
}
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: e3abcac8c3ce6824bba7be6946886473
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,42 @@
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEditor;
using UnityEditor.TextCore.Text;
namespace TMPro.EditorUtilities
{
public class TMPro_FontAssetCreatorWindow : EditorWindow
{
private static FontAssetCreatorWindow m_Window;
[MenuItem("Window/TextMeshPro/Font Asset Creator", false, 2025)]
public static void ShowFontAtlasCreatorWindow()
{
m_Window = GetWindow<FontAssetCreatorWindow>();
m_Window.titleContent = new GUIContent("Font Asset Creator");
m_Window.Focus();
// Make sure TMP Essential Resources have been imported.
CheckEssentialResources();
}
// Make sure TMP Essential Resources have been imported.
static void CheckEssentialResources()
{
if (TMP_Settings.instance == null)
{
m_Window.Close();
TextEventManager.RESOURCE_LOAD_EVENT.Add(ON_RESOURCES_LOADED);
}
}
// Event received when TMP resources have been loaded.
static void ON_RESOURCES_LOADED()
{
TextEventManager.RESOURCE_LOAD_EVENT.Remove(ON_RESOURCES_LOADED);
ShowFontAtlasCreatorWindow();
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: a7494d6bf1b80c54284138eeb758680f
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,58 @@
using UnityEngine;
namespace TMPro
{
// Helpers used by the different sorting layer classes.
public static class SortingLayerHelper
{
// Gets an array of sorting layer names.
public static string[] sortingLayerNames
{
get
{
return GetSortingLayerNames();
}
}
static string[] GetSortingLayerNames()
{
int layerCount = SortingLayer.layers.Length;
string[] layerNames = new string[layerCount];
for (int i = 0; i < layerCount; i++)
{
layerNames[i] = SortingLayer.layers[i].name;
}
return layerNames;
}
internal static int GetSortingLayerIndexFromValue(int value)
{
int layerCount = SortingLayer.layers.Length;
for (int i = 0; i < layerCount; i++)
{
if (value == SortingLayer.layers[i].value)
return i;
}
return -1;
}
internal static int GetSortingLayerIndexFromSortingLayerID(int id)
{
int layerCount = SortingLayer.layers.Length;
for (int i = 0; i < layerCount; i++)
{
if (id == SortingLayer.layers[i].id)
return i;
}
return -1;
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 2a3ed090f0f024e4c9b683faab2b03b1
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,52 @@
using System;
namespace TMPro
{
[Obsolete("AtlasPopulationMode has been deprecated. Use AtlasPopulationMode instead (UnityUpgradable) -> [UnityEngine.TextCoreTextEngineModule] UnityEngine.TextCore.Text.AtlasPopulationMode", true)]
[UnityEngine.Internal.ExcludeFromDocs]
public enum AtlasPopulationMode
{
// Original TMP_ShaderUtilities class.
}
/*[Obsolete("ShaderUtilities has been deprecated. Use TextShaderUtilities instead (UnityUpgradable) -> UnityEngine.TextCore.Text.TextShaderUtilities", true)]
public class ShaderUtilities
{
// Original TMP_ShaderUtilities class.
}*/
[Obsolete("TMP_FontAsset has been deprecated. Use FontAsset instead (UnityUpgradable) -> [UnityEngine.TextCoreTextEngineModule] UnityEngine.TextCore.Text.FontAsset", true)]
[UnityEngine.Internal.ExcludeFromDocs]
public class TMP_FontAsset
{
// Original TMP_FontAsset class.
}
[Obsolete("TMP_SpriteAsset has been deprecated. Use SpriteAsset instead (UnityUpgradable) -> [UnityEngine.TextCoreTextEngineModule] UnityEngine.TextCore.Text.SpriteAsset", true)]
[UnityEngine.Internal.ExcludeFromDocs]
public class TMP_SpriteAsset
{
// Original TMP_SpriteAsset class.
}
[Obsolete("TMP_StyleSheet has been deprecated. Use TextStyleSheet instead (UnityUpgradable) -> [UnityEngine.TextCoreTextEngineModule] UnityEngine.TextCore.Text.TextStyleSheet", true)]
[UnityEngine.Internal.ExcludeFromDocs]
public class TMP_StyleSheet
{
// Original TMP_StyleSheet class.
}
[Obsolete("TMP_ColorGradient has been deprecated. Use TextColorGradient instead (UnityUpgradable) -> [UnityEngine.TextCoreTextEngineModule] UnityEngine.TextCore.Text.TextColorGradient", true)]
[UnityEngine.Internal.ExcludeFromDocs]
public class TMP_ColorGradient
{
// Original TMP_ColorGradient class.
}
[Obsolete("TMPro_EventManager has been deprecated. Use TextEventManager instead (UnityUpgradable) -> [UnityEngine.TextCoreTextEngineModule] UnityEngine.TextCore.Text.TextEventManager", true)]
[UnityEngine.Internal.ExcludeFromDocs]
public static class TMPro_EventManager
{
// Original TMPro_EventManager class.
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bde53ab20f68be04b816a9e44ae1bba2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,37 @@
{
"name": "Unity.TextMeshPro.Editor",
"rootNamespace": "",
"references": [
"Unity.TextMeshPro",
"Unity.RenderPipelines.HighDefinition.Editor",
"Unity.RenderPipelines.Core.Runtime",
"Unity.RenderPipelines.HighDefinition.Runtime"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [
{
"name": "com.unity.render-pipelines.high-definition",
"expression": "10.7.0",
"define": "HDRP_10_7_OR_NEWER"
},
{
"name": "com.unity.render-pipelines.high-definition",
"expression": "11.0.0",
"define": "HDRP_11_OR_NEWER"
},
{
"name": "com.unity.render-pipelines.high-definition",
"expression": "12.0.0",
"define": "HDRP_12_OR_NEWER"
}
],
"noEngineReferences": false
}

View File

@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 43c7445480589fb4a944cdc658afd52e
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0e4b83ad61a6f8d47903753b697fd514
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,11 @@
using System.Runtime.CompilerServices;
// Allow internal visibility for testing purposes.
[assembly: InternalsVisibleTo("Unity.TextCore")]
[assembly: InternalsVisibleTo("Unity.FontEngine.Tests")]
#if UNITY_EDITOR
[assembly: InternalsVisibleTo("Unity.TextCore.Editor")]
[assembly: InternalsVisibleTo("Unity.TextMeshPro.Editor")]
#endif

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cc4155a9f4c4a61478dced5053f1bd07
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,17 @@

namespace TMPro
{
/// <summary>
/// Interface used for preprocessing and shaping of text.
/// </summary>
public interface ITextPreprocessor
{
/// <summary>
/// Function used for preprocessing of text
/// </summary>
/// <param name="text">Source text to be processed</param>
/// <returns>Processed text</returns>
string PreprocessText(string text);
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 04973cf92f7eb984989cc757a35ce78c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,623 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.TextCore.Text;
namespace TMPro
{
public class MaterialReferenceManager
{
private static MaterialReferenceManager s_Instance;
// Dictionaries used to track Asset references.
private Dictionary<int, Material> m_FontMaterialReferenceLookup = new Dictionary<int, Material>();
private Dictionary<int, FontAsset> m_FontAssetReferenceLookup = new Dictionary<int, FontAsset>();
private Dictionary<int, SpriteAsset> m_SpriteAssetReferenceLookup = new Dictionary<int, SpriteAsset>();
private Dictionary<int, TextColorGradient> m_ColorGradientReferenceLookup = new Dictionary<int, TextColorGradient>();
/// <summary>
/// Get a singleton instance of the registry
/// </summary>
public static MaterialReferenceManager instance
{
get
{
if (MaterialReferenceManager.s_Instance == null)
MaterialReferenceManager.s_Instance = new MaterialReferenceManager();
return MaterialReferenceManager.s_Instance;
}
}
/// <summary>
/// Add new font asset reference to dictionary.
/// </summary>
/// <param name="fontAsset"></param>
public static void AddFontAsset(FontAsset fontAsset)
{
MaterialReferenceManager.instance.AddFontAssetInternal(fontAsset);
}
/// <summary>
/// Add new Font Asset reference to dictionary.
/// </summary>
/// <param name="fontAsset"></param>
private void AddFontAssetInternal(FontAsset fontAsset)
{
if (m_FontAssetReferenceLookup.ContainsKey(fontAsset.hashCode)) return;
// Add reference to the font asset.
m_FontAssetReferenceLookup.Add(fontAsset.hashCode, fontAsset);
// Add reference to the font material.
m_FontMaterialReferenceLookup.Add(fontAsset.materialHashCode, fontAsset.material);
}
/// <summary>
/// Add new Sprite Asset to dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="spriteAsset"></param>
public static void AddSpriteAsset(SpriteAsset spriteAsset)
{
MaterialReferenceManager.instance.AddSpriteAssetInternal(spriteAsset);
}
/// <summary>
/// Internal method to add a new sprite asset to the dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="spriteAsset"></param>
private void AddSpriteAssetInternal(SpriteAsset spriteAsset)
{
if (m_SpriteAssetReferenceLookup.ContainsKey(spriteAsset.hashCode)) return;
// Add reference to sprite asset.
m_SpriteAssetReferenceLookup.Add(spriteAsset.hashCode, spriteAsset);
// Adding reference to the sprite asset material as well
m_FontMaterialReferenceLookup.Add(spriteAsset.hashCode, spriteAsset.material);
}
/// <summary>
/// Add new Sprite Asset to dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="spriteAsset"></param>
public static void AddSpriteAsset(int hashCode, SpriteAsset spriteAsset)
{
MaterialReferenceManager.instance.AddSpriteAssetInternal(hashCode, spriteAsset);
}
/// <summary>
/// Internal method to add a new sprite asset to the dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="spriteAsset"></param>
private void AddSpriteAssetInternal(int hashCode, SpriteAsset spriteAsset)
{
if (m_SpriteAssetReferenceLookup.ContainsKey(hashCode)) return;
// Add reference to Sprite Asset.
m_SpriteAssetReferenceLookup.Add(hashCode, spriteAsset);
// Add reference to Sprite Asset using the asset hashcode.
m_FontMaterialReferenceLookup.Add(hashCode, spriteAsset.material);
// Compatibility check
if (spriteAsset.hashCode == 0)
spriteAsset.hashCode = hashCode;
}
/// <summary>
/// Add new Material reference to dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="material"></param>
public static void AddFontMaterial(int hashCode, Material material)
{
MaterialReferenceManager.instance.AddFontMaterialInternal(hashCode, material);
}
/// <summary>
/// Add new material reference to dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="material"></param>
private void AddFontMaterialInternal(int hashCode, Material material)
{
// Since this function is called after checking if the material is
// contained in the dictionary, there is no need to check again.
m_FontMaterialReferenceLookup.Add(hashCode, material);
}
/// <summary>
/// Add new Color Gradient Preset to dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="spriteAsset"></param>
public static void AddColorGradientPreset(int hashCode, TextColorGradient spriteAsset)
{
MaterialReferenceManager.instance.AddColorGradientPreset_Internal(hashCode, spriteAsset);
}
/// <summary>
/// Internal method to add a new Color Gradient Preset to the dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="spriteAsset"></param>
private void AddColorGradientPreset_Internal(int hashCode, TextColorGradient spriteAsset)
{
if (m_ColorGradientReferenceLookup.ContainsKey(hashCode)) return;
// Add reference to Color Gradient Preset Asset.
m_ColorGradientReferenceLookup.Add(hashCode, spriteAsset);
}
/// <summary>
/// Add new material reference and return the index of this new reference in the materialReferences array.
/// </summary>
/// <param name="material"></param>
/// <param name="materialHashCode"></param>
/// <param name="fontAsset"></param>
//public int AddMaterial(Material material, int materialHashCode, TMP_FontAsset fontAsset)
//{
// if (!m_MaterialReferenceLookup.ContainsKey(materialHashCode))
// {
// int index = m_MaterialReferenceLookup.Count;
// materialReferences[index].fontAsset = fontAsset;
// materialReferences[index].material = material;
// materialReferences[index].isDefaultMaterial = material.GetInstanceID() == fontAsset.material.GetInstanceID() ? true : false;
// materialReferences[index].index = index;
// materialReferences[index].referenceCount = 0;
// m_MaterialReferenceLookup[materialHashCode] = index;
// // Compute Padding value and store it
// // TODO
// int fontAssetHashCode = fontAsset.hashCode;
// if (!m_FontAssetReferenceLookup.ContainsKey(fontAssetHashCode))
// m_FontAssetReferenceLookup.Add(fontAssetHashCode, fontAsset);
// m_countInternal += 1;
// return index;
// }
// else
// {
// return m_MaterialReferenceLookup[materialHashCode];
// }
//}
/// <summary>
/// Add new material reference and return the index of this new reference in the materialReferences array.
/// </summary>
/// <param name="material"></param>
/// <param name="materialHashCode"></param>
/// <param name="spriteAsset"></param>
/// <returns></returns>
//public int AddMaterial(Material material, int materialHashCode, TMP_SpriteAsset spriteAsset)
//{
// if (!m_MaterialReferenceLookup.ContainsKey(materialHashCode))
// {
// int index = m_MaterialReferenceLookup.Count;
// materialReferences[index].fontAsset = materialReferences[0].fontAsset;
// materialReferences[index].spriteAsset = spriteAsset;
// materialReferences[index].material = material;
// materialReferences[index].isDefaultMaterial = true;
// materialReferences[index].index = index;
// materialReferences[index].referenceCount = 0;
// m_MaterialReferenceLookup[materialHashCode] = index;
// int spriteAssetHashCode = spriteAsset.hashCode;
// if (!m_SpriteAssetReferenceLookup.ContainsKey(spriteAssetHashCode))
// m_SpriteAssetReferenceLookup.Add(spriteAssetHashCode, spriteAsset);
// m_countInternal += 1;
// return index;
// }
// else
// {
// return m_MaterialReferenceLookup[materialHashCode];
// }
//}
/// <summary>
/// Function to check if the font asset is already referenced.
/// </summary>
/// <param name="font"></param>
/// <returns></returns>
public bool Contains(FontAsset font)
{
return m_FontAssetReferenceLookup.ContainsKey(font.hashCode);
}
/// <summary>
/// Function to check if the sprite asset is already referenced.
/// </summary>
/// <param name="font"></param>
/// <returns></returns>
public bool Contains(SpriteAsset sprite)
{
return m_FontAssetReferenceLookup.ContainsKey(sprite.hashCode);
}
/// <summary>
/// Function returning the Font Asset corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="fontAsset"></param>
/// <returns></returns>
public static bool TryGetFontAsset(int hashCode, out FontAsset fontAsset)
{
return MaterialReferenceManager.instance.TryGetFontAssetInternal(hashCode, out fontAsset);
}
/// <summary>
/// Internal Function returning the Font Asset corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="fontAsset"></param>
/// <returns></returns>
private bool TryGetFontAssetInternal(int hashCode, out FontAsset fontAsset)
{
fontAsset = null;
return m_FontAssetReferenceLookup.TryGetValue(hashCode, out fontAsset);
}
/// <summary>
/// Function returning the Sprite Asset corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="spriteAsset"></param>
/// <returns></returns>
public static bool TryGetSpriteAsset(int hashCode, out SpriteAsset spriteAsset)
{
return MaterialReferenceManager.instance.TryGetSpriteAssetInternal(hashCode, out spriteAsset);
}
/// <summary>
/// Internal function returning the Sprite Asset corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="fontAsset"></param>
/// <returns></returns>
private bool TryGetSpriteAssetInternal(int hashCode, out SpriteAsset spriteAsset)
{
spriteAsset = null;
return m_SpriteAssetReferenceLookup.TryGetValue(hashCode, out spriteAsset);
}
/// <summary>
/// Function returning the Color Gradient Preset corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="gradientPreset"></param>
/// <returns></returns>
public static bool TryGetColorGradientPreset(int hashCode, out TextColorGradient gradientPreset)
{
return MaterialReferenceManager.instance.TryGetColorGradientPresetInternal(hashCode, out gradientPreset);
}
/// <summary>
/// Internal function returning the Color Gradient Preset corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="fontAsset"></param>
/// <returns></returns>
private bool TryGetColorGradientPresetInternal(int hashCode, out TextColorGradient gradientPreset)
{
gradientPreset = null;
return m_ColorGradientReferenceLookup.TryGetValue(hashCode, out gradientPreset);
}
/// <summary>
/// Function returning the Font Material corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="material"></param>
/// <returns></returns>
public static bool TryGetMaterial(int hashCode, out Material material)
{
return MaterialReferenceManager.instance.TryGetMaterialInternal(hashCode, out material);
}
/// <summary>
/// Internal function returning the Font Material corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="material"></param>
/// <returns></returns>
private bool TryGetMaterialInternal(int hashCode, out Material material)
{
material = null;
return m_FontMaterialReferenceLookup.TryGetValue(hashCode, out material);
}
/// <summary>
/// Function to lookup a material based on hash code and returning the MaterialReference containing this material.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="material"></param>
/// <returns></returns>
//public bool TryGetMaterial(int hashCode, out MaterialReference materialReference)
//{
// int materialIndex = -1;
// if (m_MaterialReferenceLookup.TryGetValue(hashCode, out materialIndex))
// {
// materialReference = materialReferences[materialIndex];
// return true;
// }
// materialReference = new MaterialReference();
// return false;
//}
/// <summary>
///
/// </summary>
/// <param name="fontAsset"></param>
/// <returns></returns>
//public int GetMaterialIndex(TMP_FontAsset fontAsset)
//{
// if (m_MaterialReferenceLookup.ContainsKey(fontAsset.materialHashCode))
// return m_MaterialReferenceLookup[fontAsset.materialHashCode];
// return -1;
//}
/// <summary>
///
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
//public TMP_FontAsset GetFontAsset(int index)
//{
// if (index >= 0 && index < materialReferences.Length)
// return materialReferences[index].fontAsset;
// return null;
//}
/// <summary>
///
/// </summary>
/// <param name="material"></param>
/// <param name="materialHashCode"></param>
/// <param name="fontAsset"></param>
//public void SetDefaultMaterial(Material material, int materialHashCode, TMP_FontAsset fontAsset)
//{
// if (!m_MaterialReferenceLookup.ContainsKey(materialHashCode))
// {
// materialReferences[0].fontAsset = fontAsset;
// materialReferences[0].material = material;
// materialReferences[0].index = 0;
// materialReferences[0].isDefaultMaterial = material.GetInstanceID() == fontAsset.material.GetInstanceID() ? true : false;
// materialReferences[0].referenceCount = 0;
// m_MaterialReferenceLookup[materialHashCode] = 0;
// // Compute Padding value and store it
// // TODO
// int fontHashCode = fontAsset.hashCode;
// if (!m_FontAssetReferenceLookup.ContainsKey(fontHashCode))
// m_FontAssetReferenceLookup.Add(fontHashCode, fontAsset);
// }
// else
// {
// materialReferences[0].fontAsset = fontAsset;
// materialReferences[0].material = material;
// materialReferences[0].index = 0;
// materialReferences[0].referenceCount = 0;
// m_MaterialReferenceLookup[materialHashCode] = 0;
// }
// // Compute padding
// // TODO
// m_countInternal = 1;
//}
/// <summary>
///
/// </summary>
//public void Clear()
//{
// //m_currentIndex = 0;
// m_MaterialReferenceLookup.Clear();
// m_SpriteAssetReferenceLookup.Clear();
// m_FontAssetReferenceLookup.Clear();
//}
/// <summary>
/// Function to clear the reference count for each of the material references.
/// </summary>
//public void ClearReferenceCount()
//{
// m_countInternal = 0;
// for (int i = 0; i < materialReferences.Length; i++)
// {
// if (materialReferences[i].fontAsset == null)
// return;
// materialReferences[i].referenceCount = 0;
// }
//}
}
public struct TMP_MaterialReference
{
public Material material;
public int referenceCount;
}
public struct MaterialReference
{
public int index;
public FontAsset fontAsset;
public SpriteAsset spriteAsset;
public Material material;
public bool isDefaultMaterial;
public bool isFallbackMaterial;
public Material fallbackMaterial;
public float padding;
public int referenceCount;
/// <summary>
/// Constructor for new Material Reference.
/// </summary>
/// <param name="index"></param>
/// <param name="fontAsset"></param>
/// <param name="spriteAsset"></param>
/// <param name="material"></param>
/// <param name="padding"></param>
public MaterialReference(int index, FontAsset fontAsset, SpriteAsset spriteAsset, Material material, float padding)
{
this.index = index;
this.fontAsset = fontAsset;
this.spriteAsset = spriteAsset;
this.material = material;
this.isDefaultMaterial = material.GetInstanceID() == fontAsset.material.GetInstanceID();
this.isFallbackMaterial = false;
this.fallbackMaterial = null;
this.padding = padding;
this.referenceCount = 0;
}
/// <summary>
/// Function to check if a certain font asset is contained in the material reference array.
/// </summary>
/// <param name="materialReferences"></param>
/// <param name="fontAsset"></param>
/// <returns></returns>
public static bool Contains(MaterialReference[] materialReferences, FontAsset fontAsset)
{
int id = fontAsset.GetInstanceID();
for (int i = 0; i < materialReferences.Length && materialReferences[i].fontAsset != null; i++)
{
if (materialReferences[i].fontAsset.GetInstanceID() == id)
return true;
}
return false;
}
/// <summary>
/// Function to add a new material reference and returning its index in the material reference array.
/// </summary>
/// <param name="material"></param>
/// <param name="fontAsset"></param>
/// <param name="materialReferences"></param>
/// <param name="materialReferenceIndexLookup"></param>
/// <returns></returns>
public static int AddMaterialReference(Material material, FontAsset fontAsset, ref MaterialReference[] materialReferences, Dictionary<int, int> materialReferenceIndexLookup)
{
int materialID = material.GetInstanceID();
int index;
if (materialReferenceIndexLookup.TryGetValue(materialID, out index))
return index;
index = materialReferenceIndexLookup.Count;
// Add new reference index
materialReferenceIndexLookup[materialID] = index;
if (index >= materialReferences.Length)
System.Array.Resize(ref materialReferences, Mathf.NextPowerOfTwo(index + 1));
materialReferences[index].index = index;
materialReferences[index].fontAsset = fontAsset;
materialReferences[index].spriteAsset = null;
materialReferences[index].material = material;
materialReferences[index].isDefaultMaterial = materialID == fontAsset.material.GetInstanceID();
materialReferences[index].referenceCount = 0;
return index;
}
/// <summary>
///
/// </summary>
/// <param name="material"></param>
/// <param name="spriteAsset"></param>
/// <param name="materialReferences"></param>
/// <param name="materialReferenceIndexLookup"></param>
/// <returns></returns>
public static int AddMaterialReference(Material material, SpriteAsset spriteAsset, ref MaterialReference[] materialReferences, Dictionary<int, int> materialReferenceIndexLookup)
{
int materialID = material.GetInstanceID();
int index;
if (materialReferenceIndexLookup.TryGetValue(materialID, out index))
return index;
index = materialReferenceIndexLookup.Count;
// Add new reference index
materialReferenceIndexLookup[materialID] = index;
if (index >= materialReferences.Length)
System.Array.Resize(ref materialReferences, Mathf.NextPowerOfTwo(index + 1));
materialReferences[index].index = index;
materialReferences[index].fontAsset = materialReferences[0].fontAsset;
materialReferences[index].spriteAsset = spriteAsset;
materialReferences[index].material = material;
materialReferences[index].isDefaultMaterial = true;
materialReferences[index].referenceCount = 0;
return index;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 3fd0378c8b128984483147606e14726e
timeCreated: 1449743129
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,220 @@
using System.Diagnostics;
using UnityEngine;
using UnityEngine.TextCore;
using UnityEngine.TextCore.Text;
namespace TMPro
{
public struct TMP_Vertex
{
public Vector3 position;
public Vector4 uv;
public Vector2 uv2;
//public Vector2 uv4;
public Color32 color;
public static TMP_Vertex zero { get { return k_Zero; } }
//public Vector3 normal;
//public Vector4 tangent;
static readonly TMP_Vertex k_Zero = new TMP_Vertex();
}
/// <summary>
///
/// </summary>
public struct TMP_Offset
{
public float left { get { return m_Left; } set { m_Left = value; } }
public float right { get { return m_Right; } set { m_Right = value; } }
public float top { get { return m_Top; } set { m_Top = value; } }
public float bottom { get { return m_Bottom; } set { m_Bottom = value; } }
public float horizontal { get { return m_Left; } set { m_Left = value; m_Right = value; } }
public float vertical { get { return m_Top; } set { m_Top = value; m_Bottom = value; } }
/// <summary>
///
/// </summary>
public static TMP_Offset zero { get { return k_ZeroOffset; } }
// =============================================
// Private backing fields for public properties.
// =============================================
float m_Left;
float m_Right;
float m_Top;
float m_Bottom;
static readonly TMP_Offset k_ZeroOffset = new TMP_Offset(0F, 0F, 0F, 0F);
/// <summary>
///
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <param name="top"></param>
/// <param name="bottom"></param>
public TMP_Offset(float left, float right, float top, float bottom)
{
m_Left = left;
m_Right = right;
m_Top = top;
m_Bottom = bottom;
}
/// <summary>
///
/// </summary>
/// <param name="horizontal"></param>
/// <param name="vertical"></param>
public TMP_Offset(float horizontal, float vertical)
{
m_Left = horizontal;
m_Right = horizontal;
m_Top = vertical;
m_Bottom = vertical;
}
public static bool operator ==(TMP_Offset lhs, TMP_Offset rhs)
{
return lhs.m_Left == rhs.m_Left &&
lhs.m_Right == rhs.m_Right &&
lhs.m_Top == rhs.m_Top &&
lhs.m_Bottom == rhs.m_Bottom;
}
public static bool operator !=(TMP_Offset lhs, TMP_Offset rhs)
{
return !(lhs == rhs);
}
public static TMP_Offset operator *(TMP_Offset a, float b)
{
return new TMP_Offset(a.m_Left * b, a.m_Right * b, a.m_Top * b, a.m_Bottom * b);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public bool Equals(TMP_Offset other)
{
return base.Equals(other);
}
}
/// <summary>
///
/// </summary>
public struct HighlightState
{
public Color32 color;
public TMP_Offset padding;
public HighlightState(Color32 color, TMP_Offset padding)
{
this.color = color;
this.padding = padding;
}
public static bool operator ==(HighlightState lhs, HighlightState rhs)
{
return lhs.color.Compare(rhs.color) && lhs.padding == rhs.padding;
}
public static bool operator !=(HighlightState lhs, HighlightState rhs)
{
return !(lhs == rhs);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public bool Equals(HighlightState other)
{
return base.Equals(other);
}
}
/// <summary>
/// Structure containing information about individual text elements (character or sprites).
/// </summary>
[DebuggerDisplay("Unicode '{character}' ({((uint)character).ToString(\"X\")})")]
public struct TMP_CharacterInfo
{
public TMP_TextElementType elementType;
public char character; // Should be changed to an uint to handle UTF32
public int index;
public int stringLength;
public TextElement textElement;
public Glyph alternativeGlyph;
public FontAsset fontAsset;
public Material material;
public int materialReferenceIndex;
public bool isUsingAlternateTypeface;
public float pointSize;
//public short wordNumber;
public int lineNumber;
//public short charNumber;
public int pageNumber;
public int vertexIndex;
public TMP_Vertex vertex_BL;
public TMP_Vertex vertex_TL;
public TMP_Vertex vertex_TR;
public TMP_Vertex vertex_BR;
public Vector3 topLeft;
public Vector3 bottomLeft;
public Vector3 topRight;
public Vector3 bottomRight;
public float origin;
public float xAdvance;
public float ascender;
public float baseLine;
public float descender;
internal float adjustedAscender;
internal float adjustedDescender;
internal float adjustedHorizontalAdvance;
public float aspectRatio;
public float scale;
public Color32 color;
public Color32 underlineColor;
public int underlineVertexIndex;
public Color32 strikethroughColor;
public int strikethroughVertexIndex;
public Color32 highlightColor;
public HighlightState highlightState;
public FontStyles style;
public bool isVisible;
//public bool isIgnoringAlignment;
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 78117be65f9ab544a9a373a26f4148f0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,74 @@
using UnityEngine;
using System.Collections;
namespace TMPro
{
// Class used to convert scenes and objects saved in version 0.1.44 to the new Text Container
public static class TMP_Compatibility
{
public enum AnchorPositions { TopLeft, Top, TopRight, Left, Center, Right, BottomLeft, Bottom, BottomRight, BaseLine, None };
/// <summary>
/// Function used to convert text alignment option enumeration format.
/// </summary>
/// <param name="oldValue"></param>
/// <returns></returns>
public static TextAlignmentOptions ConvertTextAlignmentEnumValues(TextAlignmentOptions oldValue)
{
switch ((int)oldValue)
{
case 0:
return TextAlignmentOptions.TopLeft;
case 1:
return TextAlignmentOptions.Top;
case 2:
return TextAlignmentOptions.TopRight;
case 3:
return TextAlignmentOptions.TopJustified;
case 4:
return TextAlignmentOptions.Left;
case 5:
return TextAlignmentOptions.Center;
case 6:
return TextAlignmentOptions.Right;
case 7:
return TextAlignmentOptions.Justified;
case 8:
return TextAlignmentOptions.BottomLeft;
case 9:
return TextAlignmentOptions.Bottom;
case 10:
return TextAlignmentOptions.BottomRight;
case 11:
return TextAlignmentOptions.BottomJustified;
case 12:
return TextAlignmentOptions.BaselineLeft;
case 13:
return TextAlignmentOptions.Baseline;
case 14:
return TextAlignmentOptions.BaselineRight;
case 15:
return TextAlignmentOptions.BaselineJustified;
case 16:
return TextAlignmentOptions.MidlineLeft;
case 17:
return TextAlignmentOptions.Midline;
case 18:
return TextAlignmentOptions.MidlineRight;
case 19:
return TextAlignmentOptions.MidlineJustified;
case 20:
return TextAlignmentOptions.CaplineLeft;
case 21:
return TextAlignmentOptions.Capline;
case 22:
return TextAlignmentOptions.CaplineRight;
case 23:
return TextAlignmentOptions.CaplineJustified;
}
return TextAlignmentOptions.TopLeft;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2c9cc00f0e8000543a1ed26c2a0f1f0b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,246 @@
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
namespace TMPro
{
// Base interface for tweeners,
// using an interface instead of
// an abstract class as we want the
// tweens to be structs.
internal interface ITweenValue
{
void TweenValue(float floatPercentage);
bool ignoreTimeScale { get; }
float duration { get; }
bool ValidTarget();
}
// Color tween class, receives the
// TweenValue callback and then sets
// the value on the target.
internal struct ColorTween : ITweenValue
{
public enum ColorTweenMode
{
All,
RGB,
Alpha
}
public class ColorTweenCallback : UnityEvent<Color> { }
private ColorTweenCallback m_Target;
private Color m_StartColor;
private Color m_TargetColor;
private ColorTweenMode m_TweenMode;
private float m_Duration;
private bool m_IgnoreTimeScale;
public Color startColor
{
get { return m_StartColor; }
set { m_StartColor = value; }
}
public Color targetColor
{
get { return m_TargetColor; }
set { m_TargetColor = value; }
}
public ColorTweenMode tweenMode
{
get { return m_TweenMode; }
set { m_TweenMode = value; }
}
public float duration
{
get { return m_Duration; }
set { m_Duration = value; }
}
public bool ignoreTimeScale
{
get { return m_IgnoreTimeScale; }
set { m_IgnoreTimeScale = value; }
}
public void TweenValue(float floatPercentage)
{
if (!ValidTarget())
return;
var newColor = Color.Lerp(m_StartColor, m_TargetColor, floatPercentage);
if (m_TweenMode == ColorTweenMode.Alpha)
{
newColor.r = m_StartColor.r;
newColor.g = m_StartColor.g;
newColor.b = m_StartColor.b;
}
else if (m_TweenMode == ColorTweenMode.RGB)
{
newColor.a = m_StartColor.a;
}
m_Target.Invoke(newColor);
}
public void AddOnChangedCallback(UnityAction<Color> callback)
{
if (m_Target == null)
m_Target = new ColorTweenCallback();
m_Target.AddListener(callback);
}
public bool GetIgnoreTimescale()
{
return m_IgnoreTimeScale;
}
public float GetDuration()
{
return m_Duration;
}
public bool ValidTarget()
{
return m_Target != null;
}
}
// Float tween class, receives the
// TweenValue callback and then sets
// the value on the target.
internal struct FloatTween : ITweenValue
{
public class FloatTweenCallback : UnityEvent<float> { }
private FloatTweenCallback m_Target;
private float m_StartValue;
private float m_TargetValue;
private float m_Duration;
private bool m_IgnoreTimeScale;
public float startValue
{
get { return m_StartValue; }
set { m_StartValue = value; }
}
public float targetValue
{
get { return m_TargetValue; }
set { m_TargetValue = value; }
}
public float duration
{
get { return m_Duration; }
set { m_Duration = value; }
}
public bool ignoreTimeScale
{
get { return m_IgnoreTimeScale; }
set { m_IgnoreTimeScale = value; }
}
public void TweenValue(float floatPercentage)
{
if (!ValidTarget())
return;
var newValue = Mathf.Lerp(m_StartValue, m_TargetValue, floatPercentage);
m_Target.Invoke(newValue);
}
public void AddOnChangedCallback(UnityAction<float> callback)
{
if (m_Target == null)
m_Target = new FloatTweenCallback();
m_Target.AddListener(callback);
}
public bool GetIgnoreTimescale()
{
return m_IgnoreTimeScale;
}
public float GetDuration()
{
return m_Duration;
}
public bool ValidTarget()
{
return m_Target != null;
}
}
// Tween runner, executes the given tween.
// The coroutine will live within the given
// behaviour container.
internal class TweenRunner<T> where T : struct, ITweenValue
{
protected MonoBehaviour m_CoroutineContainer;
protected IEnumerator m_Tween;
// utility function for starting the tween
private static IEnumerator Start(T tweenInfo)
{
if (!tweenInfo.ValidTarget())
yield break;
var elapsedTime = 0.0f;
while (elapsedTime < tweenInfo.duration)
{
elapsedTime += tweenInfo.ignoreTimeScale ? Time.unscaledDeltaTime : Time.deltaTime;
var percentage = Mathf.Clamp01(elapsedTime / tweenInfo.duration);
tweenInfo.TweenValue(percentage);
yield return null;
}
tweenInfo.TweenValue(1.0f);
}
public void Init(MonoBehaviour coroutineContainer)
{
m_CoroutineContainer = coroutineContainer;
}
public void StartTween(T info)
{
if (m_CoroutineContainer == null)
{
Debug.LogWarning("Coroutine container not configured... did you forget to call Init?");
return;
}
StopTween();
if (!m_CoroutineContainer.gameObject.activeInHierarchy)
{
info.TweenValue(1.0f);
return;
}
m_Tween = Start(info);
m_CoroutineContainer.StartCoroutine(m_Tween);
}
public void StopTween()
{
if (m_Tween != null)
{
m_CoroutineContainer.StopCoroutine(m_Tween);
m_Tween = null;
}
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 38133bafd4674d242835faca6f9f864f
timeCreated: 1464850953
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,399 @@
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace TMPro
{
public static class TMP_DefaultControls
{
public struct Resources
{
public Sprite standard;
public Sprite background;
public Sprite inputField;
public Sprite knob;
public Sprite checkmark;
public Sprite dropdown;
public Sprite mask;
}
private const float kWidth = 160f;
private const float kThickHeight = 30f;
private const float kThinHeight = 20f;
private static Vector2 s_TextElementSize = new Vector2(100f, 100f);
private static Vector2 s_ThickElementSize = new Vector2(kWidth, kThickHeight);
private static Vector2 s_ThinElementSize = new Vector2(kWidth, kThinHeight);
//private static Vector2 s_ImageElementSize = new Vector2(100f, 100f);
private static Color s_DefaultSelectableColor = new Color(1f, 1f, 1f, 1f);
//private static Color s_PanelColor = new Color(1f, 1f, 1f, 0.392f);
private static Color s_TextColor = new Color(50f / 255f, 50f / 255f, 50f / 255f, 1f);
private static GameObject CreateUIElementRoot(string name, Vector2 size)
{
GameObject child = new GameObject(name);
RectTransform rectTransform = child.AddComponent<RectTransform>();
rectTransform.sizeDelta = size;
return child;
}
static GameObject CreateUIObject(string name, GameObject parent)
{
GameObject go = new GameObject(name);
go.AddComponent<RectTransform>();
SetParentAndAlign(go, parent);
return go;
}
private static void SetDefaultTextValues(TMP_Text lbl)
{
// Set text values we want across UI elements in default controls.
// Don't set values which are the same as the default values for the Text component,
// since there's no point in that, and it's good to keep them as consistent as possible.
lbl.color = s_TextColor;
lbl.fontSize = 14;
}
private static void SetDefaultColorTransitionValues(Selectable slider)
{
ColorBlock colors = slider.colors;
colors.highlightedColor = new Color(0.882f, 0.882f, 0.882f);
colors.pressedColor = new Color(0.698f, 0.698f, 0.698f);
colors.disabledColor = new Color(0.521f, 0.521f, 0.521f);
}
private static void SetParentAndAlign(GameObject child, GameObject parent)
{
if (parent == null)
return;
child.transform.SetParent(parent.transform, false);
SetLayerRecursively(child, parent.layer);
}
private static void SetLayerRecursively(GameObject go, int layer)
{
go.layer = layer;
Transform t = go.transform;
for (int i = 0; i < t.childCount; i++)
SetLayerRecursively(t.GetChild(i).gameObject, layer);
}
// Actual controls
public static GameObject CreateScrollbar(Resources resources)
{
// Create GOs Hierarchy
GameObject scrollbarRoot = CreateUIElementRoot("Scrollbar", s_ThinElementSize);
GameObject sliderArea = CreateUIObject("Sliding Area", scrollbarRoot);
GameObject handle = CreateUIObject("Handle", sliderArea);
Image bgImage = scrollbarRoot.AddComponent<Image>();
bgImage.sprite = resources.background;
bgImage.type = Image.Type.Sliced;
bgImage.color = s_DefaultSelectableColor;
Image handleImage = handle.AddComponent<Image>();
handleImage.sprite = resources.standard;
handleImage.type = Image.Type.Sliced;
handleImage.color = s_DefaultSelectableColor;
RectTransform sliderAreaRect = sliderArea.GetComponent<RectTransform>();
sliderAreaRect.sizeDelta = new Vector2(-20, -20);
sliderAreaRect.anchorMin = Vector2.zero;
sliderAreaRect.anchorMax = Vector2.one;
RectTransform handleRect = handle.GetComponent<RectTransform>();
handleRect.sizeDelta = new Vector2(20, 20);
Scrollbar scrollbar = scrollbarRoot.AddComponent<Scrollbar>();
scrollbar.handleRect = handleRect;
scrollbar.targetGraphic = handleImage;
SetDefaultColorTransitionValues(scrollbar);
return scrollbarRoot;
}
public static GameObject CreateButton(Resources resources)
{
GameObject buttonRoot = CreateUIElementRoot("Button", s_ThickElementSize);
GameObject childText = new GameObject("Text (TMP)");
childText.AddComponent<RectTransform>();
SetParentAndAlign(childText, buttonRoot);
Image image = buttonRoot.AddComponent<Image>();
image.sprite = resources.standard;
image.type = Image.Type.Sliced;
image.color = s_DefaultSelectableColor;
Button bt = buttonRoot.AddComponent<Button>();
SetDefaultColorTransitionValues(bt);
TextMeshProUGUI text = childText.AddComponent<TextMeshProUGUI>();
text.text = "Button";
text.alignment = TextAlignmentOptions.Center;
SetDefaultTextValues(text);
RectTransform textRectTransform = childText.GetComponent<RectTransform>();
textRectTransform.anchorMin = Vector2.zero;
textRectTransform.anchorMax = Vector2.one;
textRectTransform.sizeDelta = Vector2.zero;
return buttonRoot;
}
public static GameObject CreateText(Resources resources)
{
GameObject go = null;
#if UNITY_EDITOR
go = ObjectFactory.CreateGameObject("Text (TMP)");
ObjectFactory.AddComponent<TextMeshProUGUI>(go);
#else
go = CreateUIElementRoot("Text (TMP)", s_TextElementSize);
go.AddComponent<TextMeshProUGUI>();
#endif
return go;
}
public static GameObject CreateInputField(Resources resources)
{
GameObject root = CreateUIElementRoot("InputField (TMP)", s_ThickElementSize);
GameObject textArea = CreateUIObject("Text Area", root);
GameObject childPlaceholder = CreateUIObject("Placeholder", textArea);
GameObject childText = CreateUIObject("Text", textArea);
Image image = root.AddComponent<Image>();
image.sprite = resources.inputField;
image.type = Image.Type.Sliced;
image.color = s_DefaultSelectableColor;
TMP_InputField inputField = root.AddComponent<TMP_InputField>();
SetDefaultColorTransitionValues(inputField);
RectMask2D rectMask = textArea.AddComponent<RectMask2D>();
#if UNITY_2019_4_OR_NEWER
rectMask.padding = new Vector4(-8, -5, -8, -5);
#endif
RectTransform textAreaRectTransform = textArea.GetComponent<RectTransform>();
textAreaRectTransform.anchorMin = Vector2.zero;
textAreaRectTransform.anchorMax = Vector2.one;
textAreaRectTransform.sizeDelta = Vector2.zero;
textAreaRectTransform.offsetMin = new Vector2(10, 6);
textAreaRectTransform.offsetMax = new Vector2(-10, -7);
TextMeshProUGUI text = childText.AddComponent<TextMeshProUGUI>();
text.text = "";
text.textWrappingMode = TextWrappingModes.NoWrap;
text.extraPadding = true;
text.richText = true;
SetDefaultTextValues(text);
TextMeshProUGUI placeholder = childPlaceholder.AddComponent<TextMeshProUGUI>();
placeholder.text = "Enter text...";
placeholder.fontSize = 14;
placeholder.fontStyle = FontStyles.Italic;
placeholder.textWrappingMode = TextWrappingModes.NoWrap;
placeholder.extraPadding = true;
// Make placeholder color half as opaque as normal text color.
Color placeholderColor = text.color;
placeholderColor.a *= 0.5f;
placeholder.color = placeholderColor;
// Add Layout component to placeholder.
placeholder.gameObject.AddComponent<LayoutElement>().ignoreLayout = true;
RectTransform textRectTransform = childText.GetComponent<RectTransform>();
textRectTransform.anchorMin = Vector2.zero;
textRectTransform.anchorMax = Vector2.one;
textRectTransform.sizeDelta = Vector2.zero;
textRectTransform.offsetMin = new Vector2(0, 0);
textRectTransform.offsetMax = new Vector2(0, 0);
RectTransform placeholderRectTransform = childPlaceholder.GetComponent<RectTransform>();
placeholderRectTransform.anchorMin = Vector2.zero;
placeholderRectTransform.anchorMax = Vector2.one;
placeholderRectTransform.sizeDelta = Vector2.zero;
placeholderRectTransform.offsetMin = new Vector2(0, 0);
placeholderRectTransform.offsetMax = new Vector2(0, 0);
inputField.textViewport = textAreaRectTransform;
inputField.textComponent = text;
inputField.placeholder = placeholder;
inputField.fontAsset = text.font;
return root;
}
public static GameObject CreateDropdown(Resources resources)
{
GameObject root = CreateUIElementRoot("Dropdown", s_ThickElementSize);
GameObject label = CreateUIObject("Label", root);
GameObject arrow = CreateUIObject("Arrow", root);
GameObject template = CreateUIObject("Template", root);
GameObject viewport = CreateUIObject("Viewport", template);
GameObject content = CreateUIObject("Content", viewport);
GameObject item = CreateUIObject("Item", content);
GameObject itemBackground = CreateUIObject("Item Background", item);
GameObject itemCheckmark = CreateUIObject("Item Checkmark", item);
GameObject itemLabel = CreateUIObject("Item Label", item);
// Sub controls.
GameObject scrollbar = CreateScrollbar(resources);
scrollbar.name = "Scrollbar";
SetParentAndAlign(scrollbar, template);
Scrollbar scrollbarScrollbar = scrollbar.GetComponent<Scrollbar>();
scrollbarScrollbar.SetDirection(Scrollbar.Direction.BottomToTop, true);
RectTransform vScrollbarRT = scrollbar.GetComponent<RectTransform>();
vScrollbarRT.anchorMin = Vector2.right;
vScrollbarRT.anchorMax = Vector2.one;
vScrollbarRT.pivot = Vector2.one;
vScrollbarRT.sizeDelta = new Vector2(vScrollbarRT.sizeDelta.x, 0);
// Setup item UI components.
TextMeshProUGUI itemLabelText = itemLabel.AddComponent<TextMeshProUGUI>();
SetDefaultTextValues(itemLabelText);
itemLabelText.alignment = TextAlignmentOptions.Left;
Image itemBackgroundImage = itemBackground.AddComponent<Image>();
itemBackgroundImage.color = new Color32(245, 245, 245, 255);
Image itemCheckmarkImage = itemCheckmark.AddComponent<Image>();
itemCheckmarkImage.sprite = resources.checkmark;
Toggle itemToggle = item.AddComponent<Toggle>();
itemToggle.targetGraphic = itemBackgroundImage;
itemToggle.graphic = itemCheckmarkImage;
itemToggle.isOn = true;
// Setup template UI components.
Image templateImage = template.AddComponent<Image>();
templateImage.sprite = resources.standard;
templateImage.type = Image.Type.Sliced;
ScrollRect templateScrollRect = template.AddComponent<ScrollRect>();
templateScrollRect.content = (RectTransform)content.transform;
templateScrollRect.viewport = (RectTransform)viewport.transform;
templateScrollRect.horizontal = false;
templateScrollRect.movementType = ScrollRect.MovementType.Clamped;
templateScrollRect.verticalScrollbar = scrollbarScrollbar;
templateScrollRect.verticalScrollbarVisibility = ScrollRect.ScrollbarVisibility.AutoHideAndExpandViewport;
templateScrollRect.verticalScrollbarSpacing = -3;
Mask scrollRectMask = viewport.AddComponent<Mask>();
scrollRectMask.showMaskGraphic = false;
Image viewportImage = viewport.AddComponent<Image>();
viewportImage.sprite = resources.mask;
viewportImage.type = Image.Type.Sliced;
// Setup dropdown UI components.
TextMeshProUGUI labelText = label.AddComponent<TextMeshProUGUI>();
SetDefaultTextValues(labelText);
labelText.alignment = TextAlignmentOptions.Left;
Image arrowImage = arrow.AddComponent<Image>();
arrowImage.sprite = resources.dropdown;
Image backgroundImage = root.AddComponent<Image>();
backgroundImage.sprite = resources.standard;
backgroundImage.color = s_DefaultSelectableColor;
backgroundImage.type = Image.Type.Sliced;
TMP_Dropdown dropdown = root.AddComponent<TMP_Dropdown>();
dropdown.targetGraphic = backgroundImage;
SetDefaultColorTransitionValues(dropdown);
dropdown.template = template.GetComponent<RectTransform>();
dropdown.captionText = labelText;
dropdown.itemText = itemLabelText;
// Setting default Item list.
itemLabelText.text = "Option A";
dropdown.options.Add(new TMP_Dropdown.OptionData {text = "Option A" });
dropdown.options.Add(new TMP_Dropdown.OptionData {text = "Option B" });
dropdown.options.Add(new TMP_Dropdown.OptionData {text = "Option C" });
dropdown.RefreshShownValue();
// Set up RectTransforms.
RectTransform labelRT = label.GetComponent<RectTransform>();
labelRT.anchorMin = Vector2.zero;
labelRT.anchorMax = Vector2.one;
labelRT.offsetMin = new Vector2(10, 6);
labelRT.offsetMax = new Vector2(-25, -7);
RectTransform arrowRT = arrow.GetComponent<RectTransform>();
arrowRT.anchorMin = new Vector2(1, 0.5f);
arrowRT.anchorMax = new Vector2(1, 0.5f);
arrowRT.sizeDelta = new Vector2(20, 20);
arrowRT.anchoredPosition = new Vector2(-15, 0);
RectTransform templateRT = template.GetComponent<RectTransform>();
templateRT.anchorMin = new Vector2(0, 0);
templateRT.anchorMax = new Vector2(1, 0);
templateRT.pivot = new Vector2(0.5f, 1);
templateRT.anchoredPosition = new Vector2(0, 2);
templateRT.sizeDelta = new Vector2(0, 150);
RectTransform viewportRT = viewport.GetComponent<RectTransform>();
viewportRT.anchorMin = new Vector2(0, 0);
viewportRT.anchorMax = new Vector2(1, 1);
viewportRT.sizeDelta = new Vector2(-18, 0);
viewportRT.pivot = new Vector2(0, 1);
RectTransform contentRT = content.GetComponent<RectTransform>();
contentRT.anchorMin = new Vector2(0f, 1);
contentRT.anchorMax = new Vector2(1f, 1);
contentRT.pivot = new Vector2(0.5f, 1);
contentRT.anchoredPosition = new Vector2(0, 0);
contentRT.sizeDelta = new Vector2(0, 28);
RectTransform itemRT = item.GetComponent<RectTransform>();
itemRT.anchorMin = new Vector2(0, 0.5f);
itemRT.anchorMax = new Vector2(1, 0.5f);
itemRT.sizeDelta = new Vector2(0, 20);
RectTransform itemBackgroundRT = itemBackground.GetComponent<RectTransform>();
itemBackgroundRT.anchorMin = Vector2.zero;
itemBackgroundRT.anchorMax = Vector2.one;
itemBackgroundRT.sizeDelta = Vector2.zero;
RectTransform itemCheckmarkRT = itemCheckmark.GetComponent<RectTransform>();
itemCheckmarkRT.anchorMin = new Vector2(0, 0.5f);
itemCheckmarkRT.anchorMax = new Vector2(0, 0.5f);
itemCheckmarkRT.sizeDelta = new Vector2(20, 20);
itemCheckmarkRT.anchoredPosition = new Vector2(10, 0);
RectTransform itemLabelRT = itemLabel.GetComponent<RectTransform>();
itemLabelRT.anchorMin = Vector2.zero;
itemLabelRT.anchorMax = Vector2.one;
itemLabelRT.offsetMin = new Vector2(20, 1);
itemLabelRT.offsetMax = new Vector2(-10, -2);
template.SetActive(false);
return root;
}
}
}

View File

@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 094d5dbc4aa34bc40baa80a884b5ff3c
timeCreated: 1446378357
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c0a28a6dcbb780342a6fc7a12c3d160e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: a7ec9e7ad8b847b7ae4510af83c5d868, type: 3}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,188 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.TextCore.LowLevel;
namespace TMPro
{
internal class TMP_DynamicFontAssetUtilities
{
private static TMP_DynamicFontAssetUtilities s_Instance = new TMP_DynamicFontAssetUtilities();
private Dictionary<ulong, FontReference> s_SystemFontLookup;
private string[] s_SystemFontPaths;
private uint s_RegularStyleNameHashCode = 1291372090;
public struct FontReference
{
public string familyName;
public string styleName;
public int faceIndex;
public string filePath;
public ulong hashCode;
/// <summary>
/// Constructor for new FontReference
/// </summary>
/// <param name="faceNameAndStyle">String that combines the family name with style name</param>
/// <param name="index">Index of the font face and style.</param>
public FontReference(string fontFilePath, string faceNameAndStyle, int index)
{
familyName = null;
styleName = null;
faceIndex = index;
uint familyNameHashCode = 0;
uint styleNameHashCode = 0;
filePath = fontFilePath;
int length = faceNameAndStyle.Length;
char[] conversionArray = new char[length];
int readingFlag = 0;
int writingIndex = 0;
for (int i = 0; i < length; i++)
{
char c = faceNameAndStyle[i];
// Read family name
if (readingFlag == 0)
{
bool isSeparator = i + 2 < length && c == ' ' && faceNameAndStyle[i + 1] == '-' && faceNameAndStyle[i + 2] == ' ';
if (isSeparator)
{
readingFlag = 1;
this.familyName = new string(conversionArray, 0, writingIndex);
i += 2;
writingIndex = 0;
continue;
}
familyNameHashCode = (familyNameHashCode << 5) + familyNameHashCode ^ TMP_TextUtilities.ToUpperFast(c);
conversionArray[writingIndex++] = c;
continue;
}
// Read style name
if (readingFlag == 1)
{
styleNameHashCode = (styleNameHashCode << 5) + styleNameHashCode ^ TMP_TextUtilities.ToUpperFast(c);
conversionArray[writingIndex++] = c;
if (i + 1 == length)
this.styleName = new string(conversionArray, 0, writingIndex);
}
}
hashCode = (ulong)styleNameHashCode << 32 | familyNameHashCode;
}
}
void InitializeSystemFontReferenceCache()
{
if (s_SystemFontLookup == null)
s_SystemFontLookup = new Dictionary<ulong, FontReference>();
else
s_SystemFontLookup.Clear();
if (s_SystemFontPaths == null)
s_SystemFontPaths = Font.GetPathsToOSFonts();
for (int i = 0; i < s_SystemFontPaths.Length; i++)
{
// Load font at the given path
FontEngineError error = FontEngine.LoadFontFace(s_SystemFontPaths[i]);
if (error != FontEngineError.Success)
{
Debug.LogWarning("Error [" + error + "] trying to load the font at path [" + s_SystemFontPaths[i] + "].");
continue;
}
// Get font faces and styles for this font
string[] fontFaces = FontEngine.GetFontFaces();
// Iterate over each font face
for (int j = 0; j < fontFaces.Length; j++)
{
FontReference fontRef = new FontReference(s_SystemFontPaths[i], fontFaces[j], j);
if (s_SystemFontLookup.ContainsKey(fontRef.hashCode))
{
//Debug.Log("<color=#FFFF80>[" + i + "]</color> Family Name <color=#FFFF80>[" + fontRef.familyName + "]</color> Style Name <color=#FFFF80>[" + fontRef.styleName + "]</color> Index [" + fontRef.faceIndex + "] HashCode [" + fontRef.hashCode + "] Path [" + fontRef.filePath + "].");
continue;
}
// Add font reference to lookup dictionary
s_SystemFontLookup.Add(fontRef.hashCode, fontRef);
Debug.Log("[" + i + "] Family Name [" + fontRef.familyName + "] Style Name [" + fontRef.styleName + "] Index [" + fontRef.faceIndex + "] HashCode [" + fontRef.hashCode + "] Path [" + fontRef.filePath + "].");
}
// Unload current font face.
FontEngine.UnloadFontFace();
}
}
/// <summary>
///
/// </summary>
/// <param name="familyName"></param>
/// <param name="fontRef"></param>
/// <returns></returns>
public static bool TryGetSystemFontReference(string familyName, out FontReference fontRef)
{
return s_Instance.TryGetSystemFontReferenceInternal(familyName, null, out fontRef);
}
/// <summary>
///
/// </summary>
/// <param name="familyName"></param>
/// <param name="styleName"></param>
/// <param name="fontRef"></param>
/// <returns></returns>
public static bool TryGetSystemFontReference(string familyName, string styleName, out FontReference fontRef)
{
return s_Instance.TryGetSystemFontReferenceInternal(familyName, styleName, out fontRef);
}
bool TryGetSystemFontReferenceInternal(string familyName, string styleName, out FontReference fontRef)
{
if (s_SystemFontLookup == null)
InitializeSystemFontReferenceCache();
fontRef = new FontReference();
// Compute family name hash code
uint familyNameHashCode = TMP_TextUtilities.GetHashCodeCaseInSensitive(familyName);
uint styleNameHashCode = string.IsNullOrEmpty(styleName) ? s_RegularStyleNameHashCode : TMP_TextUtilities.GetHashCodeCaseInSensitive(styleName);
ulong key = (ulong)styleNameHashCode << 32 | familyNameHashCode;
// Lookup font reference
if (s_SystemFontLookup.ContainsKey(key))
{
fontRef = s_SystemFontLookup[key];
return true;
}
// Return if specified family and style name is not found.
if (styleNameHashCode != s_RegularStyleNameHashCode)
return false;
// Return first potential reference for the given family name
foreach (KeyValuePair<ulong, FontReference> pair in s_SystemFontLookup)
{
if (pair.Value.familyName == familyName)
{
fontRef = pair.Value;
return true;
}
}
return false;
}
}
}

View File

@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: aaf9006568d76504f982305b517fb490
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,458 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.TextCore.Text;
namespace TMPro
{
/// <summary>
/// Class that contains the basic information about the font.
/// </summary>
[Serializable]
public class FaceInfo_Legacy
{
public string Name;
public float PointSize;
public float Scale;
public int CharacterCount;
public float LineHeight;
public float Baseline;
public float Ascender;
public float CapHeight;
public float Descender;
public float CenterLine;
public float SuperscriptOffset;
public float SubscriptOffset;
public float SubSize;
public float Underline;
public float UnderlineThickness;
public float strikethrough;
public float strikethroughThickness;
public float TabWidth;
public float Padding;
public float AtlasWidth;
public float AtlasHeight;
}
// Class which contains the Glyph Info / Character definition for each character contained in the font asset.
[Serializable]
public class TMP_Glyph : TMP_TextElement_Legacy
{
/// <summary>
/// Function to create a deep copy of a GlyphInfo.
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public static TMP_Glyph Clone(TMP_Glyph source)
{
TMP_Glyph copy = new TMP_Glyph();
copy.id = source.id;
copy.x = source.x;
copy.y = source.y;
copy.width = source.width;
copy.height = source.height;
copy.xOffset = source.xOffset;
copy.yOffset = source.yOffset;
copy.xAdvance = source.xAdvance;
copy.scale = source.scale;
return copy;
}
}
// Structure which holds the font creation settings
[Serializable]
public struct FontAssetCreationSettings
{
public string sourceFontFileName;
public string sourceFontFileGUID;
public int faceIndex;
public int pointSizeSamplingMode;
public int pointSize;
public int padding;
public int paddingMode;
public int packingMode;
public int atlasWidth;
public int atlasHeight;
public int characterSetSelectionMode;
public string characterSequence;
public string referencedFontAssetGUID;
public string referencedTextAssetGUID;
public int fontStyle;
public float fontStyleModifier;
public int renderMode;
public bool includeFontFeatures;
internal FontAssetCreationSettings(string sourceFontFileGUID, int pointSize, int pointSizeSamplingMode, int padding, int packingMode, int atlasWidth, int atlasHeight, int characterSelectionMode, string characterSet, int renderMode)
{
this.sourceFontFileName = string.Empty;
this.sourceFontFileGUID = sourceFontFileGUID;
this.faceIndex = 0;
this.pointSize = pointSize;
this.pointSizeSamplingMode = pointSizeSamplingMode;
this.padding = padding;
this.paddingMode = 2;
this.packingMode = packingMode;
this.atlasWidth = atlasWidth;
this.atlasHeight = atlasHeight;
this.characterSequence = characterSet;
this.characterSetSelectionMode = characterSelectionMode;
this.renderMode = renderMode;
this.referencedFontAssetGUID = string.Empty;
this.referencedTextAssetGUID = string.Empty;
this.fontStyle = 0;
this.fontStyleModifier = 0;
this.includeFontFeatures = false;
}
}
/// <summary>
/// Contains the font assets for the regular and italic styles associated with a given font weight.
/// </summary>
[Serializable]
public struct TMP_FontWeightPair
{
public FontAsset regularTypeface;
public FontAsset italicTypeface;
}
public struct KerningPairKey
{
public uint ascii_Left;
public uint ascii_Right;
public uint key;
public KerningPairKey(uint ascii_left, uint ascii_right)
{
ascii_Left = ascii_left;
ascii_Right = ascii_right;
key = (ascii_right << 16) + ascii_left;
}
}
/// <summary>
/// Positional adjustments of a glyph
/// </summary>
[Serializable]
public struct GlyphValueRecord_Legacy
{
public float xPlacement;
public float yPlacement;
public float xAdvance;
public float yAdvance;
internal GlyphValueRecord_Legacy(UnityEngine.TextCore.LowLevel.GlyphValueRecord valueRecord)
{
this.xPlacement = valueRecord.xPlacement;
this.yPlacement = valueRecord.yPlacement;
this.xAdvance = valueRecord.xAdvance;
this.yAdvance = valueRecord.yAdvance;
}
public static GlyphValueRecord_Legacy operator +(GlyphValueRecord_Legacy a, GlyphValueRecord_Legacy b)
{
GlyphValueRecord_Legacy c;
c.xPlacement = a.xPlacement + b.xPlacement;
c.yPlacement = a.yPlacement + b.yPlacement;
c.xAdvance = a.xAdvance + b.xAdvance;
c.yAdvance = a.yAdvance + b.yAdvance;
return c;
}
}
[Serializable]
public class KerningPair
{
/// <summary>
/// The first glyph part of a kerning pair.
/// </summary>
public uint firstGlyph
{
get { return m_FirstGlyph; }
set { m_FirstGlyph = value; }
}
[FormerlySerializedAs("AscII_Left")]
[SerializeField]
private uint m_FirstGlyph;
/// <summary>
/// The positional adjustment of the first glyph.
/// </summary>
public GlyphValueRecord_Legacy firstGlyphAdjustments
{
get { return m_FirstGlyphAdjustments; }
}
[SerializeField]
private GlyphValueRecord_Legacy m_FirstGlyphAdjustments;
/// <summary>
/// The second glyph part of a kerning pair.
/// </summary>
public uint secondGlyph
{
get { return m_SecondGlyph; }
set { m_SecondGlyph = value; }
}
[FormerlySerializedAs("AscII_Right")]
[SerializeField]
private uint m_SecondGlyph;
/// <summary>
/// The positional adjustment of the second glyph.
/// </summary>
public GlyphValueRecord_Legacy secondGlyphAdjustments
{
get { return m_SecondGlyphAdjustments; }
}
[SerializeField]
private GlyphValueRecord_Legacy m_SecondGlyphAdjustments;
[FormerlySerializedAs("XadvanceOffset")]
public float xOffset;
internal static KerningPair empty = new KerningPair(0, new GlyphValueRecord_Legacy(), 0, new GlyphValueRecord_Legacy());
/// <summary>
/// Determines if the Character Spacing property of the text object will affect the kerning pair.
/// This is mostly relevant when using Diacritical marks to prevent Character Spacing from altering the spacing.
/// </summary>
public bool ignoreSpacingAdjustments
{
get { return m_IgnoreSpacingAdjustments; }
}
[SerializeField]
private bool m_IgnoreSpacingAdjustments = false;
public KerningPair()
{
m_FirstGlyph = 0;
m_FirstGlyphAdjustments = new GlyphValueRecord_Legacy();
m_SecondGlyph = 0;
m_SecondGlyphAdjustments = new GlyphValueRecord_Legacy();
}
public KerningPair(uint left, uint right, float offset)
{
firstGlyph = left;
m_SecondGlyph = right;
xOffset = offset;
}
public KerningPair(uint firstGlyph, GlyphValueRecord_Legacy firstGlyphAdjustments, uint secondGlyph, GlyphValueRecord_Legacy secondGlyphAdjustments)
{
m_FirstGlyph = firstGlyph;
m_FirstGlyphAdjustments = firstGlyphAdjustments;
m_SecondGlyph = secondGlyph;
m_SecondGlyphAdjustments = secondGlyphAdjustments;
}
internal void ConvertLegacyKerningData()
{
m_FirstGlyphAdjustments.xAdvance = xOffset;
//xOffset = 0;
}
}
[Serializable]
public class KerningTable
{
public List<KerningPair> kerningPairs;
public KerningTable()
{
kerningPairs = new List<KerningPair>();
}
public void AddKerningPair()
{
if (kerningPairs.Count == 0)
{
kerningPairs.Add(new KerningPair(0, 0, 0));
}
else
{
uint left = kerningPairs.Last().firstGlyph;
uint right = kerningPairs.Last().secondGlyph;
float xoffset = kerningPairs.Last().xOffset;
kerningPairs.Add(new KerningPair(left, right, xoffset));
}
}
/// <summary>
/// Add Kerning Pair
/// </summary>
/// <param name="first">First glyph</param>
/// <param name="second">Second glyph</param>
/// <param name="offset">xAdvance value</param>
/// <returns></returns>
public int AddKerningPair(uint first, uint second, float offset)
{
int index = kerningPairs.FindIndex(item => item.firstGlyph == first && item.secondGlyph == second);
if (index == -1)
{
kerningPairs.Add(new KerningPair(first, second, offset));
return 0;
}
// Return -1 if Kerning Pair already exists.
return -1;
}
/// <summary>
/// Add Glyph pair adjustment record
/// </summary>
/// <param name="firstGlyph">The first glyph</param>
/// <param name="firstGlyphAdjustments">Adjustment record for the first glyph</param>
/// <param name="secondGlyph">The second glyph</param>
/// <param name="secondGlyphAdjustments">Adjustment record for the second glyph</param>
/// <returns></returns>
public int AddGlyphPairAdjustmentRecord(uint first, GlyphValueRecord_Legacy firstAdjustments, uint second, GlyphValueRecord_Legacy secondAdjustments)
{
int index = kerningPairs.FindIndex(item => item.firstGlyph == first && item.secondGlyph == second);
if (index == -1)
{
kerningPairs.Add(new KerningPair(first, firstAdjustments, second, secondAdjustments));
return 0;
}
// Return -1 if Kerning Pair already exists.
return -1;
}
public void RemoveKerningPair(int left, int right)
{
int index = kerningPairs.FindIndex(item => item.firstGlyph == left && item.secondGlyph == right);
if (index != -1)
kerningPairs.RemoveAt(index);
}
public void RemoveKerningPair(int index)
{
kerningPairs.RemoveAt(index);
}
public void SortKerningPairs()
{
// Sort List of Kerning Info
if (kerningPairs.Count > 0)
kerningPairs = kerningPairs.OrderBy(s => s.firstGlyph).ThenBy(s => s.secondGlyph).ToList();
}
}
public static class TMP_FontUtilities
{
private static List<int> k_searchedFontAssets;
/// <summary>
/// Search through the given font and its fallbacks for the specified character.
/// </summary>
/// <param name="font">The font asset to search for the given character.</param>
/// <param name="unicode">The character to find.</param>
/// <param name="character">out parameter containing the glyph for the specified character (if found).</param>
/// <returns></returns>
public static FontAsset SearchForCharacter(FontAsset font, uint unicode, out Character character)
{
if (k_searchedFontAssets == null)
k_searchedFontAssets = new List<int>();
k_searchedFontAssets.Clear();
return SearchForCharacterInternal(font, unicode, out character);
}
/// <summary>
/// Search through the given list of fonts and their possible fallbacks for the specified character.
/// </summary>
/// <param name="fonts"></param>
/// <param name="unicode"></param>
/// <param name="character"></param>
/// <returns></returns>
public static FontAsset SearchForCharacter(List<FontAsset> fonts, uint unicode, out Character character)
{
return SearchForCharacterInternal(fonts, unicode, out character);
}
private static FontAsset SearchForCharacterInternal(FontAsset font, uint unicode, out Character character)
{
character = null;
if (font == null) return null;
if (font.characterLookupTable.TryGetValue(unicode, out character))
{
return font;
}
else if (font.fallbackFontAssetTable != null && font.fallbackFontAssetTable.Count > 0)
{
for (int i = 0; i < font.fallbackFontAssetTable.Count && character == null; i++)
{
FontAsset temp = font.fallbackFontAssetTable[i];
if (temp == null) continue;
int id = temp.GetInstanceID();
// Skip over the fallback font asset in the event it is null or if already searched.
if (k_searchedFontAssets.Contains(id)) continue;
// Add to list of font assets already searched.
k_searchedFontAssets.Add(id);
temp = SearchForCharacterInternal(temp, unicode, out character);
if (temp != null)
return temp;
}
}
return null;
}
private static FontAsset SearchForCharacterInternal(List<FontAsset> fonts, uint unicode, out Character character)
{
character = null;
if (fonts != null && fonts.Count > 0)
{
for (int i = 0; i < fonts.Count; i++)
{
FontAsset fontAsset = SearchForCharacterInternal(fonts[i], unicode, out character);
if (fontAsset != null)
return fontAsset;
}
}
return null;
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 7c5c60f80f1a9814eb7e246f2e88afd4
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

Some files were not shown because too many files have changed in this diff Show More