Animation.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. using static Unix.Terminal.Curses;
  2. namespace Terminal.Gui.TextEffects;
  3. public enum SyncMetric
  4. {
  5. Distance,
  6. Step
  7. }
  8. public class CharacterVisual
  9. {
  10. public string Symbol { get; set; }
  11. public bool Bold { get; set; }
  12. public bool Dim { get; set; }
  13. public bool Italic { get; set; }
  14. public bool Underline { get; set; }
  15. public bool Blink { get; set; }
  16. public bool Reverse { get; set; }
  17. public bool Hidden { get; set; }
  18. public bool Strike { get; set; }
  19. public Color Color { get; set; }
  20. public string FormattedSymbol { get; private set; }
  21. private string _colorCode;
  22. public CharacterVisual (string symbol, bool bold = false, bool dim = false, bool italic = false, bool underline = false, bool blink = false, bool reverse = false, bool hidden = false, bool strike = false, Color color = null, string colorCode = null)
  23. {
  24. Symbol = symbol;
  25. Bold = bold;
  26. Dim = dim;
  27. Italic = italic;
  28. Underline = underline;
  29. Blink = blink;
  30. Reverse = reverse;
  31. Hidden = hidden;
  32. Strike = strike;
  33. Color = color;
  34. _colorCode = colorCode;
  35. FormattedSymbol = FormatSymbol ();
  36. }
  37. private string FormatSymbol ()
  38. {
  39. string formattingString = "";
  40. if (Bold) formattingString += Ansitools.ApplyBold ();
  41. if (Italic) formattingString += Ansitools.ApplyItalic ();
  42. if (Underline) formattingString += Ansitools.ApplyUnderline ();
  43. if (Blink) formattingString += Ansitools.ApplyBlink ();
  44. if (Reverse) formattingString += Ansitools.ApplyReverse ();
  45. if (Hidden) formattingString += Ansitools.ApplyHidden ();
  46. if (Strike) formattingString += Ansitools.ApplyStrikethrough ();
  47. if (_colorCode != null) formattingString += Colorterm.Fg (_colorCode);
  48. return $"{formattingString}{Symbol}{(formattingString != "" ? Ansitools.ResetAll () : "")}";
  49. }
  50. public void DisableModes ()
  51. {
  52. Bold = false;
  53. Dim = false;
  54. Italic = false;
  55. Underline = false;
  56. Blink = false;
  57. Reverse = false;
  58. Hidden = false;
  59. Strike = false;
  60. }
  61. }
  62. public class Frame
  63. {
  64. public CharacterVisual CharacterVisual { get; }
  65. public int Duration { get; }
  66. public int TicksElapsed { get; set; }
  67. public Frame (CharacterVisual characterVisual, int duration)
  68. {
  69. CharacterVisual = characterVisual;
  70. Duration = duration;
  71. TicksElapsed = 0;
  72. }
  73. public void IncrementTicks ()
  74. {
  75. TicksElapsed++;
  76. }
  77. }
  78. public class Scene
  79. {
  80. public string SceneId { get; }
  81. public bool IsLooping { get; }
  82. public SyncMetric? Sync { get; }
  83. public EasingFunction Ease { get; }
  84. public bool NoColor { get; set; }
  85. public bool UseXtermColors { get; set; }
  86. public List<Frame> Frames { get; } = new List<Frame> ();
  87. public List<Frame> PlayedFrames { get; } = new List<Frame> ();
  88. public Dictionary<int, Frame> FrameIndexMap { get; } = new Dictionary<int, Frame> ();
  89. public int EasingTotalSteps { get; private set; }
  90. public int EasingCurrentStep { get; private set; }
  91. public static Dictionary<string, int> XtermColorMap { get; } = new Dictionary<string, int> ();
  92. public Scene (string sceneId, bool isLooping = false, SyncMetric? sync = null, EasingFunction ease = null, bool noColor = false, bool useXtermColors = false)
  93. {
  94. SceneId = sceneId;
  95. IsLooping = isLooping;
  96. Sync = sync;
  97. Ease = ease;
  98. NoColor = noColor;
  99. UseXtermColors = useXtermColors;
  100. }
  101. public void AddFrame (string symbol, int duration, Color color = null, bool bold = false, bool dim = false, bool italic = false, bool underline = false, bool blink = false, bool reverse = false, bool hidden = false, bool strike = false)
  102. {
  103. string charVisColor = null;
  104. if (color != null)
  105. {
  106. if (NoColor)
  107. {
  108. charVisColor = null;
  109. }
  110. else if (UseXtermColors)
  111. {
  112. if (color.XtermColor != null)
  113. {
  114. charVisColor = color.XtermColor;
  115. }
  116. else if (XtermColorMap.ContainsKey (color.RgbColor))
  117. {
  118. // Build error says Error CS0029 Cannot implicitly convert type 'int' to 'string' Terminal.Gui (net8.0) D:\Repos\TerminalGuiDesigner\gui.cs\Terminal.Gui\TextEffects\Animation.cs 120 Active
  119. charVisColor = XtermColorMap [color.RgbColor].ToString ();
  120. }
  121. else
  122. {
  123. var xtermColor = Hexterm.HexToXterm (color.RgbColor);
  124. XtermColorMap [color.RgbColor] = int.Parse (xtermColor);
  125. charVisColor = xtermColor;
  126. }
  127. }
  128. else
  129. {
  130. charVisColor = color.RgbColor;
  131. }
  132. }
  133. if (duration < 1)
  134. {
  135. throw new ArgumentException ("duration must be greater than 0");
  136. }
  137. var charVis = new CharacterVisual (symbol, bold, dim, italic, underline, blink, reverse, hidden, strike, color, charVisColor);
  138. var frame = new Frame (charVis, duration);
  139. Frames.Add (frame);
  140. for (int i = 0; i < frame.Duration; i++)
  141. {
  142. FrameIndexMap [EasingTotalSteps] = frame;
  143. EasingTotalSteps++;
  144. }
  145. }
  146. public CharacterVisual Activate ()
  147. {
  148. if (Frames.Count > 0)
  149. {
  150. return Frames [0].CharacterVisual;
  151. }
  152. else
  153. {
  154. throw new InvalidOperationException ("Scene has no frames.");
  155. }
  156. }
  157. public CharacterVisual GetNextVisual ()
  158. {
  159. var currentFrame = Frames [0];
  160. var nextVisual = currentFrame.CharacterVisual;
  161. currentFrame.IncrementTicks ();
  162. if (currentFrame.TicksElapsed == currentFrame.Duration)
  163. {
  164. currentFrame.TicksElapsed = 0;
  165. PlayedFrames.Add (Frames [0]);
  166. Frames.RemoveAt (0);
  167. if (IsLooping && Frames.Count == 0)
  168. {
  169. Frames.AddRange (PlayedFrames);
  170. PlayedFrames.Clear ();
  171. }
  172. }
  173. return nextVisual;
  174. }
  175. public void ApplyGradientToSymbols (Gradient gradient, IList<string> symbols, int duration)
  176. {
  177. int lastIndex = 0;
  178. for (int symbolIndex = 0; symbolIndex < symbols.Count; symbolIndex++)
  179. {
  180. var symbol = symbols [symbolIndex];
  181. double symbolProgress = (symbolIndex + 1) / (double)symbols.Count;
  182. int gradientIndex = (int)(symbolProgress * gradient.Spectrum.Count);
  183. foreach (var color in gradient.Spectrum.GetRange (lastIndex, Math.Max (gradientIndex - lastIndex, 1)))
  184. {
  185. AddFrame (symbol, duration, color);
  186. }
  187. lastIndex = gradientIndex;
  188. }
  189. }
  190. public void ResetScene ()
  191. {
  192. foreach (var sequence in Frames)
  193. {
  194. sequence.TicksElapsed = 0;
  195. PlayedFrames.Add (sequence);
  196. }
  197. Frames.Clear ();
  198. Frames.AddRange (PlayedFrames);
  199. PlayedFrames.Clear ();
  200. }
  201. public override bool Equals (object obj)
  202. {
  203. if (obj is Scene other)
  204. {
  205. return SceneId == other.SceneId;
  206. }
  207. return false;
  208. }
  209. public override int GetHashCode ()
  210. {
  211. return SceneId.GetHashCode ();
  212. }
  213. }
  214. public class Animation
  215. {
  216. public Dictionary<string, Scene> Scenes { get; } = new Dictionary<string, Scene> ();
  217. public EffectCharacter Character { get; }
  218. public Scene ActiveScene { get; private set; }
  219. public bool UseXtermColors { get; set; } = false;
  220. public bool NoColor { get; set; } = false;
  221. public Dictionary<string, int> XtermColorMap { get; } = new Dictionary<string, int> ();
  222. public int ActiveSceneCurrentStep { get; private set; } = 0;
  223. public CharacterVisual CurrentCharacterVisual { get; private set; }
  224. public Animation (EffectCharacter character)
  225. {
  226. Character = character;
  227. CurrentCharacterVisual = new CharacterVisual (character.InputSymbol);
  228. }
  229. public Scene NewScene (bool isLooping = false, SyncMetric? sync = null, EasingFunction ease = null, string id = "")
  230. {
  231. if (string.IsNullOrEmpty (id))
  232. {
  233. bool foundUnique = false;
  234. int currentId = Scenes.Count;
  235. while (!foundUnique)
  236. {
  237. id = $"{Scenes.Count}";
  238. if (!Scenes.ContainsKey (id))
  239. {
  240. foundUnique = true;
  241. }
  242. else
  243. {
  244. currentId++;
  245. }
  246. }
  247. }
  248. var newScene = new Scene (id, isLooping, sync, ease);
  249. Scenes [id] = newScene;
  250. newScene.NoColor = NoColor;
  251. newScene.UseXtermColors = UseXtermColors;
  252. return newScene;
  253. }
  254. public Scene QueryScene (string sceneId)
  255. {
  256. if (!Scenes.TryGetValue (sceneId, out var scene))
  257. {
  258. throw new ArgumentException ($"Scene {sceneId} does not exist.");
  259. }
  260. return scene;
  261. }
  262. public bool ActiveSceneIsComplete ()
  263. {
  264. if (ActiveScene == null)
  265. {
  266. return true;
  267. }
  268. return ActiveScene.Frames.Count == 0 && !ActiveScene.IsLooping;
  269. }
  270. public void SetAppearance (string symbol, Color? color = null)
  271. {
  272. string charVisColor = null;
  273. if (color != null)
  274. {
  275. if (NoColor)
  276. {
  277. charVisColor = null;
  278. }
  279. else if (UseXtermColors)
  280. {
  281. charVisColor = color.XtermColor;
  282. }
  283. else
  284. {
  285. charVisColor = color.RgbColor;
  286. }
  287. }
  288. CurrentCharacterVisual = new CharacterVisual (symbol, color: color, _colorCode: charVisColor);
  289. }
  290. public static Color RandomColor ()
  291. {
  292. var random = new Random ();
  293. var colorHex = random.Next (0, 0xFFFFFF).ToString ("X6");
  294. return new Color (colorHex);
  295. }
  296. public static Color AdjustColorBrightness (Color color, float brightness)
  297. {
  298. float HueToRgb (float p, float q, float t)
  299. {
  300. if (t < 0) t += 1;
  301. if (t > 1) t -= 1;
  302. if (t < 1 / 6f) return p + (q - p) * 6 * t;
  303. if (t < 1 / 2f) return q;
  304. if (t < 2 / 3f) return p + (q - p) * (2 / 3f - t) * 6;
  305. return p;
  306. }
  307. float r = int.Parse (color.RgbColor.Substring (0, 2), System.Globalization.NumberStyles.HexNumber) / 255f;
  308. float g = int.Parse (color.RgbColor.Substring (2, 2), System.Globalization.NumberStyles.HexNumber) / 255f;
  309. float b = int.Parse (color.RgbColor.Substring (4, 2), System.Globalization.NumberStyles.HexNumber) / 255f;
  310. float max = Math.Max (r, Math.Max (g, b));
  311. float min = Math.Min (r, Math.Min (g, b));
  312. float h, s, l = (max + min) / 2f;
  313. if (max == min)
  314. {
  315. h = s = 0; // achromatic
  316. }
  317. else
  318. {
  319. float d = max - min;
  320. s = l > 0.5f ? d / (2f - max - min) : d / (max + min);
  321. if (max == r)
  322. {
  323. h = (g - b) / d + (g < b ? 6 : 0);
  324. }
  325. else if (max == g)
  326. {
  327. h = (b - r) / d + 2;
  328. }
  329. else
  330. {
  331. h = (r - g) / d + 4;
  332. }
  333. h /= 6;
  334. }
  335. l = Math.Max (Math.Min (l * brightness, 1), 0);
  336. if (s == 0)
  337. {
  338. r = g = b = l; // achromatic
  339. }
  340. else
  341. {
  342. float q = l < 0.5f ? l * (1 + s) : l + s - l * s;
  343. float p = 2 * l - q;
  344. r = HueToRgb (p, q, h + 1 / 3f);
  345. g = HueToRgb (p, q, h);
  346. b = HueToRgb (p, q, h - 1 / 3f);
  347. }
  348. var adjustedColor = $"{(int)(r * 255):X2}{(int)(g * 255):X2}{(int)(b * 255):X2}";
  349. return new Color (adjustedColor);
  350. }
  351. private float EaseAnimation (EasingFunction easingFunc)
  352. {
  353. if (ActiveScene == null)
  354. {
  355. return 0;
  356. }
  357. float elapsedStepRatio = ActiveScene.EasingCurrentStep / (float)ActiveScene.EasingTotalSteps;
  358. return easingFunc (elapsedStepRatio);
  359. }
  360. public void StepAnimation ()
  361. {
  362. if (ActiveScene != null && ActiveScene.Frames.Count > 0)
  363. {
  364. if (ActiveScene.Sync != null)
  365. {
  366. if (Character.Motion.ActivePath != null)
  367. {
  368. int sequenceIndex = 0;
  369. if (ActiveScene.Sync == SyncMetric.Step)
  370. {
  371. sequenceIndex = (int)Math.Round ((ActiveScene.Frames.Count - 1) *
  372. (Math.Max (Character.Motion.ActivePath.CurrentStep, 1) /
  373. (float)Math.Max (Character.Motion.ActivePath.MaxSteps, 1)));
  374. }
  375. else if (ActiveScene.Sync == SyncMetric.Distance)
  376. {
  377. sequenceIndex = (int)Math.Round ((ActiveScene.Frames.Count - 1) *
  378. (Math.Max (Math.Max (Character.Motion.ActivePath.TotalDistance, 1) -
  379. Math.Max (Character.Motion.ActivePath.TotalDistance -
  380. Character.Motion.ActivePath.LastDistanceReached, 1), 1) /
  381. (float)Math.Max (Character.Motion.ActivePath.TotalDistance, 1)));
  382. }
  383. try
  384. {
  385. CurrentCharacterVisual = ActiveScene.Frames [sequenceIndex].CharacterVisual;
  386. }
  387. catch (IndexOutOfRangeException)
  388. {
  389. CurrentCharacterVisual = ActiveScene.Frames [^1].CharacterVisual;
  390. }
  391. }
  392. else
  393. {
  394. CurrentCharacterVisual = ActiveScene.Frames [^1].CharacterVisual;
  395. ActiveScene.PlayedFrames.AddRange (ActiveScene.Frames);
  396. ActiveScene.Frames.Clear ();
  397. }
  398. }
  399. else if (ActiveScene.Ease != null)
  400. {
  401. float easingFactor = EaseAnimation (ActiveScene.Ease);
  402. int frameIndex = (int)Math.Round (easingFactor * Math.Max (ActiveScene.EasingTotalSteps - 1, 0));
  403. frameIndex = Math.Max (Math.Min (frameIndex, ActiveScene.EasingTotalSteps - 1), 0);
  404. Frame frame = ActiveScene.FrameIndexMap [frameIndex];
  405. CurrentCharacterVisual = frame.CharacterVisual;
  406. ActiveScene.EasingCurrentStep++;
  407. if (ActiveScene.EasingCurrentStep == ActiveScene.EasingTotalSteps)
  408. {
  409. if (ActiveScene.IsLooping)
  410. {
  411. ActiveScene.EasingCurrentStep = 0;
  412. }
  413. else
  414. {
  415. ActiveScene.PlayedFrames.AddRange (ActiveScene.Frames);
  416. ActiveScene.Frames.Clear ();
  417. }
  418. }
  419. }
  420. else
  421. {
  422. CurrentCharacterVisual = ActiveScene.GetNextVisual ();
  423. }
  424. if (ActiveSceneIsComplete ())
  425. {
  426. var completedScene = ActiveScene;
  427. if (!ActiveScene.IsLooping)
  428. {
  429. ActiveScene.ResetScene ();
  430. ActiveScene = null;
  431. }
  432. Character.EventHandler.HandleEvent (Event.SceneComplete, completedScene);
  433. }
  434. }
  435. }
  436. public void ActivateScene (Scene scene)
  437. {
  438. ActiveScene = scene;
  439. ActiveSceneCurrentStep = 0;
  440. CurrentCharacterVisual = ActiveScene.Activate ();
  441. Character.EventHandler.HandleEvent (Event.SceneActivated, scene);
  442. }
  443. public void DeactivateScene (Scene scene)
  444. {
  445. if (ActiveScene == scene)
  446. {
  447. ActiveScene = null;
  448. }
  449. }
  450. }
  451. public class EffectCharacter
  452. {
  453. public string InputSymbol { get; }
  454. public CharacterVisual CharacterVisual { get; set; }
  455. public Animation Animation { get; set; }
  456. public EffectCharacter (string inputSymbol)
  457. {
  458. InputSymbol = inputSymbol;
  459. CharacterVisual = new CharacterVisual (inputSymbol);
  460. Animation = new Animation (this);
  461. }
  462. public void Animate (string sceneId)
  463. {
  464. Animation.ActivateScene (sceneId);
  465. Animation.IncrementScene ();
  466. CharacterVisual = Animation.CurrentCharacterVisual;
  467. }
  468. public void ResetEffects ()
  469. {
  470. CharacterVisual.DisableModes ();
  471. }
  472. }
  473. public class Color
  474. {
  475. public string RgbColor { get; }
  476. public string XtermColor { get; }
  477. public Color (string rgbColor, string xtermColor)
  478. {
  479. RgbColor = rgbColor;
  480. XtermColor = xtermColor;
  481. }
  482. }
  483. public class Gradient
  484. {
  485. public List<Color> Spectrum { get; }
  486. public Gradient (List<Color> spectrum)
  487. {
  488. Spectrum = spectrum;
  489. }
  490. }
  491. // Dummy classes for Ansitools, Colorterm, and Hexterm as placeholders
  492. public static class Ansitools
  493. {
  494. public static string ApplyBold () => "\x1b[1m";
  495. public static string ApplyItalic () => "\x1b[3m";
  496. public static string ApplyUnderline () => "\x1b[4m";
  497. public static string ApplyBlink () => "\x1b[5m";
  498. public static string ApplyReverse () => "\x1b[7m";
  499. public static string ApplyHidden () => "\x1b[8m";
  500. public static string ApplyStrikethrough () => "\x1b[9m";
  501. public static string ResetAll () => "\x1b[0m";
  502. }
  503. public static class Colorterm
  504. {
  505. public static string Fg (string colorCode) => $"\x1b[38;5;{colorCode}m";
  506. }
  507. public static class Hexterm
  508. {
  509. public static string HexToXterm (string hex)
  510. {
  511. // Convert hex color to xterm color code (0-255)
  512. return "15"; // Example output
  513. }
  514. }