| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308 |
- using System;
- using System.Collections.Generic;
- using TMPro;
- using UnityEngine;
- using UnityEngine.UI;
- namespace Fateforge
- {
- // Driven by the presentation timeline so pause, speed and cancellation share one clock.
- [DisallowMultipleComponent]
- public sealed class RollingCounter : MonoBehaviour
- {
- sealed class Glyph
- {
- public int characterIndex, startDigit, steps, digitOrder;
- public bool numeric;
- public TMP_Text current, next;
- public Vector2 origin;
- public float currentBaseline, nextBaseline, pitch;
- }
- readonly List<Glyph> glyphs = new List<Glyph>();
- static readonly string[] DigitText = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
- TMP_Text label;
- RectTransform viewport, punctuation;
- Color visibleColor;
- bool hasColor, multiplier;
- string targetText = "";
- Vector2 measuredSize;
- float measuredFontSize;
- int digitCount;
- public bool IsRolling { get; private set; }
- public static RollingCounter Attach(TMP_Text target)
- {
- if (!target) return null;
- var counter = target.GetComponent<RollingCounter>();
- if (!counter)
- {
- counter = target.gameObject.AddComponent<RollingCounter>();
- counter.multiplier = target.text.IndexOf('.') >= 0;
- }
- counter.label = target;
- return counter;
- }
- public void Begin(double from, double to, bool multiplier)
- {
- this.multiplier = multiplier;
- BeginRoll(Format(from), Format(to), from != to);
- }
- public void Begin(long from, long to, string prefix = "")
- {
- multiplier = false;
- BeginRoll(English.Number(from), English.Number(to), from != to, prefix);
- }
- void BeginRoll(string from, string to, bool changed, string prefix = "")
- {
- if (!label) label = GetComponent<TMP_Text>();
- if (!label) return;
- if (IsRolling) RestoreLabel();
- visibleColor = label.color;
- hasColor = true;
- targetText = prefix + to;
- // Keep the real label at the final value for layout and accessibility.
- label.text = targetText;
- ClearGlyphs();
- if (!changed || to.Length > 32 || !label.gameObject.activeInHierarchy)
- {
- IsRolling = false;
- return;
- }
- EnsureViewport();
- viewport.gameObject.SetActive(true);
- punctuation.gameObject.SetActive(true);
- Canvas.ForceUpdateCanvases();
- label.ForceMeshUpdate();
- var startingDigits = Digits(from);
- digitCount = Digits(to).Length;
- int digitOrder = 0;
- for (int i = 0; i < targetText.Length; i++)
- {
- char character = targetText[i];
- bool numeric = i >= prefix.Length && character >= '0' && character <= '9';
- int sourceIndex = startingDigits.Length - digitCount + digitOrder;
- int first = numeric && sourceIndex >= 0 ? startingDigits[sourceIndex] - '0' : 0;
- int final = numeric ? character - '0' : 0;
- var glyph = new Glyph
- {
- characterIndex = i,
- numeric = numeric,
- digitOrder = digitOrder,
- startDigit = first,
- steps = numeric ? (final - first + 10) % 10 + 10 : 0,
- current = MakeText(numeric ? DigitText[first] : character.ToString(), numeric)
- };
- if (numeric)
- {
- glyph.next = MakeText(DigitText[(first + 1) % 10]);
- digitOrder++;
- }
- glyphs.Add(glyph);
- }
- IsRolling = true;
- Measure();
- SetLabelAlpha(0);
- Sample(0);
- }
- public void Sample(float normalizedProgress)
- {
- if (!IsRolling || !label) return;
- float progress = float.IsNaN(normalizedProgress) ? 0 : Mathf.Clamp01(normalizedProgress);
- if (progress >= 1)
- {
- Finish();
- return;
- }
- if (measuredSize != label.rectTransform.rect.size || !Mathf.Approximately(measuredFontSize, label.fontSize))
- Measure();
- foreach (var glyph in glyphs)
- {
- if (!glyph.numeric) continue;
- // Higher digits settle first; units retain the final, shorter roll.
- float end = digitCount <= 1 ? 1 : Mathf.Lerp(.76f, 1, glyph.digitOrder / (float)(digitCount - 1));
- float u = Mathf.Clamp01(progress / end);
- float travel = glyph.steps * (1 - Mathf.Pow(1 - u, 3));
- int whole = Mathf.FloorToInt(travel + .00001f);
- float fraction = Mathf.Clamp01(travel - whole);
- int digit = (glyph.startDigit + whole) % 10;
- glyph.current.text = DigitText[digit];
- glyph.next.text = DigitText[(digit + 1) % 10];
- // The outgoing digit drops while its successor enters from above.
- glyph.current.rectTransform.anchoredPosition = glyph.origin + Vector2.up * (-glyph.currentBaseline - fraction * glyph.pitch);
- glyph.next.rectTransform.anchoredPosition = glyph.origin + Vector2.up * (-glyph.nextBaseline + (1 - fraction) * glyph.pitch);
- }
- }
- public void Finish()
- {
- if (!label) return;
- label.text = targetText;
- RestoreLabel();
- }
- public void Cancel(double displayedValue)
- {
- if (!label) label = GetComponent<TMP_Text>();
- if (!label) return;
- targetText = Format(displayedValue);
- label.text = targetText;
- RestoreLabel();
- }
- string Format(double value)
- {
- if (double.IsNaN(value) || double.IsInfinity(value)) value = 0;
- return multiplier ? English.Multiplier(value) : English.Number(value);
- }
- static string Digits(string text)
- {
- var result = new System.Text.StringBuilder(text.Length);
- foreach (char character in text) if (character >= '0' && character <= '9') result.Append(character);
- return result.ToString();
- }
- void EnsureViewport()
- {
- if (viewport) return;
- viewport = new GameObject("RollingDigits", typeof(RectTransform), typeof(RectMask2D)).GetComponent<RectTransform>();
- viewport.SetParent(label.transform, false);
- viewport.pivot = label.rectTransform.pivot;
- viewport.anchorMin = Vector2.zero;
- viewport.anchorMax = Vector2.one;
- viewport.offsetMin = viewport.offsetMax = Vector2.zero;
- punctuation = new GameObject("CounterPunctuation", typeof(RectTransform)).GetComponent<RectTransform>();
- punctuation.SetParent(label.transform, false);
- punctuation.pivot = label.rectTransform.pivot;
- punctuation.anchorMin = Vector2.zero;
- punctuation.anchorMax = Vector2.one;
- punctuation.offsetMin = punctuation.offsetMax = Vector2.zero;
- }
- TMP_Text MakeText(string text, bool numeric = true)
- {
- var node = new GameObject("CounterGlyph", typeof(RectTransform), typeof(TextMeshProUGUI));
- node.transform.SetParent(numeric ? viewport : punctuation, false);
- var result = node.GetComponent<TextMeshProUGUI>();
- result.text = text;
- result.raycastTarget = false;
- result.enableAutoSizing = false;
- result.textWrappingMode = TextWrappingModes.NoWrap;
- result.overflowMode = TextOverflowModes.Overflow;
- result.alignment = TextAlignmentOptions.BaselineLeft;
- result.margin = Vector4.zero;
- result.color = visibleColor;
- return result;
- }
- void Measure()
- {
- label.ForceMeshUpdate();
- measuredSize = label.rectTransform.rect.size;
- measuredFontSize = label.fontSize;
- viewport.pivot = label.rectTransform.pivot;
- punctuation.pivot = label.rectTransform.pivot;
- float bottom = float.PositiveInfinity, top = float.NegativeInfinity;
- for (int i = 0; i < label.textInfo.characterCount; i++)
- {
- var character = label.textInfo.characterInfo[i];
- // Comma descenders must not enlarge the moving digit window.
- // Punctuation stays stationary beside that window.
- if (!character.isVisible || character.character < '0' || character.character > '9') continue;
- if (character.textElement != null && character.textElement.glyph != null)
- {
- var metrics = character.textElement.glyph.metrics;
- float glyphTop = character.baseLine + metrics.horizontalBearingY * character.scale;
- top = Mathf.Max(top, glyphTop);
- bottom = Mathf.Min(bottom, glyphTop - metrics.height * character.scale);
- }
- else
- {
- top = Mathf.Max(top, character.ascender);
- bottom = Mathf.Min(bottom, character.descender);
- }
- }
- var bounds = label.rectTransform.rect;
- if (float.IsInfinity(bottom)) { bottom = bounds.yMin; top = bounds.yMax; }
- bottom = Mathf.Max(bounds.yMin, bottom - 2);
- top = Mathf.Min(bounds.yMax, top + 2);
- // Padding is left/bottom/right/top. Keep the original coordinate origin,
- // while clipping to the single visible number row rather than its label box.
- viewport.GetComponent<RectMask2D>().padding = new Vector4(0, bottom - bounds.yMin, 0, bounds.yMax - top);
- float rowPitch = Mathf.Max(8, top - bottom + 2);
- foreach (var glyph in glyphs)
- {
- if (glyph.characterIndex >= label.textInfo.characterCount) continue;
- var source = label.textInfo.characterInfo[glyph.characterIndex];
- glyph.origin = new Vector2(source.origin, source.baseLine);
- glyph.pitch = rowPitch;
- ConfigureGlyph(glyph.current, source.pointSize, source.xAdvance - source.origin, glyph.pitch);
- glyph.current.ForceMeshUpdate();
- glyph.currentBaseline = glyph.current.textInfo.characterCount > 0 ? glyph.current.textInfo.characterInfo[0].baseLine : 0;
- glyph.current.rectTransform.anchoredPosition = glyph.origin - Vector2.up * glyph.currentBaseline;
- if (glyph.next)
- {
- ConfigureGlyph(glyph.next, source.pointSize, source.xAdvance - source.origin, glyph.pitch);
- glyph.next.ForceMeshUpdate();
- glyph.nextBaseline = glyph.next.textInfo.characterCount > 0 ? glyph.next.textInfo.characterInfo[0].baseLine : 0;
- }
- }
- }
- void ConfigureGlyph(TMP_Text glyph, float size, float width, float height)
- {
- glyph.font = label.font;
- glyph.fontSharedMaterial = label.fontSharedMaterial;
- glyph.fontStyle = label.fontStyle;
- glyph.fontWeight = label.fontWeight;
- glyph.fontSize = size;
- var rect = glyph.rectTransform;
- rect.anchorMin = rect.anchorMax = viewport.pivot;
- rect.pivot = new Vector2(0, .5f);
- rect.sizeDelta = new Vector2(Mathf.Max(width * 2, size * 2), height);
- }
- void SetLabelAlpha(float alpha)
- {
- var color = visibleColor;
- color.a = alpha;
- label.color = color;
- }
- void RestoreLabel()
- {
- IsRolling = false;
- if (label && hasColor) label.color = visibleColor;
- if (viewport) viewport.gameObject.SetActive(false);
- if (punctuation) punctuation.gameObject.SetActive(false);
- }
- void ClearGlyphs()
- {
- glyphs.Clear();
- ClearChildren(viewport);
- ClearChildren(punctuation);
- }
- void ClearChildren(RectTransform parent)
- {
- if (!parent) return;
- for (int i = parent.childCount - 1; i >= 0; i--)
- {
- var child = parent.GetChild(i).gameObject;
- child.SetActive(false);
- if (Application.isPlaying) Destroy(child); else DestroyImmediate(child);
- }
- parent.gameObject.SetActive(false);
- }
- void OnDisable() { RestoreLabel(); }
- void OnDestroy() { RestoreLabel(); }
- }
- }
|