1 package net.mograsim.logic.core.timeline;
3 import java.util.ArrayList;
5 import java.util.PriorityQueue;
6 import java.util.function.BooleanSupplier;
7 import java.util.function.Consumer;
10 * Orders Events by the time they are due to be executed. Can execute Events individually.
12 * @author Fabian Stemmler
17 private PriorityQueue<InnerEvent> events;
18 private TimeFunction time;
19 private long processedUntil = 0;
20 private long eventCounter = 0;
22 private final List<Consumer<TimelineEvent>> eventAddedListener;
24 public final TimeFunction stepByStepExec = new TimeFunction()
28 public void setTime(long time)
30 processedUntil = time;
36 return processedUntil;
39 public final TimeFunction realTimeExec = new TimeFunction()
41 private long offset = 0;
44 public void setTime(long time)
52 return System.currentTimeMillis() - offset;
55 private boolean isWorking;
58 * Constructs a Timeline object. Per default the time function is set to step by step execution.
60 * @param initCapacity The initial capacity of the event queue.
62 public Timeline(int initCapacity)
64 events = new PriorityQueue<>(initCapacity);
65 eventAddedListener = new ArrayList<>();
66 time = stepByStepExec;
70 * @param timestamp exclusive
71 * @return <code>true</code> if the first event in queue is later than the given timestamp
73 public BooleanSupplier laterThan(long timestamp)
75 return () -> timeCmp(events.peek().getTiming(), timestamp) > 0;
79 * @return <code>true</code> if there is at least one event enqueued. <code>false</code> otherwise
81 public boolean hasNext()
83 return !events.isEmpty();
87 * Executes all events at the next timestamp, at which there are any
89 public void executeNext()
91 InnerEvent first = events.peek();
93 executeUntil(laterThan(first.getTiming()), -1);
97 * Executes all events enqueued in the {@link Timeline}. Use very carefully! Events may generate new events, causing an infinite loop.
99 public void executeAll()
106 * Executes all events until a given condition is met. The simulation process can be constrained by a real world timestamp.
108 * @param condition the condition until which the events are be processed
109 * @param stopMillis the System.currentTimeMillis() when simulation definitely needs to stop. A value of -1 means no timeout.
110 * @return State of the event execution
112 * <code>NOTHING_DONE</code> if the {@link Timeline} was already empty
113 * <code>EXEC_OUT_OF_TIME</code> if the given maximum time was reached
114 * <code>EXEC_UNTIL_CONDITION</code> if the condition was met
115 * <code>EXEC_UNTIL_EMPTY</code> if events were executed until the {@link Timeline} was empty
118 public ExecutionResult executeUntil(BooleanSupplier condition, long stopMillis)
120 if (events.isEmpty())
122 processedUntil = getSimulationTime();
123 return ExecutionResult.NOTHING_DONE;
127 while (hasNext() && !condition.getAsBoolean())
130 synchronized (events)
132 event = events.remove();
134 processedUntil = event.getTiming();
136 // Don't check after every run
137 checkStop = (checkStop + 1) % 10;
138 if (checkStop == 0 && System.currentTimeMillis() >= stopMillis)
141 return ExecutionResult.EXEC_OUT_OF_TIME;
145 processedUntil = getSimulationTime();
146 return hasNext() ? ExecutionResult.EXEC_UNTIL_EMPTY : ExecutionResult.EXEC_UNTIL_CONDITION;
150 * Sets the function, which defines the current simulation time at any time.
152 * @param time The return value of calling this function is the current simulation time.
154 public void setTimeFunction(TimeFunction time)
156 time.setTime(this.time.getTime());
161 * Calculates the current simulation time.
163 * @return The simulation time as defined by the time function.
165 public long getSimulationTime()
167 return isWorking() ? processedUntil : time.getTime();
171 * Retrieves the timestamp of the next event.
173 * @return The timestamp of the next enqueued event, if the {@link Timeline} is not empty, -1 otherwise.
175 public long nextEventTime()
179 return events.peek().getTiming();
183 * Clears the {@link Timeline} of enqueued events.
187 synchronized (events)
191 processedUntil = time.getTime();
195 * Adds a listener, that is called when a {@link TimelineEvent} is added.
197 public void addEventAddedListener(Consumer<TimelineEvent> listener)
199 eventAddedListener.add(listener);
203 * Removes the listener, if possible. It will no longer be called when a {@link TimelineEvent} is added.
205 public void removeEventAddedListener(Consumer<TimelineEvent> listener)
207 eventAddedListener.remove(listener);
211 * Adds an Event to the {@link Timeline}
213 * @param function The {@link TimelineEventHandler} that will be executed, when the {@link InnerEvent} occurs on the timeline.
214 * @param relativeTiming The amount of MI ticks in which the {@link InnerEvent} is called, starting from the current time.
216 public void addEvent(TimelineEventHandler function, int relativeTiming)
218 long timing = getSimulationTime() + relativeTiming;
219 TimelineEvent event = new TimelineEvent(timing);
220 synchronized (events)
222 events.add(new InnerEvent(function, event, eventCounter++));
224 eventAddedListener.forEach(l -> l.accept(event));
228 private void working() { isWorking = true; }
229 private void notWorking() { isWorking = false; }
230 private boolean isWorking() { return isWorking; }
233 private class InnerEvent implements Runnable, Comparable<InnerEvent>
235 private final TimelineEventHandler function;
236 private final TimelineEvent event;
237 private final long id;
240 * Creates an {@link InnerEvent}
242 * @param function {@link TimelineEventHandler} to be executed when the {@link InnerEvent} occurs
243 * @param timing Point in the MI simulation {@link Timeline}, at which the {@link InnerEvent} is executed;
245 InnerEvent(TimelineEventHandler function, TimelineEvent event, long id)
247 this.function = function;
252 public long getTiming()
254 return event.getTiming();
260 function.handle(event);
264 public String toString()
266 return event.toString();
270 public int compareTo(InnerEvent o)
273 return (c1 = timeCmp(getTiming(), o.getTiming())) == 0 ? timeCmp(id, o.id) : c1;
277 public static int timeCmp(long a, long b)
279 return Long.signum(a - b);
283 public String toString()
286 synchronized (events)
288 eventsString = events.toString();
290 return String.format("Simulation time: %s, Last update: %d, Events: %s", getSimulationTime(), processedUntil, eventsString);
293 public static enum ExecutionResult
295 NOTHING_DONE, EXEC_UNTIL_EMPTY, EXEC_UNTIL_CONDITION, EXEC_OUT_OF_TIME
298 public static interface TimeFunction
302 void setTime(long time);
306 * Sets the time of the {@link TimeFunction} to the timestamp of the latest processed event
308 public void synchTime()
310 time.setTime(processedUntil);