#define TMP_PRESENT using System; using System.Text; using System.Collections.Generic; using Unity.Profiling; using UnityEngine; using UnityEngine.Serialization; using UnityEngine.TextCore; using UnityEngine.TextCore.LowLevel; using UnityEngine.UI; namespace TMPro { public interface ITextElement { Material sharedMaterial { get; } void Rebuild(CanvasUpdate update); int GetInstanceID(); } public enum TextAlignmentOptions { TopLeft = HorizontalAlignmentOptions.Left | VerticalAlignmentOptions.Top, Top = HorizontalAlignmentOptions.Center | VerticalAlignmentOptions.Top, TopRight = HorizontalAlignmentOptions.Right | VerticalAlignmentOptions.Top, TopJustified = HorizontalAlignmentOptions.Justified | VerticalAlignmentOptions.Top, TopFlush = HorizontalAlignmentOptions.Flush | VerticalAlignmentOptions.Top, TopGeoAligned = HorizontalAlignmentOptions.Geometry | VerticalAlignmentOptions.Top, Left = HorizontalAlignmentOptions.Left | VerticalAlignmentOptions.Middle, Center = HorizontalAlignmentOptions.Center | VerticalAlignmentOptions.Middle, Right = HorizontalAlignmentOptions.Right | VerticalAlignmentOptions.Middle, Justified = HorizontalAlignmentOptions.Justified | VerticalAlignmentOptions.Middle, Flush = HorizontalAlignmentOptions.Flush | VerticalAlignmentOptions.Middle, CenterGeoAligned = HorizontalAlignmentOptions.Geometry | VerticalAlignmentOptions.Middle, BottomLeft = HorizontalAlignmentOptions.Left | VerticalAlignmentOptions.Bottom, Bottom = HorizontalAlignmentOptions.Center | VerticalAlignmentOptions.Bottom, BottomRight = HorizontalAlignmentOptions.Right | VerticalAlignmentOptions.Bottom, BottomJustified = HorizontalAlignmentOptions.Justified | VerticalAlignmentOptions.Bottom, BottomFlush = HorizontalAlignmentOptions.Flush | VerticalAlignmentOptions.Bottom, BottomGeoAligned = HorizontalAlignmentOptions.Geometry | VerticalAlignmentOptions.Bottom, BaselineLeft = HorizontalAlignmentOptions.Left | VerticalAlignmentOptions.Baseline, Baseline = HorizontalAlignmentOptions.Center | VerticalAlignmentOptions.Baseline, BaselineRight = HorizontalAlignmentOptions.Right | VerticalAlignmentOptions.Baseline, BaselineJustified = HorizontalAlignmentOptions.Justified | VerticalAlignmentOptions.Baseline, BaselineFlush = HorizontalAlignmentOptions.Flush | VerticalAlignmentOptions.Baseline, BaselineGeoAligned = HorizontalAlignmentOptions.Geometry | VerticalAlignmentOptions.Baseline, MidlineLeft = HorizontalAlignmentOptions.Left | VerticalAlignmentOptions.Geometry, Midline = HorizontalAlignmentOptions.Center | VerticalAlignmentOptions.Geometry, MidlineRight = HorizontalAlignmentOptions.Right | VerticalAlignmentOptions.Geometry, MidlineJustified = HorizontalAlignmentOptions.Justified | VerticalAlignmentOptions.Geometry, MidlineFlush = HorizontalAlignmentOptions.Flush | VerticalAlignmentOptions.Geometry, MidlineGeoAligned = HorizontalAlignmentOptions.Geometry | VerticalAlignmentOptions.Geometry, CaplineLeft = HorizontalAlignmentOptions.Left | VerticalAlignmentOptions.Capline, Capline = HorizontalAlignmentOptions.Center | VerticalAlignmentOptions.Capline, CaplineRight = HorizontalAlignmentOptions.Right | VerticalAlignmentOptions.Capline, CaplineJustified = HorizontalAlignmentOptions.Justified | VerticalAlignmentOptions.Capline, CaplineFlush = HorizontalAlignmentOptions.Flush | VerticalAlignmentOptions.Capline, CaplineGeoAligned = HorizontalAlignmentOptions.Geometry | VerticalAlignmentOptions.Capline, Converted = 0xFFFF }; /// /// Horizontal text alignment options. /// public enum HorizontalAlignmentOptions { Left = 0x1, Center = 0x2, Right = 0x4, Justified = 0x8, Flush = 0x10, Geometry = 0x20 } /// /// Vertical text alignment options. /// public enum VerticalAlignmentOptions { Top = 0x100, Middle = 0x200, Bottom = 0x400, Baseline = 0x800, Geometry = 0x1000, Capline = 0x2000, } /// /// Flags controlling what vertex data gets pushed to the mesh. /// public enum TextRenderFlags { DontRender = 0x0, Render = 0xFF }; public enum TMP_TextElementType { Character, Sprite }; public enum MaskingTypes { MaskOff = 0, MaskHard = 1, MaskSoft = 2 }; //, MaskTex = 4 }; public enum TextOverflowModes { Overflow = 0, Ellipsis = 1, Masking = 2, Truncate = 3, ScrollRect = 4, Page = 5, Linked = 6 }; public enum TextWrappingModes { NoWrap = 0, Normal = 1, PreserveWhitespace = 2, PreserveWhitespaceNoWrap = 3 }; public enum MaskingOffsetMode { Percentage = 0, Pixel = 1 }; public enum TextureMappingOptions { Character = 0, Line = 1, Paragraph = 2, MatchAspect = 3 }; [Flags] public enum FontStyles { Normal = 0x0, Bold = 0x1, Italic = 0x2, Underline = 0x4, LowerCase = 0x8, UpperCase = 0x10, SmallCaps = 0x20, Strikethrough = 0x40, Superscript = 0x80, Subscript = 0x100, Highlight = 0x200 }; public enum FontWeight { Thin = 100, ExtraLight = 200, Light = 300, Regular = 400, Medium = 500, SemiBold = 600, Bold = 700, Heavy = 800, Black = 900 }; /// /// Base class which contains common properties and functions shared between the TextMeshPro and TextMeshProUGUI component. /// public abstract class TMP_Text : MaskableGraphic { /// /// A string containing the text to be displayed. /// public virtual string text { get { if (m_IsTextBackingStringDirty) return InternalTextBackingArrayToString(); return m_text; } set { if (m_IsTextBackingStringDirty == false && m_text != null && value != null && m_text.Length == value.Length && m_text == value) return; m_IsTextBackingStringDirty = false; m_text = value; m_inputSource = TextInputSources.TextString; m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] [TextArea(5, 10)] protected string m_text; /// /// /// private bool m_IsTextBackingStringDirty; /// /// The ITextPreprocessor component referenced by the text object (if any) /// public ITextPreprocessor textPreprocessor { get { return m_TextPreprocessor; } set { m_TextPreprocessor = value; } } [SerializeField] protected ITextPreprocessor m_TextPreprocessor; /// /// /// public bool isRightToLeftText { get { return m_isRightToLeft; } set { if (m_isRightToLeft == value) return; m_isRightToLeft = value; m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected bool m_isRightToLeft = false; /// /// The Font Asset to be assigned to this text object. /// public TMP_FontAsset font { get { return m_fontAsset; } set { if (m_fontAsset == value) return; m_fontAsset = value; LoadFontAsset(); m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected TMP_FontAsset m_fontAsset; protected TMP_FontAsset m_currentFontAsset; protected bool m_isSDFShader; /// /// The material to be assigned to this text object. /// public virtual Material fontSharedMaterial { get { return m_sharedMaterial; } set { if (m_sharedMaterial == value) return; SetSharedMaterial(value); m_havePropertiesChanged = true; SetVerticesDirty(); SetMaterialDirty(); } } [SerializeField] protected Material m_sharedMaterial; protected Material m_currentMaterial; protected static MaterialReference[] m_materialReferences = new MaterialReference[4]; protected static Dictionary m_materialReferenceIndexLookup = new Dictionary(); protected static TMP_TextProcessingStack m_materialReferenceStack = new TMP_TextProcessingStack(new MaterialReference[16]); protected int m_currentMaterialIndex; /// /// An array containing the materials used by the text object. /// public virtual Material[] fontSharedMaterials { get { return GetSharedMaterials(); } set { SetSharedMaterials(value); m_havePropertiesChanged = true; SetVerticesDirty(); SetMaterialDirty(); } } [SerializeField] protected Material[] m_fontSharedMaterials; /// /// The material to be assigned to this text object. An instance of the material will be assigned to the object's renderer. /// public Material fontMaterial { // Return an Instance of the current material. get { return GetMaterial(m_sharedMaterial); } // Assign new font material set { if (m_sharedMaterial != null && m_sharedMaterial.GetInstanceID() == value.GetInstanceID()) return; m_sharedMaterial = value; m_padding = GetPaddingForMaterial(); m_havePropertiesChanged = true; SetVerticesDirty(); SetMaterialDirty(); } } [SerializeField] protected Material m_fontMaterial; /// /// The materials to be assigned to this text object. An instance of the materials will be assigned. /// public virtual Material[] fontMaterials { get { return GetMaterials(m_fontSharedMaterials); } set { SetSharedMaterials(value); m_havePropertiesChanged = true; SetVerticesDirty(); SetMaterialDirty(); } } [SerializeField] protected Material[] m_fontMaterials; protected bool m_isMaterialDirty; /// /// This is the default vertex color assigned to each vertices. Color tags will override vertex colors unless the overrideColorTags is set. /// public override Color color { get { return m_fontColor; } set { if (m_fontColor == value) return; m_havePropertiesChanged = true; m_fontColor = value; SetVerticesDirty(); } } //[UnityEngine.Serialization.FormerlySerializedAs("m_fontColor")] // Required for backwards compatibility with pre-Unity 4.6 releases. [SerializeField] protected Color32 m_fontColor32 = Color.white; [SerializeField] protected Color m_fontColor = Color.white; protected static Color32 s_colorWhite = new Color32(255, 255, 255, 255); protected Color32 m_underlineColor = s_colorWhite; protected Color32 m_strikethroughColor = s_colorWhite; internal HighlightState m_HighlightState = new HighlightState(s_colorWhite, TMP_Offset.zero); internal bool m_ConvertToLinearSpace; /// /// Sets the vertex color alpha value. /// public float alpha { get { return m_fontColor.a; } set { if (m_fontColor.a == value) return; m_fontColor.a = value; m_havePropertiesChanged = true; SetVerticesDirty(); } } /// /// Determines if Vertex Color Gradient should be used /// /// true if enable vertex gradient; otherwise, false. public bool enableVertexGradient { get { return m_enableVertexGradient; } set { if (m_enableVertexGradient == value) return; m_havePropertiesChanged = true; m_enableVertexGradient = value; SetVerticesDirty(); } } [SerializeField] protected bool m_enableVertexGradient; [SerializeField] protected ColorMode m_colorMode = ColorMode.FourCornersGradient; /// /// Sets the vertex colors for each of the 4 vertices of the character quads. /// /// The color gradient. public VertexGradient colorGradient { get { return m_fontColorGradient; } set { m_havePropertiesChanged = true; m_fontColorGradient = value; SetVerticesDirty(); } } [SerializeField] protected VertexGradient m_fontColorGradient = new VertexGradient(Color.white); /// /// Set the vertex colors of the 4 vertices of each character quads. /// public TMP_ColorGradient colorGradientPreset { get { return m_fontColorGradientPreset; } set { m_havePropertiesChanged = true; m_fontColorGradientPreset = value; SetVerticesDirty(); } } [SerializeField] protected TMP_ColorGradient m_fontColorGradientPreset; /// /// Sprite Asset used by the text object. /// public TMP_SpriteAsset spriteAsset { get { return m_spriteAsset; } set { m_spriteAsset = value; m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected TMP_SpriteAsset m_spriteAsset; /// /// Determines whether or not the sprite color is multiplies by the vertex color of the text. /// public bool tintAllSprites { get { return m_tintAllSprites; } set { if (m_tintAllSprites == value) return; m_tintAllSprites = value; m_havePropertiesChanged = true; SetVerticesDirty(); } } [SerializeField] protected bool m_tintAllSprites; protected bool m_tintSprite; protected Color32 m_spriteColor; /// /// Style sheet used by the text object. /// public TMP_StyleSheet styleSheet { get { return m_StyleSheet; } set { m_StyleSheet = value; m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected TMP_StyleSheet m_StyleSheet; /// /// /// public TMP_Style textStyle { get { m_TextStyle = GetStyle(m_TextStyleHashCode); if (m_TextStyle == null) { m_TextStyle = TMP_Style.NormalStyle; m_TextStyleHashCode = m_TextStyle.hashCode; } return m_TextStyle; } set { m_TextStyle = value; m_TextStyleHashCode = m_TextStyle.hashCode; m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } internal TMP_Style m_TextStyle; [SerializeField] protected int m_TextStyleHashCode; /// /// This overrides the color tags forcing the vertex colors to be the default font color. /// public bool overrideColorTags { get { return m_overrideHtmlColors; } set { if (m_overrideHtmlColors == value) return; m_havePropertiesChanged = true; m_overrideHtmlColors = value; SetVerticesDirty(); } } [SerializeField] protected bool m_overrideHtmlColors = false; /// /// Sets the color of the _FaceColor property of the assigned material. Changing face color will result in an instance of the material. /// public Color32 faceColor { get { if (m_sharedMaterial == null) return m_faceColor; m_faceColor = m_sharedMaterial.GetColor(ShaderUtilities.ID_FaceColor); return m_faceColor; } set { if (m_faceColor.Compare(value)) return; SetFaceColor(value); m_havePropertiesChanged = true; m_faceColor = value; SetVerticesDirty(); SetMaterialDirty(); } } [SerializeField] protected Color32 m_faceColor = Color.white; /// /// Sets the color of the _OutlineColor property of the assigned material. Changing outline color will result in an instance of the material. /// public Color32 outlineColor { get { if (m_sharedMaterial == null) return m_outlineColor; m_outlineColor = m_sharedMaterial.GetColor(ShaderUtilities.ID_OutlineColor); return m_outlineColor; } set { if (m_outlineColor.Compare(value)) return; SetOutlineColor(value); m_havePropertiesChanged = true; m_outlineColor = value; SetVerticesDirty(); } } //[SerializeField] protected Color32 m_outlineColor = Color.black; /// /// Sets the thickness of the outline of the font. Setting this value will result in an instance of the material. /// public float outlineWidth { get { if (m_sharedMaterial == null) return m_outlineWidth; m_outlineWidth = m_sharedMaterial.GetFloat(ShaderUtilities.ID_OutlineWidth); return m_outlineWidth; } set { if (m_outlineWidth == value) return; SetOutlineThickness(value); m_havePropertiesChanged = true; m_outlineWidth = value; SetVerticesDirty(); } } protected float m_outlineWidth = 0.0f; /// /// The rotation for the environment map lighting. /// protected Vector3 m_currentEnvMapRotation; /// /// Determine if the environment map property is valid. /// protected bool m_hasEnvMapProperty; /// /// The point size of the font. /// public float fontSize { get { return m_fontSize; } set { if (m_fontSize == value) return; m_havePropertiesChanged = true; m_fontSize = value; if (!m_enableAutoSizing) m_fontSizeBase = m_fontSize; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected float m_fontSize = -99; // Font Size protected float m_currentFontSize; // Temporary Font Size affected by tags [SerializeField] // TODO: Review if this should be serialized protected float m_fontSizeBase = 36; protected TMP_TextProcessingStack m_sizeStack = new TMP_TextProcessingStack(16); /// /// Control the weight of the font if an alternative font asset is assigned for the given weight in the font asset editor. /// public FontWeight fontWeight { get { return m_fontWeight; } set { if (m_fontWeight == value) return; m_fontWeight = value; m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected FontWeight m_fontWeight = FontWeight.Regular; protected FontWeight m_FontWeightInternal = FontWeight.Regular; protected TMP_TextProcessingStack m_FontWeightStack = new TMP_TextProcessingStack(8); /// /// /// public float pixelsPerUnit { get { var localCanvas = canvas; if (!localCanvas) return 1; // For dynamic fonts, ensure we use one pixel per pixel on the screen. if (!font) return localCanvas.scaleFactor; // For non-dynamic fonts, calculate pixels per unit based on specified font size relative to font object's own font size. if (m_currentFontAsset == null || m_currentFontAsset.faceInfo.pointSize <= 0 || m_fontSize <= 0) return 1; return m_fontSize / m_currentFontAsset.faceInfo.pointSize; } } /// /// Enable text auto-sizing /// public bool enableAutoSizing { get { return m_enableAutoSizing; } set { if (m_enableAutoSizing == value) return; m_enableAutoSizing = value; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected bool m_enableAutoSizing; protected float m_maxFontSize; // Used in conjunction with auto-sizing protected float m_minFontSize; // Used in conjunction with auto-sizing protected int m_AutoSizeIterationCount; protected int m_AutoSizeMaxIterationCount = 100; protected bool m_IsAutoSizePointSizeSet; /// /// Minimum point size of the font when text auto-sizing is enabled. /// public float fontSizeMin { get { return m_fontSizeMin; } set { if (m_fontSizeMin == value) return; m_fontSizeMin = value; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected float m_fontSizeMin = 0; // Text Auto Sizing Min Font Size. /// /// Maximum point size of the font when text auto-sizing is enabled. /// public float fontSizeMax { get { return m_fontSizeMax; } set { if (m_fontSizeMax == value) return; m_fontSizeMax = value; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected float m_fontSizeMax = 0; // Text Auto Sizing Max Font Size. /// /// The style of the text /// public FontStyles fontStyle { get { return m_fontStyle; } set { if (m_fontStyle == value) return; m_fontStyle = value; m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected FontStyles m_fontStyle = FontStyles.Normal; protected FontStyles m_FontStyleInternal = FontStyles.Normal; protected TMP_FontStyleStack m_fontStyleStack; /// /// Property used in conjunction with padding calculation for the geometry. /// public bool isUsingBold { get { return m_isUsingBold; } } protected bool m_isUsingBold = false; // Used to ensure GetPadding & Ratios take into consideration bold characters. /// /// Horizontal alignment options /// public HorizontalAlignmentOptions horizontalAlignment { get { return m_HorizontalAlignment; } set { if (m_HorizontalAlignment == value) return; m_HorizontalAlignment = value; m_havePropertiesChanged = true; SetVerticesDirty(); } } [SerializeField] protected HorizontalAlignmentOptions m_HorizontalAlignment = HorizontalAlignmentOptions.Left; /// /// Vertical alignment options /// public VerticalAlignmentOptions verticalAlignment { get { return m_VerticalAlignment; } set { if (m_VerticalAlignment == value) return; m_VerticalAlignment = value; m_havePropertiesChanged = true; SetVerticesDirty(); } } [SerializeField] protected VerticalAlignmentOptions m_VerticalAlignment = VerticalAlignmentOptions.Top; /// /// Text alignment options /// public TextAlignmentOptions alignment { get { return (TextAlignmentOptions)((int)m_HorizontalAlignment | (int)m_VerticalAlignment); } set { HorizontalAlignmentOptions horizontalAlignment = (HorizontalAlignmentOptions)((int)value & 0xFF); VerticalAlignmentOptions verticalAlignment = (VerticalAlignmentOptions)((int)value & 0xFF00); if (m_HorizontalAlignment == horizontalAlignment && m_VerticalAlignment == verticalAlignment) return; m_HorizontalAlignment = horizontalAlignment; m_VerticalAlignment = verticalAlignment; m_havePropertiesChanged = true; SetVerticesDirty(); } } [SerializeField] [UnityEngine.Serialization.FormerlySerializedAs("m_lineJustification")] protected TextAlignmentOptions m_textAlignment = TextAlignmentOptions.Converted; protected HorizontalAlignmentOptions m_lineJustification; protected TMP_TextProcessingStack m_lineJustificationStack = new TMP_TextProcessingStack(new HorizontalAlignmentOptions[16]); protected Vector3[] m_textContainerLocalCorners = new Vector3[4]; /// /// Use the extents of the text geometry for alignment instead of font metrics. /// //public bool alignByGeometry //{ // get { return m_alignByGeometry; } // set { if (m_alignByGeometry == value) return; m_havePropertiesChanged = true; m_alignByGeometry = value; SetVerticesDirty(); } //} //[SerializeField] //protected bool m_alignByGeometry; /// /// The amount of additional spacing between characters. /// public float characterSpacing { get { return m_characterSpacing; } set { if (m_characterSpacing == value) return; m_havePropertiesChanged = true; m_characterSpacing = value; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected float m_characterSpacing = 0; protected float m_cSpacing = 0; protected float m_monoSpacing = 0; protected bool m_duoSpace; /// /// The amount of additional spacing between words. /// public float wordSpacing { get { return m_wordSpacing; } set { if (m_wordSpacing == value) return; m_havePropertiesChanged = true; m_wordSpacing = value; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected float m_wordSpacing = 0; /// /// The amount of additional spacing to add between each lines of text. /// public float lineSpacing { get { return m_lineSpacing; } set { if (m_lineSpacing == value) return; m_havePropertiesChanged = true; m_lineSpacing = value; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected float m_lineSpacing = 0; protected float m_lineSpacingDelta = 0; // Used with Text Auto Sizing feature protected float m_lineHeight = TMP_Math.FLOAT_UNSET; // Used with the tag. protected bool m_IsDrivenLineSpacing; /// /// The amount of potential line spacing adjustment before text auto sizing kicks in. /// public float lineSpacingAdjustment { get { return m_lineSpacingMax; } set { if (m_lineSpacingMax == value) return; m_havePropertiesChanged = true; m_lineSpacingMax = value; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected float m_lineSpacingMax = 0; // Text Auto Sizing Max Line spacing reduction. //protected bool m_forceLineBreak; /// /// The amount of additional spacing to add between each lines of text. /// public float paragraphSpacing { get { return m_paragraphSpacing; } set { if (m_paragraphSpacing == value) return; m_havePropertiesChanged = true; m_paragraphSpacing = value; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected float m_paragraphSpacing = 0; /// /// Percentage the width of characters can be adjusted before text auto-sizing begins to reduce the point size. /// public float characterWidthAdjustment { get { return m_charWidthMaxAdj; } set { if (m_charWidthMaxAdj == value) return; m_havePropertiesChanged = true; m_charWidthMaxAdj = value; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected float m_charWidthMaxAdj = 0f; // Text Auto Sizing Max Character Width reduction. protected float m_charWidthAdjDelta = 0; /// /// Controls the text wrapping mode. /// public TextWrappingModes textWrappingMode { get { return m_TextWrappingMode; } set { if (m_TextWrappingMode == value) return; m_havePropertiesChanged = true; m_TextWrappingMode = value; SetVerticesDirty(); SetLayoutDirty(); } } /// /// Controls whether or not word wrapping is applied. When disabled, the text will be displayed on a single line. /// [Obsolete("The enabledWordWrapping property is now obsolete. Please use the textWrappingMode property instead.")] public bool enableWordWrapping { get { return m_TextWrappingMode == TextWrappingModes.Normal || textWrappingMode == TextWrappingModes.PreserveWhitespace; } set { TextWrappingModes mode = (TextWrappingModes)(value ? 1 : 0); if (m_TextWrappingMode == mode) return; m_havePropertiesChanged = true; m_TextWrappingMode = mode; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] [FormerlySerializedAs("m_enableWordWrapping")] protected TextWrappingModes m_TextWrappingMode; protected bool m_isCharacterWrappingEnabled = false; protected bool m_isNonBreakingSpace = false; protected bool m_isIgnoringAlignment; /// /// Controls the blending between using character and word spacing to fill-in the space for justified text. /// public float wordWrappingRatios { get { return m_wordWrappingRatios; } set { if (m_wordWrappingRatios == value) return; m_wordWrappingRatios = value; m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected float m_wordWrappingRatios = 0.4f; // Controls word wrapping ratios between word or characters. /// /// /// //public bool enableAdaptiveJustification //{ // get { return m_enableAdaptiveJustification; } // set { if (m_enableAdaptiveJustification == value) return; m_enableAdaptiveJustification = value; m_havePropertiesChanged = true; m_isCalculateSizeRequired = true; SetVerticesDirty(); SetLayoutDirty(); } //} //[SerializeField] //protected bool m_enableAdaptiveJustification; //protected float m_adaptiveJustificationThreshold = 10.0f; /// /// Controls the Text Overflow Mode /// public TextOverflowModes overflowMode { get { return m_overflowMode; } set { if (m_overflowMode == value) return; m_overflowMode = value; m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected TextOverflowModes m_overflowMode = TextOverflowModes.Overflow; /// /// Indicates if the text exceeds the vertical bounds of its text container. /// public bool isTextOverflowing { get { if (m_firstOverflowCharacterIndex != -1) return true; return false; } } /// /// The first character which exceeds the vertical bounds of its text container. /// public int firstOverflowCharacterIndex { get { return m_firstOverflowCharacterIndex; } } //[SerializeField] protected int m_firstOverflowCharacterIndex = -1; /// /// The linked text component used for flowing the text from one text component to another. /// public TMP_Text linkedTextComponent { get { return m_linkedTextComponent; } set { if (value == null) { // Release linked text components ReleaseLinkedTextComponent(m_linkedTextComponent); m_linkedTextComponent = value; } else if (IsSelfOrLinkedAncestor(value)) { // We do nothing since new assigned is invalid return; } else { // Release linked text components ReleaseLinkedTextComponent(m_linkedTextComponent); m_linkedTextComponent = value; m_linkedTextComponent.parentLinkedComponent = this; } m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected TMP_Text m_linkedTextComponent; [SerializeField] internal TMP_Text parentLinkedComponent; /// /// Property indicating whether the text is Truncated or using Ellipsis. /// public bool isTextTruncated { get { return m_isTextTruncated; } } //[SerializeField] protected bool m_isTextTruncated; /// /// Determines if kerning is enabled or disabled. /// [Obsolete("The \"enableKerning\" property has been deprecated. Use the \"fontFeatures\" property to control what features are enabled on the text component.")] public bool enableKerning { get { return m_ActiveFontFeatures.Contains(OTL_FeatureTag.kern); } set { if (m_ActiveFontFeatures.Contains(OTL_FeatureTag.kern)) { if (value) return; m_ActiveFontFeatures.Remove(OTL_FeatureTag.kern); m_enableKerning = false; } else { if (!value) return; m_ActiveFontFeatures.Add(OTL_FeatureTag.kern); m_enableKerning = true; } m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected bool m_enableKerning; protected int m_LastBaseGlyphIndex; /// /// List of OpenType font features that are enabled. /// public List fontFeatures { get { return m_ActiveFontFeatures; } set { if (value == null) return; m_havePropertiesChanged = true; m_ActiveFontFeatures = value; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected List m_ActiveFontFeatures = new List { 0 }; /// /// Adds extra padding around each character. This may be necessary when the displayed text is very small to prevent clipping. /// public bool extraPadding { get { return m_enableExtraPadding; } set { if (m_enableExtraPadding == value) return; m_havePropertiesChanged = true; m_enableExtraPadding = value; UpdateMeshPadding(); SetVerticesDirty(); /* SetLayoutDirty();*/ } } [SerializeField] protected bool m_enableExtraPadding = false; [SerializeField] protected bool checkPaddingRequired; /// /// Enables or Disables Rich Text Tags /// public bool richText { get { return m_isRichText; } set { if (m_isRichText == value) return; m_isRichText = value; m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected bool m_isRichText = true; // Used to enable or disable Rich Text. /// /// Determines if text assets defined in the Emoji Fallback Text Assets list in the TMP Settings will be search first for characters defined as Emojis in the Unicode 14.0 standards. /// public bool emojiFallbackSupport { get { return m_EmojiFallbackSupport; } set { if (m_EmojiFallbackSupport == value) return; m_EmojiFallbackSupport = value; m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] private bool m_EmojiFallbackSupport = true; /// /// Enables or Disables parsing of CTRL characters in input text. /// public bool parseCtrlCharacters { get { return m_parseCtrlCharacters; } set { if (m_parseCtrlCharacters == value) return; m_parseCtrlCharacters = value; m_havePropertiesChanged = true; SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected bool m_parseCtrlCharacters = true; /// /// Sets the RenderQueue along with Ztest to force the text to be drawn last and on top of scene elements. /// public bool isOverlay { get { return m_isOverlay; } set { if (m_isOverlay == value) return; m_isOverlay = value; SetShaderDepth(); m_havePropertiesChanged = true; SetVerticesDirty(); } } protected bool m_isOverlay = false; /// /// Sets Perspective Correction to Zero for Orthographic Camera mode & 0.875f for Perspective Camera mode. /// public bool isOrthographic { get { return m_isOrthographic; } set { if (m_isOrthographic == value) return; m_havePropertiesChanged = true; m_isOrthographic = value; SetVerticesDirty(); } } [SerializeField] protected bool m_isOrthographic = false; /// /// Sets the culling on the shaders. Note changing this value will result in an instance of the material. /// public bool enableCulling { get { return m_isCullingEnabled; } set { if (m_isCullingEnabled == value) return; m_isCullingEnabled = value; SetCulling(); m_havePropertiesChanged = true; } } [SerializeField] protected bool m_isCullingEnabled = false; // protected bool m_isMaskingEnabled; protected bool isMaskUpdateRequired; /// /// Forces objects that are not visible to get refreshed. /// public bool ignoreVisibility { get { return m_ignoreCulling; } set { if (m_ignoreCulling == value) return; m_havePropertiesChanged = true; m_ignoreCulling = value; } } //[SerializeField] protected bool m_ignoreCulling = true; // Not implemented yet. /// /// Controls how the face and outline textures will be applied to the text object. /// public TextureMappingOptions horizontalMapping { get { return m_horizontalMapping; } set { if (m_horizontalMapping == value) return; m_havePropertiesChanged = true; m_horizontalMapping = value; SetVerticesDirty(); } } [SerializeField] protected TextureMappingOptions m_horizontalMapping = TextureMappingOptions.Character; /// /// Controls how the face and outline textures will be applied to the text object. /// public TextureMappingOptions verticalMapping { get { return m_verticalMapping; } set { if (m_verticalMapping == value) return; m_havePropertiesChanged = true; m_verticalMapping = value; SetVerticesDirty(); } } [SerializeField] protected TextureMappingOptions m_verticalMapping = TextureMappingOptions.Character; /// /// Controls the UV Offset for the various texture mapping mode on the text object. /// //public Vector2 mappingUvOffset //{ // get { return m_uvOffset; } // set { if (m_uvOffset == value) return; m_havePropertiesChanged = true; m_uvOffset = value; SetVerticesDirty(); } //} //[SerializeField] //protected Vector2 m_uvOffset = Vector2.zero; // Used to offset UV on Texturing /// /// Controls the horizontal offset of the UV of the texture mapping mode for each line of the text object. /// public float mappingUvLineOffset { get { return m_uvLineOffset; } set { if (m_uvLineOffset == value) return; m_havePropertiesChanged = true; m_uvLineOffset = value; SetVerticesDirty(); } } [SerializeField] protected float m_uvLineOffset = 0.0f; // Used for UV line offset per line /// /// Determines if the Mesh will be rendered. /// public TextRenderFlags renderMode { get { return m_renderMode; } set { if (m_renderMode == value) return; m_renderMode = value; m_havePropertiesChanged = true; } } protected TextRenderFlags m_renderMode = TextRenderFlags.Render; /// /// Determines the sorting order of the geometry of the text object. /// public VertexSortingOrder geometrySortingOrder { get { return m_geometrySortingOrder; } set { m_geometrySortingOrder = value; m_havePropertiesChanged = true; SetVerticesDirty(); } } [SerializeField] protected VertexSortingOrder m_geometrySortingOrder; /// /// Determines if a text object will be excluded from the InternalUpdate callback used to handle updates of SDF Scale when the scale of the text object or parent(s) changes. /// public bool isTextObjectScaleStatic { get { return m_IsTextObjectScaleStatic; } set { m_IsTextObjectScaleStatic = value; if (m_IsTextObjectScaleStatic) TMP_UpdateManager.UnRegisterTextObjectForUpdate(this); else TMP_UpdateManager.RegisterTextObjectForUpdate(this); } } [SerializeField] protected bool m_IsTextObjectScaleStatic; /// /// Determines if the data structures allocated to contain the geometry of the text object will be reduced in size if the number of characters required to display the text is reduced by more than 256 characters. /// This reduction has the benefit of reducing the amount of vertex data being submitted to the graphic device but results in GC when it occurs. /// public bool vertexBufferAutoSizeReduction { get { return m_VertexBufferAutoSizeReduction; } set { m_VertexBufferAutoSizeReduction = value; m_havePropertiesChanged = true; SetVerticesDirty(); } } [SerializeField] protected bool m_VertexBufferAutoSizeReduction = false; /// /// The first character which should be made visible in conjunction with the Text Overflow Linked mode. /// public int firstVisibleCharacter { get { return m_firstVisibleCharacter; } set { if (m_firstVisibleCharacter == value) return; m_havePropertiesChanged = true; m_firstVisibleCharacter = value; SetVerticesDirty(); } } //[SerializeField] protected int m_firstVisibleCharacter; /// /// Allows to control how many characters are visible from the input. /// public int maxVisibleCharacters { get { return m_maxVisibleCharacters; } set { if (m_maxVisibleCharacters == value) return; m_havePropertiesChanged = true; m_maxVisibleCharacters = value; SetVerticesDirty(); } } protected int m_maxVisibleCharacters = 99999; /// /// Allows to control how many words are visible from the input. /// public int maxVisibleWords { get { return m_maxVisibleWords; } set { if (m_maxVisibleWords == value) return; m_havePropertiesChanged = true; m_maxVisibleWords = value; SetVerticesDirty(); } } protected int m_maxVisibleWords = 99999; /// /// Allows control over how many lines of text are displayed. /// public int maxVisibleLines { get { return m_maxVisibleLines; } set { if (m_maxVisibleLines == value) return; m_havePropertiesChanged = true; m_maxVisibleLines = value; SetVerticesDirty(); } } protected int m_maxVisibleLines = 99999; /// /// Determines if the text's vertical alignment will be adjusted based on visible descender of the text. /// public bool useMaxVisibleDescender { get { return m_useMaxVisibleDescender; } set { if (m_useMaxVisibleDescender == value) return; m_havePropertiesChanged = true; m_useMaxVisibleDescender = value; SetVerticesDirty(); } } [SerializeField] protected bool m_useMaxVisibleDescender = true; /// /// Controls which page of text is shown /// public int pageToDisplay { get { return m_pageToDisplay; } set { if (m_pageToDisplay == value) return; m_havePropertiesChanged = true; m_pageToDisplay = value; SetVerticesDirty(); } } [SerializeField] protected int m_pageToDisplay = 1; protected bool m_isNewPage = false; /// /// The margins of the text object. /// public virtual Vector4 margin { get { return m_margin; } set { if (m_margin == value) return; m_margin = value; ComputeMarginSize(); m_havePropertiesChanged = true; SetVerticesDirty(); } } [SerializeField] protected Vector4 m_margin = new Vector4(0, 0, 0, 0); protected float m_marginLeft; protected float m_marginRight; protected float m_marginWidth; // Width of the RectTransform minus left and right margins. protected float m_marginHeight; // Height of the RectTransform minus top and bottom margins. protected float m_width = -1; /// /// Returns data about the text object which includes information about each character, word, line, link, etc. /// public TMP_TextInfo textInfo { get { if (m_textInfo == null) m_textInfo = new TMP_TextInfo(this); return m_textInfo; } } //[SerializeField] protected TMP_TextInfo m_textInfo; // Class which holds information about the Text object such as characters, lines, mesh data as well as metrics. /// /// Property tracking if any of the text properties have changed. Flag is set before the text is regenerated. /// public bool havePropertiesChanged { get { return m_havePropertiesChanged; } set { if (m_havePropertiesChanged == value) return; m_havePropertiesChanged = value; SetAllDirty(); } } //[SerializeField] protected bool m_havePropertiesChanged; // Used to track when properties of the text object have changed. /// /// Property to handle legacy animation component. /// public bool isUsingLegacyAnimationComponent { get { return m_isUsingLegacyAnimationComponent; } set { m_isUsingLegacyAnimationComponent = value; } } [SerializeField] protected bool m_isUsingLegacyAnimationComponent; /// /// Returns are reference to the Transform /// public new Transform transform { get { if (m_transform == null) m_transform = GetComponent(); return m_transform; } } protected Transform m_transform; /// /// Returns are reference to the RectTransform /// public new RectTransform rectTransform { get { if (m_rectTransform == null) m_rectTransform = GetComponent(); return m_rectTransform; } } protected RectTransform m_rectTransform; /// /// Used to track potential changes in RectTransform size to allow us to ignore OnRectTransformDimensionsChange getting called due to rounding errors when using Stretch Anchors. /// protected Vector2 m_PreviousRectTransformSize; /// /// Used to track potential changes in pivot position to allow us to ignore OnRectTransformDimensionsChange getting called due to rounding errors when using Stretch Anchors. /// protected Vector2 m_PreviousPivotPosition; /// /// Enables control over setting the size of the text container to match the text object. /// public virtual bool autoSizeTextContainer { get; set; } protected bool m_autoSizeTextContainer; /// /// The mesh used by the font asset and material assigned to the text object. /// public virtual Mesh mesh { get { return m_mesh; } } protected Mesh m_mesh; /// /// Determines if the geometry of the characters will be quads or volumetric (cubes). /// public bool isVolumetricText { get { return m_isVolumetricText; } set { if (m_isVolumetricText == value) return; m_havePropertiesChanged = value; m_textInfo.ResetVertexLayout(value); SetVerticesDirty(); SetLayoutDirty(); } } [SerializeField] protected bool m_isVolumetricText; /// /// Returns the bounds of the mesh of the text object in world space. /// public Bounds bounds { get { if (m_mesh == null) return new Bounds(); return GetCompoundBounds(); } } /// /// Returns the bounds of the text of the text object. /// public Bounds textBounds { get { if (m_textInfo == null) return new Bounds(); return GetTextBounds(); } } // *** Unity Event Handling *** /// /// Event delegate to allow custom loading of TMP_FontAsset when using the tag. /// public static event Func OnFontAssetRequest; /// /// Event delegate to allow custom loading of TMP_SpriteAsset when using the tag. /// public static event Func OnSpriteAssetRequest; /// /// Delegate for the OnMissingCharacter event called when the requested Unicode character is missing from the font asset. /// /// The Unicode of the missing character. /// The index of the missing character in the source string. /// The source text that contains the missing character. /// The font asset that is missing the requested characters. /// The text component where the requested character is missing. public delegate void MissingCharacterEventCallback(int unicode, int stringIndex, string text, TMP_FontAsset fontAsset, TMP_Text textComponent); /// /// Event delegate to be called when the requested Unicode character is missing from the font asset. /// public static event MissingCharacterEventCallback OnMissingCharacter; /// /// Event delegate to allow modifying the text geometry before it is uploaded to the mesh and rendered. /// public virtual event Action OnPreRenderText = delegate { }; // *** SPECIAL COMPONENTS *** /// /// Component used to control wrapping of text following some arbitrary shape. /// //public MarginShaper marginShaper //{ // get // { // if (m_marginShaper == null) m_marginShaper = GetComponent(); // return m_marginShaper; // } //} //[SerializeField] //protected MarginShaper m_marginShaper; /// /// Component used to control and animate sprites in the text object. /// protected TMP_SpriteAnimator spriteAnimator { get { if (m_spriteAnimator == null) { m_spriteAnimator = GetComponent(); if (m_spriteAnimator == null) m_spriteAnimator = gameObject.AddComponent(); } return m_spriteAnimator; } } protected TMP_SpriteAnimator m_spriteAnimator; /// /// /// //public TMP_TextShaper textShaper //{ // get // { // if (m_textShaper == null) // m_textShaper = GetComponent(); // return m_textShaper; // } //} //[SerializeField] //protected TMP_TextShaper m_textShaper; // *** PROPERTIES RELATED TO UNITY LAYOUT SYSTEM *** /// /// /// public float flexibleHeight { get { return m_flexibleHeight; } } protected float m_flexibleHeight = -1f; /// /// /// public float flexibleWidth { get { return m_flexibleWidth; } } protected float m_flexibleWidth = -1f; /// /// /// public float minWidth { get { return m_minWidth; } } protected float m_minWidth; /// /// /// public float minHeight { get { return m_minHeight; } } protected float m_minHeight; /// /// /// public float maxWidth { get { return m_maxWidth; } } protected float m_maxWidth; /// /// /// public float maxHeight { get { return m_maxHeight; } } protected float m_maxHeight; /// /// /// protected LayoutElement layoutElement { get { if (m_LayoutElement == null) { m_LayoutElement = GetComponent(); } return m_LayoutElement; } } protected LayoutElement m_LayoutElement; /// /// Computed preferred width of the text object. /// public virtual float preferredWidth { get { m_preferredWidth = GetPreferredWidth(); return m_preferredWidth; } } protected float m_preferredWidth; protected float m_RenderedWidth; protected bool m_isPreferredWidthDirty; /// /// Computed preferred height of the text object. /// public virtual float preferredHeight { get { m_preferredHeight = GetPreferredHeight(); return m_preferredHeight; } } protected float m_preferredHeight; protected float m_RenderedHeight; protected bool m_isPreferredHeightDirty; protected bool m_isCalculatingPreferredValues; /// /// Compute the rendered width of the text object. /// public virtual float renderedWidth { get { return GetRenderedWidth(); } } /// /// Compute the rendered height of the text object. /// public virtual float renderedHeight { get { return GetRenderedHeight(); } } /// /// /// public int layoutPriority { get { return m_layoutPriority; } } protected int m_layoutPriority = 0; protected bool m_isLayoutDirty; protected bool m_isAwake; internal bool m_isWaitingOnResourceLoad; protected struct CharacterSubstitution { public int index; public uint unicode; public CharacterSubstitution (int index, uint unicode) { this.index = index; this.unicode = unicode; } } // Protected Fields internal enum TextInputSources { TextInputBox = 0, SetText = 1, SetTextArray = 2, TextString = 3 }; //[SerializeField] internal TextInputSources m_inputSource; protected float m_fontScaleMultiplier; // Used for handling of superscript and subscript. private static char[] m_htmlTag = new char[128]; // Maximum length of rich text tag. This is pre-allocated to avoid GC. private static RichTextTagAttribute[] m_xmlAttribute = new RichTextTagAttribute[8]; private static float[] m_attributeParameterValues = new float[16]; protected float tag_LineIndent = 0; protected float tag_Indent = 0; protected TMP_TextProcessingStack m_indentStack = new TMP_TextProcessingStack(new float[16]); protected bool tag_NoParsing; //protected TMP_LinkInfo tag_LinkInfo = new TMP_LinkInfo(); protected bool m_isTextLayoutPhase; //protected Vector3 m_FXTranslation; protected Quaternion m_FXRotation; protected Vector3 m_FXScale; /// /// Array containing the Unicode characters to be parsed. /// internal TextProcessingElement[] m_TextProcessingArray = new TextProcessingElement[8]; /// /// The number of Unicode characters that have been parsed and contained in the m_InternalParsingBuffer /// internal int m_InternalTextProcessingArraySize; [System.Diagnostics.DebuggerDisplay("Unicode ({unicode}) '{(char)unicode}'")] internal struct TextProcessingElement { public TextProcessingElementType elementType; public uint unicode; public int stringIndex; public int length; } protected struct SpecialCharacter { public TMP_Character character; public TMP_FontAsset fontAsset; public Material material; public int materialIndex; public SpecialCharacter(TMP_Character character, int materialIndex) { this.character = character; this.fontAsset = character.textAsset as TMP_FontAsset; this.material = this.fontAsset != null ? this.fontAsset.material : null; this.materialIndex = materialIndex; } } private TMP_CharacterInfo[] m_internalCharacterInfo; // Used by functions to calculate preferred values. protected int m_totalCharacterCount; // Structures used to save the state of the text layout in conjunction with line breaking / word wrapping. internal static WordWrapState m_SavedWordWrapState = new WordWrapState(); internal static WordWrapState m_SavedLineState = new WordWrapState(); internal static WordWrapState m_SavedEllipsisState = new WordWrapState(); internal static WordWrapState m_SavedLastValidState = new WordWrapState(); internal static WordWrapState m_SavedSoftLineBreakState = new WordWrapState(); //internal Stack m_LineBreakCandiateStack = new Stack(); internal static TMP_TextProcessingStack m_EllipsisInsertionCandidateStack = new TMP_TextProcessingStack(8, 8); // Fields whose state is saved in conjunction with text parsing and word wrapping. protected int m_characterCount; //protected int m_visibleCharacterCount; //protected int m_visibleSpriteCount; protected int m_firstCharacterOfLine; protected int m_firstVisibleCharacterOfLine; protected int m_lastCharacterOfLine; protected int m_lastVisibleCharacterOfLine; protected int m_lineNumber; protected int m_lineVisibleCharacterCount; protected int m_lineVisibleSpaceCount; protected int m_pageNumber; protected float m_PageAscender; protected float m_maxTextAscender; protected float m_maxCapHeight; protected float m_ElementAscender; protected float m_ElementDescender; protected float m_maxLineAscender; protected float m_maxLineDescender; protected float m_startOfLineAscender; protected float m_startOfLineDescender; //protected float m_maxFontScale; protected float m_lineOffset; protected Extents m_meshExtents; // Fields used for vertex colors protected Color32 m_htmlColor = new Color(255, 255, 255, 128); protected TMP_TextProcessingStack m_colorStack = new TMP_TextProcessingStack(new Color32[16]); protected TMP_TextProcessingStack m_underlineColorStack = new TMP_TextProcessingStack(new Color32[16]); protected TMP_TextProcessingStack m_strikethroughColorStack = new TMP_TextProcessingStack(new Color32[16]); protected TMP_TextProcessingStack m_HighlightStateStack = new TMP_TextProcessingStack(new HighlightState[16]); protected TMP_ColorGradient m_colorGradientPreset; protected TMP_TextProcessingStack m_colorGradientStack = new TMP_TextProcessingStack(new TMP_ColorGradient[16]); protected bool m_colorGradientPresetIsTinted; protected float m_tabSpacing = 0; protected float m_spacing = 0; // STYLE TAGS protected TMP_TextProcessingStack[] m_TextStyleStacks = new TMP_TextProcessingStack[8]; protected int m_TextStyleStackDepth = 0; protected TMP_TextProcessingStack m_ItalicAngleStack = new TMP_TextProcessingStack(new int[16]); protected int m_ItalicAngle; protected TMP_TextProcessingStack m_actionStack = new TMP_TextProcessingStack(new int[16]); protected float m_padding = 0; protected float m_baselineOffset; // Used for superscript and subscript. protected TMP_TextProcessingStack m_baselineOffsetStack = new TMP_TextProcessingStack(new float[16]); protected float m_xAdvance; // Tracks x advancement from character to character. protected TMP_TextElementType m_textElementType; protected TMP_TextElement m_cached_TextElement; // Glyph / Character information is cached into this variable which is faster than having to fetch from the Dictionary multiple times. protected SpecialCharacter m_Ellipsis; protected SpecialCharacter m_Underline; protected TMP_SpriteAsset m_defaultSpriteAsset; protected TMP_SpriteAsset m_currentSpriteAsset; protected int m_spriteCount = 0; protected int m_spriteIndex; protected int m_spriteAnimationID; // Profiler Marker declarations private static ProfilerMarker k_ParseTextMarker = new ProfilerMarker("TMP Parse Text"); private static ProfilerMarker k_InsertNewLineMarker = new ProfilerMarker("TMP.InsertNewLine"); /// /// Method which derived classes need to override to load Font Assets. /// protected virtual void LoadFontAsset() { } /// /// Function called internally when a new shared material is assigned via the fontSharedMaterial property. /// /// protected virtual void SetSharedMaterial(Material mat) { } /// /// Function called internally when a new material is assigned via the fontMaterial property. /// protected virtual Material GetMaterial(Material mat) { return null; } /// /// Function called internally when assigning a new base material. /// /// protected virtual void SetFontBaseMaterial(Material mat) { } /// /// Method which returns an array containing the materials used by the text object. /// /// protected virtual Material[] GetSharedMaterials() { return null; } /// /// /// protected virtual void SetSharedMaterials(Material[] materials) { } /// /// Method returning instances of the materials used by the text object. /// /// protected virtual Material[] GetMaterials(Material[] mats) { return null; } /// /// Method to set the materials of the text and sub text objects. /// /// //protected virtual void SetMaterials (Material[] mats) { } /// /// Function used to create an instance of the material /// /// /// protected virtual Material CreateMaterialInstance(Material source) { Material mat = new Material(source); mat.shaderKeywords = source.shaderKeywords; mat.name += " (Instance)"; return mat; } protected void SetVertexColorGradient(TMP_ColorGradient gradient) { if (gradient == null) return; m_fontColorGradient.bottomLeft = gradient.bottomLeft; m_fontColorGradient.bottomRight = gradient.bottomRight; m_fontColorGradient.topLeft = gradient.topLeft; m_fontColorGradient.topRight = gradient.topRight; SetVerticesDirty(); } /// /// Function to control the sorting of the geometry of the text object. /// protected void SetTextSortingOrder(VertexSortingOrder order) { } /// /// Function to sort the geometry of the text object in accordance to the provided order. /// /// protected void SetTextSortingOrder(int[] order) { } /// /// Function called internally to set the face color of the material. This will results in an instance of the material. /// /// protected virtual void SetFaceColor(Color32 color) { } /// /// Function called internally to set the outline color of the material. This will results in an instance of the material. /// /// protected virtual void SetOutlineColor(Color32 color) { } /// /// Function called internally to set the outline thickness property of the material. This will results in an instance of the material. /// /// protected virtual void SetOutlineThickness(float thickness) { } /// /// Set the Render Queue and ZTest mode on the current material /// protected virtual void SetShaderDepth() { } /// /// Set the culling mode on the material. /// protected virtual void SetCulling() { } /// /// /// internal virtual void UpdateCulling() {} /// /// Get the padding value for the currently assigned material /// /// protected virtual float GetPaddingForMaterial() { ShaderUtilities.GetShaderPropertyIDs(); if (m_sharedMaterial == null) return 0; m_padding = ShaderUtilities.GetPadding(m_sharedMaterial, m_enableExtraPadding, m_isUsingBold); m_isMaskingEnabled = ShaderUtilities.IsMaskingEnabled(m_sharedMaterial); m_isSDFShader = m_sharedMaterial.HasProperty(ShaderUtilities.ID_WeightNormal); return m_padding; } /// /// Get the padding value for the given material /// /// protected virtual float GetPaddingForMaterial(Material mat) { if (mat == null) return 0; m_padding = ShaderUtilities.GetPadding(mat, m_enableExtraPadding, m_isUsingBold); m_isMaskingEnabled = ShaderUtilities.IsMaskingEnabled(m_sharedMaterial); m_isSDFShader = mat.HasProperty(ShaderUtilities.ID_WeightNormal); return m_padding; } /// /// Method to return the local corners of the Text Container or RectTransform. /// /// protected virtual Vector3[] GetTextContainerLocalCorners() { return null; } // PUBLIC FUNCTIONS protected bool m_ignoreActiveState; /// /// Function to force regeneration of the text object before its normal process time. This is useful when changes to the text object properties need to be applied immediately. /// /// Ignore Active State of text objects. Inactive objects are ignored by default. /// Force re-parsing of the text. public virtual void ForceMeshUpdate(bool ignoreActiveState = false, bool forceTextReparsing = false) { } /// /// Function to update the geometry of the main and sub text objects. /// /// /// public virtual void UpdateGeometry(Mesh mesh, int index) { } /// /// Function to push the updated vertex data into the mesh and renderer. /// public virtual void UpdateVertexData(TMP_VertexDataUpdateFlags flags) { } /// /// Function to push the updated vertex data into the mesh and renderer. /// public virtual void UpdateVertexData() { } /// /// Function to push a new set of vertices to the mesh. /// /// public virtual void SetVertices(Vector3[] vertices) { } /// /// Function to be used to force recomputing of character padding when Shader / Material properties have been changed via script. /// public virtual void UpdateMeshPadding() { } /// /// /// //public virtual new void UpdateGeometry() { } /// /// Tweens the CanvasRenderer color associated with this Graphic. /// /// Target color. /// Tween duration. /// Should ignore Time.scale? /// Should also Tween the alpha channel? public override void CrossFadeColor(Color targetColor, float duration, bool ignoreTimeScale, bool useAlpha) { base.CrossFadeColor(targetColor, duration, ignoreTimeScale, useAlpha); InternalCrossFadeColor(targetColor, duration, ignoreTimeScale, useAlpha); } /// /// Tweens the alpha of the CanvasRenderer color associated with this Graphic. /// /// Target alpha. /// Duration of the tween in seconds. /// Should ignore Time.scale? public override void CrossFadeAlpha(float alpha, float duration, bool ignoreTimeScale) { base.CrossFadeAlpha(alpha, duration, ignoreTimeScale); InternalCrossFadeAlpha(alpha, duration, ignoreTimeScale); } /// /// /// /// /// /// /// /// protected virtual void InternalCrossFadeColor(Color targetColor, float duration, bool ignoreTimeScale, bool useAlpha) { } /// /// /// /// /// /// protected virtual void InternalCrossFadeAlpha(float alpha, float duration, bool ignoreTimeScale) { } /// /// /// struct TextBackingContainer { public uint[] Text { get { return m_Array; } } public int Capacity { get { return m_Array.Length; } } public int Count { get { return m_Index; } set { m_Index = value; } } private uint[] m_Array; private int m_Index; public uint this[int index] { get { return m_Array[index]; } set { if (index >= m_Array.Length) Resize(index); m_Array[index] = value; } } public TextBackingContainer(int size) { m_Array = new uint[size]; m_Index = 0; } public void Resize(int size) { size = Mathf.NextPowerOfTwo(size + 1); Array.Resize(ref m_Array, size); } } /// /// Internal array containing the converted source text used in the text parsing process. /// private TextBackingContainer m_TextBackingArray = new TextBackingContainer(4); /// /// Method to parse the input text based on its source /// protected void ParseInputText() { k_ParseTextMarker.Begin(); switch (m_inputSource) { case TextInputSources.TextString: case TextInputSources.TextInputBox: PopulateTextBackingArray(m_TextPreprocessor == null ? m_text : m_TextPreprocessor.PreprocessText(m_text)); PopulateTextProcessingArray(); break; case TextInputSources.SetText: break; case TextInputSources.SetTextArray: break; } SetArraySizes(m_TextProcessingArray); k_ParseTextMarker.End(); } /// /// Convert source text to Unicode (uint) and populate internal text backing array. /// /// Source text to be converted void PopulateTextBackingArray(string sourceText) { int srcLength = sourceText == null ? 0 : sourceText.Length; PopulateTextBackingArray(sourceText, 0, srcLength); } /// /// Convert source text to uint and populate internal text backing array. /// /// string containing the source text to be converted /// Index of the first element of the source array to be converted and copied to the internal text backing array. /// Number of elements in the array to be converted and copied to the internal text backing array. void PopulateTextBackingArray(string sourceText, int start, int length) { int readIndex; int writeIndex = 0; // Range check if (sourceText == null) { readIndex = 0; length = 0; } else { readIndex = Mathf.Clamp(start, 0, sourceText.Length); length = Mathf.Clamp(length, 0, start + length < sourceText.Length ? length : sourceText.Length - start); } // Make sure array size is appropriate if (length >= m_TextBackingArray.Capacity) m_TextBackingArray.Resize((length)); int end = readIndex + length; for (; readIndex < end; readIndex++) { m_TextBackingArray[writeIndex] = sourceText[readIndex]; writeIndex += 1; } // Terminate array with zero as we are not clearing the array on new invocation of this function. m_TextBackingArray[writeIndex] = 0; m_TextBackingArray.Count = writeIndex; } /// /// Convert source text to uint and populate internal text backing array. /// /// char array containing the source text to be converted /// Index of the first element of the source array to be converted and copied to the internal text backing array. /// Number of elements in the array to be converted and copied to the internal text backing array. void PopulateTextBackingArray(StringBuilder sourceText, int start, int length) { int readIndex; int writeIndex = 0; // Range check if (sourceText == null) { readIndex = 0; length = 0; } else { readIndex = Mathf.Clamp(start, 0, sourceText.Length); length = Mathf.Clamp(length, 0, start + length < sourceText.Length ? length : sourceText.Length - start); } // Make sure array size is appropriate if (length >= m_TextBackingArray.Capacity) m_TextBackingArray.Resize((length)); int end = readIndex + length; for (; readIndex < end; readIndex++) { m_TextBackingArray[writeIndex] = sourceText[readIndex]; writeIndex += 1; } // Terminate array with zero as we are not clearing the array on new invocation of this function. m_TextBackingArray[writeIndex] = 0; m_TextBackingArray.Count = writeIndex; } /// /// Convert source text to Unicode (uint) and populate internal text backing array. /// /// char array containing the source text to be converted /// Index of the first element of the source array to be converted and copied to the internal text backing array. /// Number of elements in the array to be converted and copied to the internal text backing array. void PopulateTextBackingArray(char[] sourceText, int start, int length) { int readIndex; int writeIndex = 0; // Range check if (sourceText == null) { readIndex = 0; length = 0; } else { readIndex = Mathf.Clamp(start, 0, sourceText.Length); length = Mathf.Clamp(length, 0, start + length < sourceText.Length ? length : sourceText.Length - start); } // Make sure array size is appropriate if (length >= m_TextBackingArray.Capacity) m_TextBackingArray.Resize((length)); int end = readIndex + length; for (; readIndex < end; readIndex++) { m_TextBackingArray[writeIndex] = sourceText[readIndex]; writeIndex += 1; } // Terminate array with zero as we are not clearing the array on new invocation of this function. m_TextBackingArray[writeIndex] = 0; m_TextBackingArray.Count = writeIndex; } /// /// /// void PopulateTextProcessingArray() { // Reset Style stack back to default TMP_TextProcessingStack.SetDefault(m_TextStyleStacks, 0); int srcLength = m_TextBackingArray.Count; int requiredCapacity = srcLength + (textStyle.styleOpeningDefinition?.Length ?? 0); // Make sure parsing buffer is large enough to handle the required text. if (m_TextProcessingArray.Length < requiredCapacity) ResizeInternalArray(ref m_TextProcessingArray, requiredCapacity); m_TextStyleStackDepth = 0; int writeIndex = 0; // Insert Opening Style if (textStyle.hashCode != (int)MarkupTag.NORMAL) InsertOpeningStyleTag(m_TextStyle, ref m_TextProcessingArray, ref writeIndex); tag_NoParsing = false; int readIndex = 0; for (; readIndex < srcLength; readIndex++) { uint c = m_TextBackingArray[readIndex]; if (c == 0) break; if (/*m_inputSource == TextInputSources.TextInputBox &&*/ c == '\\' && readIndex < srcLength - 1) { switch (m_TextBackingArray[readIndex + 1]) { case 92: // \ escape if (!m_parseCtrlCharacters) break; readIndex += 1; break; case 110: // \n LineFeed if (!m_parseCtrlCharacters) break; m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 1, unicode = 10 }; readIndex += 1; writeIndex += 1; continue; case 114: // \r Carriage Return if (!m_parseCtrlCharacters) break; m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 1, unicode = 13 }; readIndex += 1; writeIndex += 1; continue; case 116: // \t Tab if (!m_parseCtrlCharacters) break; m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 1, unicode = 9 }; readIndex += 1; writeIndex += 1; continue; case 118: // \v Vertical tab used as soft line break if (!m_parseCtrlCharacters) break; m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 1, unicode = 11 }; readIndex += 1; writeIndex += 1; continue; case 117: // \u0000 for UTF-16 Unicode if (srcLength > readIndex + 5 && IsValidUTF16(m_TextBackingArray, readIndex + 2)) { m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 6, unicode = GetUTF16(m_TextBackingArray, readIndex + 2) }; readIndex += 5; writeIndex += 1; continue; } break; case 85: // \U00000000 for UTF-32 Unicode if (srcLength > readIndex + 9 && IsValidUTF32(m_TextBackingArray, readIndex + 2)) { m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 10, unicode = GetUTF32(m_TextBackingArray, readIndex + 2) }; readIndex += 9; writeIndex += 1; continue; } break; } } // Handle surrogate pair conversion if (c >= CodePoint.HIGH_SURROGATE_START && c <= CodePoint.HIGH_SURROGATE_END && srcLength > readIndex + 1 && m_TextBackingArray[readIndex + 1] >= CodePoint.LOW_SURROGATE_START && m_TextBackingArray[readIndex + 1] <= CodePoint.LOW_SURROGATE_END) { m_TextProcessingArray[writeIndex] = new TextProcessingElement { elementType = TextProcessingElementType.TextCharacterElement, stringIndex = readIndex, length = 2, unicode = TMP_TextParsingUtilities.ConvertToUTF32(c, m_TextBackingArray[readIndex + 1]) }; readIndex += 1; writeIndex += 1; continue; } // Handle inline replacement of //case 1022986: // // style = TMP_StyleSheet.GetStyle(m_xmlAttribute[0].valueHashCode); // if (style == null) // { // // Get style from the Style Stack // int styleHashCode = m_styleStack.CurrentItem(); // style = TMP_StyleSheet.GetStyle(styleHashCode); // m_styleStack.Remove(); // } // if (style == null) return false; // //// Parse Style Macro // for (int i = 0; i < style.styleClosingTagArray.Length; i++) // { // if (style.styleClosingTagArray[i] == 60) // ValidateHtmlTag(style.styleClosingTagArray, i + 1, out i); // } // return true; case MarkupTag.COLOR: // 3 Hex (short hand) if (m_htmlTag[6] == 35 && tagCharCount == 10) { m_htmlColor = HexCharsToColor(m_htmlTag, tagCharCount); m_colorStack.Add(m_htmlColor); return true; } // 4 Hex (short hand) else if (m_htmlTag[6] == 35 && tagCharCount == 11) { m_htmlColor = HexCharsToColor(m_htmlTag, tagCharCount); m_colorStack.Add(m_htmlColor); return true; } // 3 Hex pairs if (m_htmlTag[6] == 35 && tagCharCount == 13) { m_htmlColor = HexCharsToColor(m_htmlTag, tagCharCount); m_colorStack.Add(m_htmlColor); return true; } // 4 Hex pairs else if (m_htmlTag[6] == 35 && tagCharCount == 15) { m_htmlColor = HexCharsToColor(m_htmlTag, tagCharCount); m_colorStack.Add(m_htmlColor); return true; } // switch (m_xmlAttribute[0].valueHashCode) { case (int)MarkupTag.RED: // m_htmlColor = Color.red; m_colorStack.Add(m_htmlColor); return true; case (int)MarkupTag.LIGHTBLUE: // m_htmlColor = new Color32(173, 216, 230, 255); m_colorStack.Add(m_htmlColor); return true; case (int)MarkupTag.BLUE: // m_htmlColor = Color.blue; m_colorStack.Add(m_htmlColor); return true; case (int)MarkupTag.GREY: // m_htmlColor = new Color32(128, 128, 128, 255); m_colorStack.Add(m_htmlColor); return true; case (int)MarkupTag.BLACK: // m_htmlColor = Color.black; m_colorStack.Add(m_htmlColor); return true; case (int)MarkupTag.GREEN: // m_htmlColor = Color.green; m_colorStack.Add(m_htmlColor); return true; case (int)MarkupTag.WHITE: // m_htmlColor = Color.white; m_colorStack.Add(m_htmlColor); return true; case (int)MarkupTag.ORANGE: // m_htmlColor = new Color32(255, 128, 0, 255); m_colorStack.Add(m_htmlColor); return true; case (int)MarkupTag.PURPLE: // m_htmlColor = new Color32(160, 32, 240, 255); m_colorStack.Add(m_htmlColor); return true; case (int)MarkupTag.YELLOW: // m_htmlColor = Color.yellow; m_colorStack.Add(m_htmlColor); return true; } return false; case MarkupTag.GRADIENT: int gradientPresetHashCode = m_xmlAttribute[0].valueHashCode; TMP_ColorGradient tempColorGradientPreset; // Check if Color Gradient Preset has already been loaded. if (MaterialReferenceManager.TryGetColorGradientPreset(gradientPresetHashCode, out tempColorGradientPreset)) { m_colorGradientPreset = tempColorGradientPreset; } else { // Load Color Gradient Preset if (tempColorGradientPreset == null) { tempColorGradientPreset = Resources.Load(TMP_Settings.defaultColorGradientPresetsPath + new string(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength)); } if (tempColorGradientPreset == null) return false; MaterialReferenceManager.AddColorGradientPreset(gradientPresetHashCode, tempColorGradientPreset); m_colorGradientPreset = tempColorGradientPreset; } m_colorGradientPresetIsTinted = false; // Check Attributes for (int i = 1; i < m_xmlAttribute.Length && m_xmlAttribute[i].nameHashCode != 0; i++) { // Get attribute name int nameHashCode = m_xmlAttribute[i].nameHashCode; switch ((MarkupTag)nameHashCode) { case MarkupTag.TINT: m_colorGradientPresetIsTinted = ConvertToFloat(m_htmlTag, m_xmlAttribute[i].valueStartIndex, m_xmlAttribute[i].valueLength) != 0; break; } } m_colorGradientStack.Add(m_colorGradientPreset); // TODO : Add support for defining preset in the tag itself return true; case MarkupTag.SLASH_GRADIENT: m_colorGradientPreset = m_colorGradientStack.Remove(); return true; case MarkupTag.CHARACTER_SPACE: value = ConvertToFloat(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_cSpacing = value * (m_isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_cSpacing = value * (m_isOrthographic ? 1 : 0.1f) * m_currentFontSize; break; case TagUnitType.Percentage: return false; } return true; case MarkupTag.SLASH_CHARACTER_SPACE: if (!m_isTextLayoutPhase) return true; // Adjust xAdvance to remove extra space from last character. if (m_characterCount > 0) { m_xAdvance -= m_cSpacing; m_textInfo.characterInfo[m_characterCount - 1].xAdvance = m_xAdvance; } m_cSpacing = 0; return true; case MarkupTag.MONOSPACE: value = ConvertToFloat(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (m_xmlAttribute[0].unitType) { case TagUnitType.Pixels: m_monoSpacing = value * (m_isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_monoSpacing = value * (m_isOrthographic ? 1 : 0.1f) * m_currentFontSize; break; case TagUnitType.Percentage: return false; } // Check for potential DuoSpace attribute. if (m_xmlAttribute[1].nameHashCode == (int)MarkupTag.DUOSPACE) m_duoSpace = ConvertToFloat(m_htmlTag, m_xmlAttribute[1].valueStartIndex, m_xmlAttribute[1].valueLength) != 0; return true; case MarkupTag.SLASH_MONOSPACE: m_monoSpacing = 0; m_duoSpace = false; return true; case MarkupTag.CLASS: return false; case MarkupTag.SLASH_COLOR: m_htmlColor = m_colorStack.Remove(); return true; case MarkupTag.INDENT: value = ConvertToFloat(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: tag_Indent = value * (m_isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: tag_Indent = value * (m_isOrthographic ? 1 : 0.1f) * m_currentFontSize; break; case TagUnitType.Percentage: tag_Indent = m_marginWidth * value / 100; break; } m_indentStack.Add(tag_Indent); m_xAdvance = tag_Indent; return true; case MarkupTag.SLASH_INDENT: tag_Indent = m_indentStack.Remove(); //m_xAdvance = tag_Indent; return true; case MarkupTag.LINE_INDENT: value = ConvertToFloat(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: tag_LineIndent = value * (m_isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: tag_LineIndent = value * (m_isOrthographic ? 1 : 0.1f) * m_currentFontSize; break; case TagUnitType.Percentage: tag_LineIndent = m_marginWidth * value / 100; break; } m_xAdvance += tag_LineIndent; return true; case MarkupTag.SLASH_LINE_INDENT: tag_LineIndent = 0; return true; case MarkupTag.SPRITE: int spriteAssetHashCode = m_xmlAttribute[0].valueHashCode; TMP_SpriteAsset tempSpriteAsset; m_spriteIndex = -1; // CHECK TAG FORMAT if (m_xmlAttribute[0].valueType == TagValueType.None || m_xmlAttribute[0].valueType == TagValueType.NumericalValue) { // No Sprite Asset is assigned to the text object if (m_spriteAsset != null) { m_currentSpriteAsset = m_spriteAsset; } else if (m_defaultSpriteAsset != null) { m_currentSpriteAsset = m_defaultSpriteAsset; } else if (m_defaultSpriteAsset == null) { if (TMP_Settings.defaultSpriteAsset != null) m_defaultSpriteAsset = TMP_Settings.defaultSpriteAsset; else m_defaultSpriteAsset = Resources.Load("Sprite Assets/Default Sprite Asset"); m_currentSpriteAsset = m_defaultSpriteAsset; } // No valid sprite asset available if (m_currentSpriteAsset == null) return false; } else { // A Sprite Asset has been specified if (MaterialReferenceManager.TryGetSpriteAsset(spriteAssetHashCode, out tempSpriteAsset)) { m_currentSpriteAsset = tempSpriteAsset; } else { // Load Sprite Asset if (tempSpriteAsset == null) { // tempSpriteAsset = OnSpriteAssetRequest?.Invoke(spriteAssetHashCode, new string(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength)); if (tempSpriteAsset == null) tempSpriteAsset = Resources.Load(TMP_Settings.defaultSpriteAssetPath + new string(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength)); } if (tempSpriteAsset == null) return false; //Debug.Log("Loading & assigning new Sprite Asset: " + tempSpriteAsset.name); MaterialReferenceManager.AddSpriteAsset(spriteAssetHashCode, tempSpriteAsset); m_currentSpriteAsset = tempSpriteAsset; } } // Handling of legacy tag format. if (m_xmlAttribute[0].valueType == TagValueType.NumericalValue) // { int index = (int)ConvertToFloat(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength); // Reject tag if value is invalid. if (index == Int16.MinValue) return false; // Check to make sure sprite index is valid if (index > m_currentSpriteAsset.spriteCharacterTable.Count - 1) return false; m_spriteIndex = index; } m_spriteColor = s_colorWhite; m_tintSprite = false; // Handle Sprite Tag Attributes for (int i = 0; i < m_xmlAttribute.Length && m_xmlAttribute[i].nameHashCode != 0; i++) { //Debug.Log("Attribute[" + i + "].nameHashCode=" + m_xmlAttribute[i].nameHashCode + " Value:" + ConvertToFloat(m_htmlTag, m_xmlAttribute[i].valueStartIndex, m_xmlAttribute[i].valueLength)); int nameHashCode = m_xmlAttribute[i].nameHashCode; int index = 0; switch ((MarkupTag)nameHashCode) { case MarkupTag.NAME: m_currentSpriteAsset = TMP_SpriteAsset.SearchForSpriteByHashCode(m_currentSpriteAsset, m_xmlAttribute[i].valueHashCode, true, out index); if (index == -1) return false; m_spriteIndex = index; break; case MarkupTag.INDEX: index = (int)ConvertToFloat(m_htmlTag, m_xmlAttribute[1].valueStartIndex, m_xmlAttribute[1].valueLength); // Reject tag if value is invalid. if (index == Int16.MinValue) return false; // Check to make sure sprite index is valid if (index > m_currentSpriteAsset.spriteCharacterTable.Count - 1) return false; m_spriteIndex = index; break; case MarkupTag.TINT: m_tintSprite = ConvertToFloat(m_htmlTag, m_xmlAttribute[i].valueStartIndex, m_xmlAttribute[i].valueLength) != 0; break; case MarkupTag.COLOR: m_spriteColor = HexCharsToColor(m_htmlTag, m_xmlAttribute[i].valueStartIndex, m_xmlAttribute[i].valueLength); break; case MarkupTag.ANIM: //Debug.Log("Start: " + m_xmlAttribute[i].valueStartIndex + " Length: " + m_xmlAttribute[i].valueLength); int paramCount = GetAttributeParameters(m_htmlTag, m_xmlAttribute[i].valueStartIndex, m_xmlAttribute[i].valueLength, ref m_attributeParameterValues); if (paramCount != 3) return false; m_spriteIndex = (int)m_attributeParameterValues[0]; if (m_isTextLayoutPhase) { // TODO : fix this! // It is possible for a sprite to get animated when it ends up being truncated. // Should consider moving the animation of the sprite after text geometry upload. spriteAnimator.DoSpriteAnimation(m_characterCount, m_currentSpriteAsset, m_spriteIndex, (int)m_attributeParameterValues[1], (int)m_attributeParameterValues[2]); } break; //case 45545: // size //case 32745: // SIZE // break; default: if (nameHashCode != (int)MarkupTag.SPRITE) return false; break; } } if (m_spriteIndex == -1) return false; // Material HashCode for the Sprite Asset is the Sprite Asset Hash Code m_currentMaterialIndex = MaterialReference.AddMaterialReference(m_currentSpriteAsset.material, m_currentSpriteAsset, ref m_materialReferences, m_materialReferenceIndexLookup); m_textElementType = TMP_TextElementType.Sprite; return true; case MarkupTag.LOWERCASE: m_FontStyleInternal |= FontStyles.LowerCase; m_fontStyleStack.Add(FontStyles.LowerCase); return true; case MarkupTag.SLASH_LOWERCASE: if ((m_fontStyle & FontStyles.LowerCase) != FontStyles.LowerCase) { if (m_fontStyleStack.Remove(FontStyles.LowerCase) == 0) m_FontStyleInternal &= ~FontStyles.LowerCase; } return true; case MarkupTag.ALLCAPS: case MarkupTag.UPPERCASE: m_FontStyleInternal |= FontStyles.UpperCase; m_fontStyleStack.Add(FontStyles.UpperCase); return true; case MarkupTag.SLASH_ALLCAPS: case MarkupTag.SLASH_UPPERCASE: if ((m_fontStyle & FontStyles.UpperCase) != FontStyles.UpperCase) { if (m_fontStyleStack.Remove(FontStyles.UpperCase) == 0) m_FontStyleInternal &= ~FontStyles.UpperCase; } return true; case MarkupTag.SMALLCAPS: m_FontStyleInternal |= FontStyles.SmallCaps; m_fontStyleStack.Add(FontStyles.SmallCaps); return true; case MarkupTag.SLASH_SMALLCAPS: if ((m_fontStyle & FontStyles.SmallCaps) != FontStyles.SmallCaps) { if (m_fontStyleStack.Remove(FontStyles.SmallCaps) == 0) m_FontStyleInternal &= ~FontStyles.SmallCaps; } return true; case MarkupTag.MARGIN: // Check value type switch (m_xmlAttribute[0].valueType) { case TagValueType.NumericalValue: value = ConvertToFloat(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength); // px // Reject tag if value is invalid. if (value == Int16.MinValue) return false; // Determine tag unit type switch (tagUnitType) { case TagUnitType.Pixels: m_marginLeft = value * (m_isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_marginLeft = value * (m_isOrthographic ? 1 : 0.1f) * m_currentFontSize; break; case TagUnitType.Percentage: m_marginLeft = (m_marginWidth - (m_width != -1 ? m_width : 0)) * value / 100; break; } m_marginLeft = m_marginLeft >= 0 ? m_marginLeft : 0; m_marginRight = m_marginLeft; return true; case TagValueType.None: for (int i = 1; i < m_xmlAttribute.Length && m_xmlAttribute[i].nameHashCode != 0; i++) { // Get attribute name int nameHashCode = m_xmlAttribute[i].nameHashCode; switch ((MarkupTag)nameHashCode) { case MarkupTag.LEFT: value = ConvertToFloat(m_htmlTag, m_xmlAttribute[i].valueStartIndex, m_xmlAttribute[i].valueLength); // px // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (m_xmlAttribute[i].unitType) { case TagUnitType.Pixels: m_marginLeft = value * (m_isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_marginLeft = value * (m_isOrthographic ? 1 : 0.1f) * m_currentFontSize; break; case TagUnitType.Percentage: m_marginLeft = (m_marginWidth - (m_width != -1 ? m_width : 0)) * value / 100; break; } m_marginLeft = m_marginLeft >= 0 ? m_marginLeft : 0; break; case MarkupTag.RIGHT: value = ConvertToFloat(m_htmlTag, m_xmlAttribute[i].valueStartIndex, m_xmlAttribute[i].valueLength); // px // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (m_xmlAttribute[i].unitType) { case TagUnitType.Pixels: m_marginRight = value * (m_isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_marginRight = value * (m_isOrthographic ? 1 : 0.1f) * m_currentFontSize; break; case TagUnitType.Percentage: m_marginRight = (m_marginWidth - (m_width != -1 ? m_width : 0)) * value / 100; break; } m_marginRight = m_marginRight >= 0 ? m_marginRight : 0; break; } } return true; } return false; case MarkupTag.SLASH_MARGIN: m_marginLeft = 0; m_marginRight = 0; return true; case MarkupTag.MARGIN_LEFT: value = ConvertToFloat(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength); // px // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_marginLeft = value * (m_isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_marginLeft = value * (m_isOrthographic ? 1 : 0.1f) * m_currentFontSize; break; case TagUnitType.Percentage: m_marginLeft = (m_marginWidth - (m_width != -1 ? m_width : 0)) * value / 100; break; } m_marginLeft = m_marginLeft >= 0 ? m_marginLeft : 0; return true; case MarkupTag.MARGIN_RIGHT: value = ConvertToFloat(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength); // px // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_marginRight = value * (m_isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_marginRight = value * (m_isOrthographic ? 1 : 0.1f) * m_currentFontSize; break; case TagUnitType.Percentage: m_marginRight = (m_marginWidth - (m_width != -1 ? m_width : 0)) * value / 100; break; } m_marginRight = m_marginRight >= 0 ? m_marginRight : 0; return true; case MarkupTag.LINE_HEIGHT: value = ConvertToFloat(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; switch (tagUnitType) { case TagUnitType.Pixels: m_lineHeight = value * (m_isOrthographic ? 1 : 0.1f); break; case TagUnitType.FontUnits: m_lineHeight = value * (m_isOrthographic ? 1 : 0.1f) * m_currentFontSize; break; case TagUnitType.Percentage: fontScale = (m_currentFontSize / m_currentFontAsset.faceInfo.pointSize * m_currentFontAsset.faceInfo.scale * (m_isOrthographic ? 1 : 0.1f)); m_lineHeight = m_fontAsset.faceInfo.lineHeight * value / 100 * fontScale; break; } return true; case MarkupTag.SLASH_LINE_HEIGHT: m_lineHeight = TMP_Math.FLOAT_UNSET; return true; case MarkupTag.NO_PARSE: tag_NoParsing = true; return true; case MarkupTag.ACTION: int actionID = m_xmlAttribute[0].valueHashCode; if (m_isTextLayoutPhase) { m_actionStack.Add(actionID); Debug.Log("Action ID: [" + actionID + "] First character index: " + m_characterCount); } //if (m_isParsingText) //{ // TMP_Action action = TMP_Action.GetAction(m_xmlAttribute[0].valueHashCode); //} return true; case MarkupTag.SLASH_ACTION: if (m_isTextLayoutPhase) { Debug.Log("Action ID: [" + m_actionStack.CurrentItem() + "] Last character index: " + (m_characterCount - 1)); } m_actionStack.Remove(); return true; case MarkupTag.SCALE: value = ConvertToFloat(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; m_FXScale = new Vector3(value, 1, 1); return true; case MarkupTag.SLASH_SCALE: m_FXScale = Vector3.one; return true; case MarkupTag.ROTATE: // TODO: Add attribute to provide for ability to use Random Rotation value = ConvertToFloat(m_htmlTag, m_xmlAttribute[0].valueStartIndex, m_xmlAttribute[0].valueLength); // Reject tag if value is invalid. if (value == Int16.MinValue) return false; m_FXRotation = Quaternion.Euler(0, 0, value); return true; case MarkupTag.SLASH_ROTATE: m_FXRotation = Quaternion.identity; return true; case MarkupTag.TABLE: //switch (m_xmlAttribute[1].nameHashCode) //{ // case 327550: // width // float tableWidth = ConvertToFloat(m_htmlTag, m_xmlAttribute[1].valueStartIndex, m_xmlAttribute[1].valueLength); // // Reject tag if value is invalid. // if (tableWidth == Int16.MinValue) return false; // switch (tagUnitType) // { // case TagUnitType.Pixels: // Debug.Log("Table width = " + tableWidth + "px."); // break; // case TagUnitType.FontUnits: // Debug.Log("Table width = " + tableWidth + "em."); // break; // case TagUnitType.Percentage: // Debug.Log("Table width = " + tableWidth + "%."); // break; // } // break; //} return false; case MarkupTag.SLASH_TABLE: return false; case MarkupTag.TR: return false; case MarkupTag.SLASH_TR: return false; case MarkupTag.TH: // Set style to bold and center alignment return false; case MarkupTag.SLASH_TH: return false; case MarkupTag.TD: // Style options //for (int i = 1; i < m_xmlAttribute.Length && m_xmlAttribute[i].nameHashCode != 0; i++) //{ // switch (m_xmlAttribute[i].nameHashCode) // { // case 327550: // width // float tableWidth = ConvertToFloat(m_htmlTag, m_xmlAttribute[i].valueStartIndex, m_xmlAttribute[i].valueLength); // switch (tagUnitType) // { // case TagUnitType.Pixels: // Debug.Log("Table width = " + tableWidth + "px."); // break; // case TagUnitType.FontUnits: // Debug.Log("Table width = " + tableWidth + "em."); // break; // case TagUnitType.Percentage: // Debug.Log("Table width = " + tableWidth + "%."); // break; // } // break; // case 275917: // align // switch (m_xmlAttribute[i].valueHashCode) // { // case 3774683: // left // Debug.Log("TD align=\"left\"."); // break; // case 136703040: // right // Debug.Log("TD align=\"right\"."); // break; // case -458210101: // center // Debug.Log("TD align=\"center\"."); // break; // case -523808257: // justified // Debug.Log("TD align=\"justified\"."); // break; // } // break; // } //} return false; case MarkupTag.SLASH_TD: return false; } } #endif #endregion return false; } } }