1
0

StartEndTime.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using Robust.Shared.Timing;
  2. namespace Content.Shared.Timing;
  3. /// <summary>
  4. /// Represents a range of an "action" in time, as start/end times.
  5. /// </summary>
  6. /// <remarks>
  7. /// Positions in time are represented as <see cref="TimeSpan"/>s, usually from <see cref="IGameTiming.CurTime"/>
  8. /// or <see cref="IGameTiming.RealTime"/>.
  9. /// </remarks>
  10. /// <param name="Start">The time the action starts.</param>
  11. /// <param name="End">The time action ends.</param>
  12. [Serializable]
  13. public record struct StartEndTime(TimeSpan Start, TimeSpan End)
  14. {
  15. /// <summary>
  16. /// How long the action takes.
  17. /// </summary>
  18. public TimeSpan Length => End - Start;
  19. /// <summary>
  20. /// Get how far the action has progressed relative to a time value.
  21. /// </summary>
  22. /// <param name="time">The time to get the current progress value for.</param>
  23. /// <param name="clamp">If true, clamp values outside the time range to 0 through 1.</param>
  24. /// <returns>
  25. /// <para>
  26. /// A progress value. Zero means <paramref name="time"/> is at <see cref="Start"/>,
  27. /// one means <paramref name="time"/> is at <see cref="End"/>.
  28. /// </para>
  29. /// <para>
  30. /// This function returns <see cref="float.NaN"/> if <see cref="Start"/> and <see cref="End"/> are identical.
  31. /// </para>
  32. /// </returns>
  33. public float ProgressAt(TimeSpan time, bool clamp = true)
  34. {
  35. var length = Length;
  36. if (length == default)
  37. return float.NaN;
  38. var progress = (float) ((time - Start) / length);
  39. if (clamp)
  40. progress = MathHelper.Clamp01(progress);
  41. return progress;
  42. }
  43. public static StartEndTime FromStartDuration(TimeSpan start, TimeSpan duration)
  44. {
  45. return new StartEndTime(start, start + duration);
  46. }
  47. public static StartEndTime FromStartDuration(TimeSpan start, float durationSeconds)
  48. {
  49. return new StartEndTime(start, start + TimeSpan.FromSeconds(durationSeconds));
  50. }
  51. public static StartEndTime FromCurTime(IGameTiming gameTiming, TimeSpan duration)
  52. {
  53. return FromStartDuration(gameTiming.CurTime, duration);
  54. }
  55. public static StartEndTime FromCurTime(IGameTiming gameTiming, float durationSeconds)
  56. {
  57. return FromStartDuration(gameTiming.CurTime, durationSeconds);
  58. }
  59. }