-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.js
285 lines (248 loc) · 7.79 KB
/
driver.js
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/**
* The driver is an adapter that converts keyboard input into animated turns of
* the game engine.
* The driver receives input from button-key-handler.js (or eventually
* something more sophisticated that fuses input from other sources like DOM
* button presses or game controllers) and drives controller.js.
* This is the only component that observes the passage of time.
* All others receive pre-computed progress and see time as transitions between
* turns.
*
* The driver is also responsible for pacing repeated commands, which occur
* when a key is held for the duration of an entire turn or beyond.
*/
// @ts-check
/**
* @template T
* @typedef {import('./lib/cell.js').Cell<T>} Cell
*/
import { frameDeltas } from './lib/animation.js';
import { assert } from './lib/assert.js';
import { makeProgress } from './progress.js';
import { delay, defer } from './lib/async.js';
import { fullQuarturn } from './lib/geometry2d.js';
/**
* @template T
* @typedef {import('./lib/async.js').Deferred<T>} Deferred
*/
/**
* @typedef {import('./progress.js').Progress} Progress
*/
/**
* @callback HandleCommandFn
* @param {number} command
* @param {boolean} repeat
* @returns {AsyncIterator<void, void>}
*/
/**
* @callback CommandForKeyFn
* @param {string} key
* @returns {number | undefined}
*/
/**
* The controller is an object that the driver will drive input, animation, turn
* reset, and command key up and down events.
*
* @typedef {object} Controller
* @property {HandleCommandFn} handleCommand
* @property {CommandForKeyFn} commandForKey
* @property {(key: string) => boolean} handleMiscKeyPress
* @property {(command: number) => () => void} down
* @property {() => void} tick
* @property {() => void} tock
* @property {(progress: Progress) => void} animate
* @property {(direction: number) => number} commandForDirection
* @property {(command: number) => number | undefined} directionForCommand
* @property {() => void} idle
*/
/**
* @param {Controller} controller
* @param {Object} options
* @param {number} options.animatedTransitionDuration
* @param {Cell<number>} options.moment
*/
export const makeDriver = (controller, options) => {
const { animatedTransitionDuration, moment } = options;
/** @type {Array<Set<string>>} */
const commandHolders = new Array(10).fill(undefined).map(() => new Set());
/**
* Account for how the key to command mapping changes due to mode switching.
* Each keyup will cancel whatever command it innitiated.
* @type {Map<string, number>}
*/
const lastCommandForKey = new Map();
/** @type {Deferred<void>} */
let sync = defer();
/** @type {Deferred<void>} */
let abort = defer();
/** @type {Array<number>} directions */
const queue = [];
/** @type {Map<number, {start: number, up: () => void}>} direction to timestamp */
const held = new Map();
// TODO const vector = {x: 0, y: 0};
// Time elapsed since tick.
let timeSinceTransitionStart = animatedTransitionDuration;
/**
* @param {number} command
* @param {boolean} repeat
*/
async function tickTock(command, repeat) {
const turnGenerator = controller.handleCommand(command, repeat);
for (;;) {
// Ensure that the animation gets all the way to 100%, regardless of
// animation frame timing.
controller.animate(makeProgress(timeSinceTransitionStart, 1));
timeSinceTransitionStart = 0;
controller.tock();
const turnCompleted = turnGenerator.next();
controller.tick();
await delay(animatedTransitionDuration, abort.promise);
const { done } = await turnCompleted;
if (done) {
return;
}
}
}
/**
* @param {number} command
* @param {boolean} repeat
*/
async function issue(command, repeat) {
const direction = controller.directionForCommand(command);
if (direction === undefined) {
await tickTock(command, repeat);
} else {
const momentumAdjustedDirection =
(direction + moment.get()) % fullQuarturn;
await tickTock(
controller.commandForDirection(momentumAdjustedDirection),
repeat,
);
}
}
async function run() {
for (;;) {
sync = defer();
await sync.promise;
// The user can plan some number of moves ahead by tapping the command
// keys sequentially, as opposed to holding them down.
let command;
while (((command = queue.shift()), command !== undefined)) {
await issue(command, false);
}
// Repeat
while (held.size) {
const now = performance.now();
for (const [heldCommand, { start }] of held.entries()) {
const duration = now - start;
if (duration > animatedTransitionDuration) {
command = heldCommand;
}
}
if (command !== undefined) {
await issue(command, true);
}
}
controller.idle();
}
}
async function animate() {
for await (const elapsed of frameDeltas()) {
timeSinceTransitionStart += elapsed;
const progress = makeProgress(
elapsed,
timeSinceTransitionStart / animatedTransitionDuration,
);
controller.animate(progress);
}
}
/**
* @param {string} holder
* @param {number} [command]
* @returns {boolean}
*/
function down(holder, command) {
if (command === undefined) {
// The command for each key is mode-dependent.
command = controller.commandForKey(holder);
if (command === undefined) {
return controller.handleMiscKeyPress(holder);
}
lastCommandForKey.set(holder, command);
}
// Commands can be held by multiple holders (keys, mouse
// events, touch events).
// This paragraph ensures that we only proceed for the
// first holder, and track the holder so we don't release
// until it and all others are up.
const holders = commandHolders[command];
const alreadyHeld = holders.size !== 0;
holders.add(holder);
if (alreadyHeld) {
return true;
}
// If a command key goes down during an animated transition for a prior
// command, we abort that animation so the next move advances immediately
// to the beginning of the next animation.
if (held.size <= 1) {
abort.resolve();
abort = defer();
queue.length = 0;
}
assert(!held.has(command));
const up = controller.down(command);
held.set(command, { start: performance.now(), up });
queue.push(command);
// Kick the command processor into gear if it hasn't been provoked
// already.
sync.resolve();
sync = defer();
return true;
}
/**
* @param {string} holder
* @param {number} [command]
* @returns {boolean}
*/
function up(holder, command) {
if (command === undefined) {
command = lastCommandForKey.get(holder);
if (command === undefined) {
return false;
}
lastCommandForKey.delete(holder);
}
// Multiple holders can hold down a command button.
// This paragraph ensures we only proceed when the last
// holder on the command gets released.
const holders = commandHolders[command];
holders.delete(holder);
if (holders.size !== 0) {
return true;
}
const descriptor = held.get(command);
if (descriptor === undefined) {
return true;
}
const { up } = descriptor;
up();
held.delete(command);
// Clear the momentum heading if the player releases all keys.
if (held.size === 0) {
moment.set(0);
}
return true;
}
const cancel = () => {
for (const [command, holders] of commandHolders.entries()) {
for (const holder of holders) {
up(holder, command);
}
}
};
// @ts-ignore-next-line reportError not defined
run().catch(reportError);
// @ts-ignore-next-line reportError not defined
animate().catch(reportError);
return { down, up, cancel };
};