EventQueue.cs 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System;
  2. using System.Collections.Generic;
  3. namespace sccdlib
  4. {
  5. /// <summary>
  6. /// Abstracting the event Queue. Currently uses a List to store it's content, but could have better performance when built on a priority queue.
  7. /// </summary>
  8. public class EventQueue
  9. {
  10. private class EventQueueEntry
  11. {
  12. double time_offset;
  13. Event e;
  14. public EventQueueEntry(Event e, double time_offset)
  15. {
  16. this.e = e;
  17. this.time_offset = time_offset;
  18. }
  19. public void decreaseTime(double offset)
  20. {
  21. this.time_offset -= offset;
  22. }
  23. public Event getEvent()
  24. {
  25. return this.e;
  26. }
  27. public double getTime ()
  28. {
  29. return this.time_offset;
  30. }
  31. }
  32. List<EventQueueEntry> event_list = new List<EventQueueEntry>();
  33. public void Add (Event e, double time_offset)
  34. {
  35. EventQueueEntry entry = new EventQueueEntry(e,time_offset);
  36. //We maintain a sorted stable list
  37. int insert_index = 0;
  38. for (int index = this.event_list.Count-1; index >= 0; index--)
  39. {
  40. if (this.event_list[index].getTime() <= time_offset)
  41. {
  42. insert_index = index + 1;
  43. break;
  44. }
  45. }
  46. this.event_list.Insert(insert_index, entry);
  47. }
  48. public void decreaseTime(double offset)
  49. {
  50. foreach (EventQueueEntry e in this.event_list)
  51. e.decreaseTime(offset);
  52. }
  53. public bool isEmpty()
  54. {
  55. return this.event_list.Count == 0;
  56. }
  57. /// <summary>
  58. /// Gets the earliest time.
  59. /// </summary>
  60. /// <returns>
  61. /// The earliest time. Positive infinity if no events are present.
  62. /// </returns>
  63. public double getEarliestTime ()
  64. {
  65. if (this.isEmpty())
  66. {
  67. return double.PositiveInfinity;
  68. }
  69. else
  70. {
  71. return this.event_list[0].getTime();
  72. }
  73. }
  74. public List<Event> popDueEvents ()
  75. {
  76. List<Event> result = new List<Event> ();
  77. if (this.isEmpty() || this.event_list[0].getTime() > 0.0)
  78. //There are no events, or the earliest event isn't due, so we can already return an emtpy result
  79. return result;
  80. int index = 0;
  81. while (index < this.event_list.Count && this.event_list[index].getTime() <= 0.0)
  82. {
  83. result.Add(this.event_list[index].getEvent()); //Add all events that are due (offset less than 0) to the result
  84. index++;
  85. }
  86. this.event_list.RemoveRange(0, result.Count);
  87. return result;
  88. }
  89. }
  90. }