-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsim.ts
105 lines (91 loc) · 2.34 KB
/
sim.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import { actions } from "../actions";
import { Watcher } from "../watcher";
import {
SimulationState,
MachineState,
Code,
SimulationParams,
} from "../types";
import { Store } from "../store";
import { physx } from "../physics-constants";
export default function(w: Watcher) {
w.on(actions.boot, async (store, action) => {
const onTick = () => {
const { simulation } = store.getState();
if (simulation) {
const { machineState } = simulation;
if (machineState && !simulation.paused) {
tick(store);
}
}
requestAnimationFrame(onTick);
};
requestAnimationFrame(onTick);
});
}
function tick(store: Store) {
const { machineState, code, params, stepping } = store.getState().simulation;
const oldState = machineState;
let state = {
...oldState,
ticks: oldState.ticks + 1,
};
let freqTicks = 60 / state.freq;
let ticksDelta = state.ticks - state.lastUpdateTicks;
if (ticksDelta >= freqTicks) {
state = machineStep(code, params, state);
if (stepping) {
store.dispatch(actions.setPaused({ paused: true }));
store.dispatch(actions.setStepping({ stepping: false }));
}
}
// now update flippers
physx.step(state.course.world);
for (const j of state.course.leftJoints) {
physx.setLeftEnabled(j, state.flipperL);
}
for (const j of state.course.rightJoints) {
physx.setRightEnabled(j, state.flipperR);
}
store.dispatch(actions.commitMachineState({ state }));
}
export function machineStep(
code: Code,
params: SimulationParams,
oldState: MachineState,
): MachineState {
let state = { ...oldState };
const op = code[state.pc];
let nextPc = state.pc + 1;
switch (op.type) {
case "goto": {
for (let i = 0; i < code.length; i++) {
if (code[i].label == op.name) {
nextPc = i;
break;
}
}
break;
}
case "freq": {
if (op.numberValue > 0 && op.numberValue <= params.freq) {
state.freq = op.numberValue;
}
break;
}
case "motor": {
switch (op.name) {
case "left":
state.flipperL = op.boolValue;
break;
case "right":
state.flipperR = op.boolValue;
break;
}
break;
}
}
state.lastUpdateTicks = state.ticks;
state.pc = nextPc % code.length;
return state;
}