Renamed project folders to match the respective project name
[Mograsim.git] / net.mograsim.logic.core / src / net / mograsim / logic / core / timeline / Timeline.java
1 package net.mograsim.logic.core.timeline;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.PriorityQueue;
6 import java.util.function.BooleanSupplier;
7 import java.util.function.Consumer;
8 import java.util.function.LongSupplier;
9
10 /**
11  * Orders Events by the time they are due to be executed. Can execute Events individually.
12  * 
13  * @author Fabian Stemmler
14  *
15  */
16 public class Timeline
17 {
18         private PriorityQueue<InnerEvent> events;
19         private LongSupplier time;
20         private long lastTimeUpdated = 0;
21
22         private final List<Consumer<TimelineEvent>> eventAddedListener;
23
24         public Timeline(int initCapacity)
25         {
26                 events = new PriorityQueue<InnerEvent>(initCapacity);
27
28                 eventAddedListener = new ArrayList<>();
29                 time = () -> lastTimeUpdated;
30         }
31
32         /**
33          * @param timestamp exclusive
34          * @return true if the first event is later than the timestamp
35          */
36         public BooleanSupplier laterThan(long timestamp)
37         {
38                 return () -> timeCmp(events.peek().getTiming(), timestamp) > 0;
39         }
40
41         public boolean hasNext()
42         {
43                 return !events.isEmpty();
44         }
45
46         /**
47          * Executes all events at the next timestamp, at which there are any
48          */
49         public void executeNext()
50         {
51                 InnerEvent first = events.peek();
52                 if (first != null)
53                         executeUntil(laterThan(first.getTiming()), -1);
54         }
55
56         public void executeAll()
57         {
58                 while (hasNext())
59                         executeNext();
60         }
61
62         /**
63          * Executes all events until a given condition is met. The simulation process can be constrained by a real world timestamp.
64          * 
65          * @param condition  the condition until which the events are be processed
66          * @param stopMillis the System.currentTimeMillis() when simulation definitely needs to stop. A value of -1 means no timeout.
67          * @return State of the event execution
68          * @formatter:off
69          * <code>NOTHING_DONE</code> if the {@link Timeline} was already empty
70          * <code>EXEC_OUT_OF_TIME</code> if the given maximum time was reached
71          * <code>EXEC_UNTIL_CONDITION</code> if the condition was met
72          * <code>EXEC_UNTIL_EMPTY</code> if events were executed until the {@link Timeline} was empty
73          * @formatter:on
74          * @author Christian Femers, Fabian Stemmler
75          */
76         public ExecutionResult executeUntil(BooleanSupplier condition, long stopMillis)
77         {
78                 if (events.isEmpty())
79                 {
80                         lastTimeUpdated = getSimulationTime();
81                         return ExecutionResult.NOTHING_DONE;
82                 }
83                 int checkStop = 0;
84                 InnerEvent first = events.peek();
85                 while (hasNext() && !condition.getAsBoolean())
86                 {
87                         events.remove();
88                         lastTimeUpdated = first.getTiming();
89                         first.run();
90                         // Don't check after every run
91                         checkStop = (checkStop + 1) % 10;
92                         if (checkStop == 0 && System.currentTimeMillis() >= stopMillis)
93                                 return ExecutionResult.EXEC_OUT_OF_TIME;
94                         first = events.peek();
95                 }
96                 lastTimeUpdated = getSimulationTime();
97                 return hasNext() ? ExecutionResult.EXEC_UNTIL_EMPTY : ExecutionResult.EXEC_UNTIL_CONDITION;
98         }
99
100         public void setTimeFunction(LongSupplier time)
101         {
102                 this.time = time;
103         }
104
105         public long getSimulationTime()
106         {
107                 return time.getAsLong();
108         }
109
110         public long nextEventTime()
111         {
112                 if (!hasNext())
113                         return -1;
114                 return events.peek().getTiming();
115         }
116
117         public void reset()
118         {
119                 events.clear();
120                 lastTimeUpdated = 0;
121         }
122
123         public void addEventAddedListener(Consumer<TimelineEvent> listener)
124         {
125                 eventAddedListener.add(listener);
126         }
127
128         public void removeEventAddedListener(Consumer<TimelineEvent> listener)
129         {
130                 eventAddedListener.remove(listener);
131         }
132
133         /**
134          * Adds an Event to the {@link Timeline}
135          * 
136          * @param function       The {@link TimelineEventHandler} that will be executed, when the {@link InnerEvent} occurs on the timeline.
137          * @param relativeTiming The amount of MI ticks in which the {@link InnerEvent} is called, starting from the current time.
138          */
139         public void addEvent(TimelineEventHandler function, int relativeTiming)
140         {
141                 long timing = getSimulationTime() + relativeTiming;
142                 TimelineEvent event = new TimelineEvent(timing);
143                 events.add(new InnerEvent(function, event));
144                 eventAddedListener.forEach(l -> l.accept(event));
145         }
146
147         private class InnerEvent implements Runnable, Comparable<InnerEvent>
148         {
149                 private final TimelineEventHandler function;
150                 private final TimelineEvent event;
151
152                 /**
153                  * Creates an {@link InnerEvent}
154                  * 
155                  * @param function {@link TimelineEventHandler} to be executed when the {@link InnerEvent} occurs
156                  * @param timing   Point in the MI simulation {@link Timeline}, at which the {@link InnerEvent} is executed;
157                  */
158                 InnerEvent(TimelineEventHandler function, TimelineEvent event)
159                 {
160                         this.function = function;
161                         this.event = event;
162                 }
163
164                 public long getTiming()
165                 {
166                         return event.getTiming();
167                 }
168
169                 @Override
170                 public void run()
171                 {
172                         function.handle(event);
173                 }
174
175                 @Override
176                 public String toString()
177                 {
178                         return event.toString();
179                 }
180
181                 @Override
182                 public int compareTo(InnerEvent o)
183                 {
184                         return timeCmp(getTiming(), o.getTiming());
185                 }
186         }
187
188         public static int timeCmp(long a, long b)
189         {
190                 return Long.signum(a - b);
191         }
192
193         @Override
194         public String toString()
195         {
196                 return String.format("Simulation time: %s, Last update: %d, Events: %s", getSimulationTime(), lastTimeUpdated, events.toString());
197         }
198
199         public enum ExecutionResult
200         {
201                 NOTHING_DONE, EXEC_UNTIL_EMPTY, EXEC_UNTIL_CONDITION, EXEC_OUT_OF_TIME
202         }
203 }