RollingCounter.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. using System;
  2. using System.Collections.Generic;
  3. using TMPro;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. namespace Fateforge
  7. {
  8. // Driven by the presentation timeline so pause, speed and cancellation share one clock.
  9. [DisallowMultipleComponent]
  10. public sealed class RollingCounter : MonoBehaviour
  11. {
  12. sealed class Glyph
  13. {
  14. public int characterIndex, startDigit, steps, digitOrder;
  15. public bool numeric;
  16. public TMP_Text current, next;
  17. public Vector2 origin;
  18. public float currentBaseline, nextBaseline, pitch;
  19. }
  20. readonly List<Glyph> glyphs = new List<Glyph>();
  21. static readonly string[] DigitText = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
  22. TMP_Text label;
  23. RectTransform viewport, punctuation;
  24. Color visibleColor;
  25. bool hasColor, multiplier;
  26. string targetText = "";
  27. Vector2 measuredSize;
  28. float measuredFontSize;
  29. int digitCount;
  30. public bool IsRolling { get; private set; }
  31. public static RollingCounter Attach(TMP_Text target)
  32. {
  33. if (!target) return null;
  34. var counter = target.GetComponent<RollingCounter>();
  35. if (!counter)
  36. {
  37. counter = target.gameObject.AddComponent<RollingCounter>();
  38. counter.multiplier = target.text.IndexOf('.') >= 0;
  39. }
  40. counter.label = target;
  41. return counter;
  42. }
  43. public void Begin(double from, double to, bool multiplier)
  44. {
  45. this.multiplier = multiplier;
  46. BeginRoll(Format(from), Format(to), from != to);
  47. }
  48. public void Begin(long from, long to, string prefix = "")
  49. {
  50. multiplier = false;
  51. BeginRoll(English.Number(from), English.Number(to), from != to, prefix);
  52. }
  53. void BeginRoll(string from, string to, bool changed, string prefix = "")
  54. {
  55. if (!label) label = GetComponent<TMP_Text>();
  56. if (!label) return;
  57. if (IsRolling) RestoreLabel();
  58. visibleColor = label.color;
  59. hasColor = true;
  60. targetText = prefix + to;
  61. // Keep the real label at the final value for layout and accessibility.
  62. label.text = targetText;
  63. ClearGlyphs();
  64. if (!changed || to.Length > 32 || !label.gameObject.activeInHierarchy)
  65. {
  66. IsRolling = false;
  67. return;
  68. }
  69. EnsureViewport();
  70. viewport.gameObject.SetActive(true);
  71. punctuation.gameObject.SetActive(true);
  72. Canvas.ForceUpdateCanvases();
  73. label.ForceMeshUpdate();
  74. var startingDigits = Digits(from);
  75. digitCount = Digits(to).Length;
  76. int digitOrder = 0;
  77. for (int i = 0; i < targetText.Length; i++)
  78. {
  79. char character = targetText[i];
  80. bool numeric = i >= prefix.Length && character >= '0' && character <= '9';
  81. int sourceIndex = startingDigits.Length - digitCount + digitOrder;
  82. int first = numeric && sourceIndex >= 0 ? startingDigits[sourceIndex] - '0' : 0;
  83. int final = numeric ? character - '0' : 0;
  84. var glyph = new Glyph
  85. {
  86. characterIndex = i,
  87. numeric = numeric,
  88. digitOrder = digitOrder,
  89. startDigit = first,
  90. steps = numeric ? (final - first + 10) % 10 + 10 : 0,
  91. current = MakeText(numeric ? DigitText[first] : character.ToString(), numeric)
  92. };
  93. if (numeric)
  94. {
  95. glyph.next = MakeText(DigitText[(first + 1) % 10]);
  96. digitOrder++;
  97. }
  98. glyphs.Add(glyph);
  99. }
  100. IsRolling = true;
  101. Measure();
  102. SetLabelAlpha(0);
  103. Sample(0);
  104. }
  105. public void Sample(float normalizedProgress)
  106. {
  107. if (!IsRolling || !label) return;
  108. float progress = float.IsNaN(normalizedProgress) ? 0 : Mathf.Clamp01(normalizedProgress);
  109. if (progress >= 1)
  110. {
  111. Finish();
  112. return;
  113. }
  114. if (measuredSize != label.rectTransform.rect.size || !Mathf.Approximately(measuredFontSize, label.fontSize))
  115. Measure();
  116. foreach (var glyph in glyphs)
  117. {
  118. if (!glyph.numeric) continue;
  119. // Higher digits settle first; units retain the final, shorter roll.
  120. float end = digitCount <= 1 ? 1 : Mathf.Lerp(.76f, 1, glyph.digitOrder / (float)(digitCount - 1));
  121. float u = Mathf.Clamp01(progress / end);
  122. float travel = glyph.steps * (1 - Mathf.Pow(1 - u, 3));
  123. int whole = Mathf.FloorToInt(travel + .00001f);
  124. float fraction = Mathf.Clamp01(travel - whole);
  125. int digit = (glyph.startDigit + whole) % 10;
  126. glyph.current.text = DigitText[digit];
  127. glyph.next.text = DigitText[(digit + 1) % 10];
  128. // The outgoing digit drops while its successor enters from above.
  129. glyph.current.rectTransform.anchoredPosition = glyph.origin + Vector2.up * (-glyph.currentBaseline - fraction * glyph.pitch);
  130. glyph.next.rectTransform.anchoredPosition = glyph.origin + Vector2.up * (-glyph.nextBaseline + (1 - fraction) * glyph.pitch);
  131. }
  132. }
  133. public void Finish()
  134. {
  135. if (!label) return;
  136. label.text = targetText;
  137. RestoreLabel();
  138. }
  139. public void Cancel(double displayedValue)
  140. {
  141. if (!label) label = GetComponent<TMP_Text>();
  142. if (!label) return;
  143. targetText = Format(displayedValue);
  144. label.text = targetText;
  145. RestoreLabel();
  146. }
  147. string Format(double value)
  148. {
  149. if (double.IsNaN(value) || double.IsInfinity(value)) value = 0;
  150. return multiplier ? English.Multiplier(value) : English.Number(value);
  151. }
  152. static string Digits(string text)
  153. {
  154. var result = new System.Text.StringBuilder(text.Length);
  155. foreach (char character in text) if (character >= '0' && character <= '9') result.Append(character);
  156. return result.ToString();
  157. }
  158. void EnsureViewport()
  159. {
  160. if (viewport) return;
  161. viewport = new GameObject("RollingDigits", typeof(RectTransform), typeof(RectMask2D)).GetComponent<RectTransform>();
  162. viewport.SetParent(label.transform, false);
  163. viewport.pivot = label.rectTransform.pivot;
  164. viewport.anchorMin = Vector2.zero;
  165. viewport.anchorMax = Vector2.one;
  166. viewport.offsetMin = viewport.offsetMax = Vector2.zero;
  167. punctuation = new GameObject("CounterPunctuation", typeof(RectTransform)).GetComponent<RectTransform>();
  168. punctuation.SetParent(label.transform, false);
  169. punctuation.pivot = label.rectTransform.pivot;
  170. punctuation.anchorMin = Vector2.zero;
  171. punctuation.anchorMax = Vector2.one;
  172. punctuation.offsetMin = punctuation.offsetMax = Vector2.zero;
  173. }
  174. TMP_Text MakeText(string text, bool numeric = true)
  175. {
  176. var node = new GameObject("CounterGlyph", typeof(RectTransform), typeof(TextMeshProUGUI));
  177. node.transform.SetParent(numeric ? viewport : punctuation, false);
  178. var result = node.GetComponent<TextMeshProUGUI>();
  179. result.text = text;
  180. result.raycastTarget = false;
  181. result.enableAutoSizing = false;
  182. result.textWrappingMode = TextWrappingModes.NoWrap;
  183. result.overflowMode = TextOverflowModes.Overflow;
  184. result.alignment = TextAlignmentOptions.BaselineLeft;
  185. result.margin = Vector4.zero;
  186. result.color = visibleColor;
  187. return result;
  188. }
  189. void Measure()
  190. {
  191. label.ForceMeshUpdate();
  192. measuredSize = label.rectTransform.rect.size;
  193. measuredFontSize = label.fontSize;
  194. viewport.pivot = label.rectTransform.pivot;
  195. punctuation.pivot = label.rectTransform.pivot;
  196. float bottom = float.PositiveInfinity, top = float.NegativeInfinity;
  197. for (int i = 0; i < label.textInfo.characterCount; i++)
  198. {
  199. var character = label.textInfo.characterInfo[i];
  200. // Comma descenders must not enlarge the moving digit window.
  201. // Punctuation stays stationary beside that window.
  202. if (!character.isVisible || character.character < '0' || character.character > '9') continue;
  203. if (character.textElement != null && character.textElement.glyph != null)
  204. {
  205. var metrics = character.textElement.glyph.metrics;
  206. float glyphTop = character.baseLine + metrics.horizontalBearingY * character.scale;
  207. top = Mathf.Max(top, glyphTop);
  208. bottom = Mathf.Min(bottom, glyphTop - metrics.height * character.scale);
  209. }
  210. else
  211. {
  212. top = Mathf.Max(top, character.ascender);
  213. bottom = Mathf.Min(bottom, character.descender);
  214. }
  215. }
  216. var bounds = label.rectTransform.rect;
  217. if (float.IsInfinity(bottom)) { bottom = bounds.yMin; top = bounds.yMax; }
  218. bottom = Mathf.Max(bounds.yMin, bottom - 2);
  219. top = Mathf.Min(bounds.yMax, top + 2);
  220. // Padding is left/bottom/right/top. Keep the original coordinate origin,
  221. // while clipping to the single visible number row rather than its label box.
  222. viewport.GetComponent<RectMask2D>().padding = new Vector4(0, bottom - bounds.yMin, 0, bounds.yMax - top);
  223. float rowPitch = Mathf.Max(8, top - bottom + 2);
  224. foreach (var glyph in glyphs)
  225. {
  226. if (glyph.characterIndex >= label.textInfo.characterCount) continue;
  227. var source = label.textInfo.characterInfo[glyph.characterIndex];
  228. glyph.origin = new Vector2(source.origin, source.baseLine);
  229. glyph.pitch = rowPitch;
  230. ConfigureGlyph(glyph.current, source.pointSize, source.xAdvance - source.origin, glyph.pitch);
  231. glyph.current.ForceMeshUpdate();
  232. glyph.currentBaseline = glyph.current.textInfo.characterCount > 0 ? glyph.current.textInfo.characterInfo[0].baseLine : 0;
  233. glyph.current.rectTransform.anchoredPosition = glyph.origin - Vector2.up * glyph.currentBaseline;
  234. if (glyph.next)
  235. {
  236. ConfigureGlyph(glyph.next, source.pointSize, source.xAdvance - source.origin, glyph.pitch);
  237. glyph.next.ForceMeshUpdate();
  238. glyph.nextBaseline = glyph.next.textInfo.characterCount > 0 ? glyph.next.textInfo.characterInfo[0].baseLine : 0;
  239. }
  240. }
  241. }
  242. void ConfigureGlyph(TMP_Text glyph, float size, float width, float height)
  243. {
  244. glyph.font = label.font;
  245. glyph.fontSharedMaterial = label.fontSharedMaterial;
  246. glyph.fontStyle = label.fontStyle;
  247. glyph.fontWeight = label.fontWeight;
  248. glyph.fontSize = size;
  249. var rect = glyph.rectTransform;
  250. rect.anchorMin = rect.anchorMax = viewport.pivot;
  251. rect.pivot = new Vector2(0, .5f);
  252. rect.sizeDelta = new Vector2(Mathf.Max(width * 2, size * 2), height);
  253. }
  254. void SetLabelAlpha(float alpha)
  255. {
  256. var color = visibleColor;
  257. color.a = alpha;
  258. label.color = color;
  259. }
  260. void RestoreLabel()
  261. {
  262. IsRolling = false;
  263. if (label && hasColor) label.color = visibleColor;
  264. if (viewport) viewport.gameObject.SetActive(false);
  265. if (punctuation) punctuation.gameObject.SetActive(false);
  266. }
  267. void ClearGlyphs()
  268. {
  269. glyphs.Clear();
  270. ClearChildren(viewport);
  271. ClearChildren(punctuation);
  272. }
  273. void ClearChildren(RectTransform parent)
  274. {
  275. if (!parent) return;
  276. for (int i = parent.childCount - 1; i >= 0; i--)
  277. {
  278. var child = parent.GetChild(i).gameObject;
  279. child.SetActive(false);
  280. if (Application.isPlaying) Destroy(child); else DestroyImmediate(child);
  281. }
  282. parent.gameObject.SetActive(false);
  283. }
  284. void OnDisable() { RestoreLabel(); }
  285. void OnDestroy() { RestoreLabel(); }
  286. }
  287. }