1 package org.simantics.simulation.sequences.action;
3 import java.util.ArrayList;
4 import java.util.Collections;
6 import java.util.PriorityQueue;
8 import org.simantics.scl.runtime.SCLContext;
9 import org.simantics.scl.runtime.function.Function1;
10 import org.simantics.scl.runtime.tuple.Tuple0;
12 public abstract class AbstractActionContext implements ActionContext {
13 public static final double TIME_TOLERANCE = 1e-6;
16 volatile boolean stopped;
17 ArrayList<Function1<Tuple0, Object>> scheduledNow = new ArrayList<Function1<Tuple0, Object>>();
18 ArrayList<Function1<Tuple0, Object>> scheduledNextStep = new ArrayList<Function1<Tuple0, Object>>();
19 PriorityQueue<Task> scheduledAt = new PriorityQueue<Task>();
21 public List<Exception> exceptions;
23 private static class Task implements Comparable<Task> {
25 final Function1<Tuple0, Object> continuation;
27 public Task(double time, Function1<Tuple0, Object> continuation) {
29 this.continuation = continuation;
33 public int compareTo(Task o) {
34 return Double.compare(time, o.time);
39 public double time() {
44 public void scheduleNow(Function1<Tuple0, Object> continuation) {
45 scheduledNow.add(continuation);
49 public void scheduleNextStep(Function1<Tuple0, Object> continuation) {
50 scheduledNextStep.add(continuation);
54 public void scheduleAt(double time, Function1<Tuple0, Object> continuation) {
55 if(time <= currentTime)
56 scheduleNow(continuation);
58 scheduledAt.add(new Task(time, continuation));
66 public boolean isStopped() {
68 return stopped || (scheduledNextStep.isEmpty() && scheduledAt.isEmpty());
72 public double handleStep(double currentTime) {
74 this.currentTime = currentTime;
76 ArrayList<Function1<Tuple0, Object>> temp = scheduledNow;
77 scheduledNow = scheduledNextStep;
78 scheduledNextStep = temp;
79 Collections.reverse(scheduledNow);
82 SCLContext context = SCLContext.getCurrent();
83 Object oldActionContext = context.put("sequenceAction", this);
85 Task firstTask = scheduledAt.peek();
87 while(!scheduledNow.isEmpty()) {
89 Function1<Tuple0, Object> currentContinuation = scheduledNow.remove(scheduledNow.size()-1);
90 currentContinuation.apply(Tuple0.INSTANCE);
91 currentContinuation = null;
92 } catch (Exception e) {
93 if (this.exceptions == null)
94 this.exceptions = new ArrayList<Exception>();
95 this.exceptions.add(new RuntimeException("Action failure at " + currentTime + ": " + e.getMessage(), e));
99 return Double.POSITIVE_INFINITY;
100 else if(firstTask.time > currentTime+TIME_TOLERANCE)
101 return firstTask.time;
103 firstTask.continuation.apply(Tuple0.INSTANCE);
104 synchronized (this) {
105 scheduledAt.remove();
107 firstTask = scheduledAt.peek();
111 context.put("sequenceAction", oldActionContext);