RuntimeClassBase.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. namespace sccdlib
  4. {
  5. public abstract class RuntimeClassBase
  6. {
  7. protected bool active = false;
  8. protected bool state_changed = false;
  9. protected EventQueue events = new EventQueue();
  10. protected ControllerBase controller;
  11. protected ObjectManagerBase object_manager;
  12. protected Dictionary<int,double> timers = null;
  13. public RuntimeClassBase ()
  14. {
  15. }
  16. public void addEvent (Event input_event, double time_offset = 0.0)
  17. {
  18. this.events.Add (input_event, time_offset);
  19. }
  20. public double getEarliestEventTime ()
  21. {
  22. if (this.timers != null)
  23. {
  24. double smallest_timer_value = double.PositiveInfinity;
  25. foreach (double timer_value in this.timers.Values)
  26. {
  27. if (timer_value < smallest_timer_value)
  28. smallest_timer_value = timer_value;
  29. }
  30. return Math.Min(this.events.getEarliestTime(), smallest_timer_value);
  31. }
  32. return this.events.getEarliestTime();
  33. }
  34. /// <summary>
  35. /// Execute statechart
  36. /// </summary>
  37. /// <param name='delta'>
  38. /// Time passed since last step.
  39. /// </param>
  40. public void step(double delta)
  41. {
  42. if (!this.active)
  43. return;
  44. this.events.decreaseTime(delta);
  45. if (this.timers != null && this.timers.Count > 0)
  46. {
  47. var next_timers = new Dictionary<int,double>();
  48. foreach(KeyValuePair<int,double> pair in this.timers)
  49. {
  50. double new_time = pair.Value - delta;
  51. if (new_time <= 0.0)
  52. this.addEvent (new Event("_" + pair.Key + "after"), new_time);
  53. else
  54. next_timers[pair.Key] = new_time;
  55. }
  56. this.timers = next_timers;
  57. }
  58. this.microstep();
  59. while (this.state_changed)
  60. this.microstep();
  61. }
  62. private void microstep ()
  63. {
  64. List<Event> due = this.events.popDueEvents();
  65. if (due.Count == 0) {
  66. this.transition ();
  67. } else {
  68. foreach (Event e in due)
  69. {
  70. this.transition(e);
  71. }
  72. }
  73. }
  74. protected abstract void transition (Event e = null);
  75. public virtual void start ()
  76. {
  77. this.active = true;
  78. }
  79. }
  80. }