-
Notifications
You must be signed in to change notification settings - Fork 2
/
io.js
287 lines (251 loc) · 8.82 KB
/
io.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
286
287
// generic IO functions (not specific to NGU or any game)
const {px, wait} = require('./util.js');
const {PixelDetector} = require('./color.js');
const {Point, Rect} = require('./ui.js');
// input part: sending emulated input events
// NOTE(peoro): NGU processes input events with the following priority:
// 1. move the mouse to the latest position
// 2. read all mouse click events (only one per button though!)
// 3. read the first key pressed
//
// This means that if during a single frame the mouse is moved several times, multiple keys are pressed and multiple mouse buttons click:
// - first, NGU moves the mouse to the latest location our mouse moved to
// - then, NGU processes all the mouse buttons that have been clicked
// - at last, NGU processes the first key that has been pressed
//
// TODO(peoro): figure out what happens with different combinations of mouse/key down or up...
//
// Given the above, we'll use the following (suboptimal, but simple) state machine to decide whether to send input immediately, or to wait for the next frame:
// states:
// - NO_INPUT: no input of any kind has been sent during the current frame
// - MOUSE_MOVE: mousemove has been requested
// - MOUSE_DOWN(button): mousedown has been requested on `button`
// - CLICK: mouseup has been requested
// - KEY_DOWN(key): keydown has been requested on `key`
// - KEYPRESS: a key has been pressed
// we can only move from a state to one strictly lower in the list, and from `MOUSE_DOWN` to `CLICK` or from `KEY_DOWN` to `KEYPRESS` only if the button/key is the same
const mkEvent = (EvType, eventName, data)=>{
return new EvType( eventName, Object.assign({
view: window,
bubbles: true,
cancelable: true,
}, data) );
};
class IO {
constructor( gameCanvas, ui, {headless=false}={} ) {
this.state = new IO.State( this );
this.animationHandle = null;
this.nextFrame = null;
this.mouse = new Mouse( this, gameCanvas, ui );
this.keyboard = new Keyboard( this );
if( ! headless ) {
this.framebuffer = new Framebuffer( this, gameCanvas );
}
const waitForNextFrame = ()=>{
return this.nextFrame = new Promise( (resolve,reject)=>{
this.animationHandle = window.requestAnimationFrame( ()=>{
waitForNextFrame();
resolve();
});
});
};
waitForNextFrame();
}
eachFrame( fn ) {
let running = true;
(async ()=>{
while( running ) {
fn();
await this.nextFrame;
}
})();
return { destroy(){ running = false; } };
}
log( ...args ) {
// console.log( ...args );
}
toState( newState ) { return this.state.toState( newState ); }
// NOTE(peoro): `sync` doesn't work properly... `await this.sync()` usually returns before the latest input request is done sending its event. Not sure why; promise branching doesn't guarantee any call ordering or what?
// because of that, `sync()` always wait one extra, unnecessary frame...
async sync() {
const state = await this.state.latestInputRequest;
await state.nextFrame;
console.assert( this.state.commandsToProcess === 0, `somehow sync didn't catch up with all the commands` );
}
destroy() { window.cancelAnimationFrame( this.animationHandle ); }
}
IO.State = class IOState {
constructor( io ) {
this.io = io;
// a promise that is resolved when the latest input event has been executed
// it returns the state as it's left by the latest input event
this.latestInputRequest = Promise.resolve({
state: IO.states.noInput,
nextFrame: Promise.resolve(),
});
this.commandsToProcess = 0;
}
async toState( newState ) {
++ this.commandsToProcess;
return this.latestInputRequest = (async ()=>{
const state = await this.latestInputRequest; // waiting for the latest input event requseted so far
// waiting a whole frame after the previous request, if necessary
//console.log( state, `->`, newState, `need to wait?`, this.needToWait(state, newState) );
if( this.needToWait(state, newState) ) {
await state.nextFrame;
await wait(IO.delay/1000);
}
-- this.commandsToProcess;
// let's return the state we're leaving the system in
return Object.assign( {}, newState, {
nextFrame: this.io.nextFrame,
});
})();
}
needToWait( state, newState ) {
if( newState.state <= state.state ) {
return true;
}
if( newState.state === IO.states.click && state.state === IO.states.mouseDown && newState.button !== state.button ) {
return true;
}
if( newState.state === IO.states.keyPress && state.state === IO.states.keyDown && newState.key !== state.key ) {
return true;
}
return false;
}
};
IO.states = {
noInput: 0,
mouseMove: 1,
mouseDown: 2,
click: 3,
keyDown: 4,
keyPress: 5,
};
IO.delay = 0;
// TODO(peoro): currently it's important to `await` every io function and be careful to put short pauses after each call... Let's change this module so that input functions can be called synchronously: they just keep track of the current input sequence (e.g. using a singleton promise that keeps getting replaced) and execute it all with the correct pauses (i.e. waiting for animation frames between pieces of input that need to be broken apart, like mouse moves). Then awaiting on a single synchronization function at the end will be enough.
class Mouse {
constructor( io, target, ui ) {
this.io = io;
this.target = target;
this.p = px( 0, 0 );
if( ui ) {
const vMouse = new Point( 'vMouse' );
vMouse.show( ui );
this.vMouse = vMouse;
}
}
sendEvent( eventName, data={} ) {
const {x, y} = this.p;
const element = this.target || document.elementFromPoint(x, y);
const event = mkEvent( window.MouseEvent, eventName, Object.assign({clientX:x, clientY:y}, data) );
element.dispatchEvent( event );
}
async move( p ) {
await this.io.toState( {state:IO.states.mouseMove, p} );
this.p.copy( p );
if( this.vMouse ) {
this.vMouse.move( p );
}
this.io.log( `mouse move ${p}` );
return this.sendEvent( `mousemove` );
}
async down( button=0 ) {
await this.io.toState( {state:IO.states.mouseDown, button} );
this.io.log( `mouse down ${button}` );
return this.sendEvent(`mousedown`, {button});
}
async up( button=0 ) {
await this.io.toState( {state:IO.states.click, button} );
this.io.log( `mouse up ${button}` );
return this.sendEvent(`mouseup`, {button});
}
click( button=0 ) {
// return this.sendEvent( `click`, {button} );
this.down( button );
return this.up( button );
}
}
class Keyboard {
constructor( io ) {
this.io = io;
}
sendEvent( eventName, {code, key, keyCode}, data={} ) {
const event = mkEvent( window.KeyboardEvent, eventName, Object.assign({
code,
key,
keyCode,
which: keyCode,
}, data) );
window.dispatchEvent( event );
}
async down( key ) {
await this.io.toState( {state:IO.states.keyDown, key} );
return this.sendEvent(`keydown`, key);
}
async up( key ) {
await this.io.toState( {state:IO.states.keyPress, key} );
return this.sendEvent(`keyup`, key);
}
async press( key ) {
this.down( key );
return this.up( key );
}
};
Keyboard.keys = {
leftArrow: {keyCode:37},
upArrow: {keyCode:38},
rightArrow: {keyCode:39},
downArrow: {keyCode:40},
};
// adding all the letters to `Keyboard.keys`
for( let keyCode = 65; keyCode < 91; ++keyCode ) {
const char = String.fromCharCode( keyCode );
const key = char.toLowerCase();
const code = `Key${char}`;
Keyboard.keys[key] = {code, key, keyCode};
}
// output part: reading information from the canvas
const W = 960, H = 600;
class Framebuffer {
constructor( io, canvas ) {
console.assert( canvas.width === W && canvas.height === H, `Framebuffer is currently meant to only work with ${W}x${H} canvases (canvas is ${canvas.width}x${canvas.height})` );
this.io = io;
const gl = this.gl = canvas.getContext('webgl') || canvas.getContext('webgl2');
const buffer = new ArrayBuffer( 4*W*H );
this.dataView = new DataView( buffer );
// recapturing the framebuffer image every frame
const u8arr = new Uint8Array( buffer );
io.eachFrame( ()=>{
gl.readPixels( 0, 0, W, H, gl.RGBA, gl.UNSIGNED_BYTE, u8arr );
});
}
get size() { return px(W, H); }
get rect() { return Rect.fromTLSize( px(0,0), this.size() ); }
// overriding `getOffset`, since top and bottom in the framebuffer is inverted...
getOffset( p ) {
return p.x + (H-p.y-1)*W;
}
getPixel( p ) {
console.assert( p.isInteger(), `${p} not an integer size...` );
return this.dataView.getUint32( this.getOffset(p)*4, false );
}
}
// adding a `detect :: Framebuffer -> value` method to `PixelDetector`
PixelDetector.prototype.detect = function( fb=nguJs.io.framebuffer ) {
const color = fb.getPixel( this.offset.clone().round() );
return this.colorMap.get( color );
};
PixelDetector.prototype.debug = function( fb=nguJs.io.framebuffer ) {
const color = fb.getPixel( this.offset.clone().round() );
console.log( `${this.offset}: #${color.toString(16)} ➜ ${this.colorMap.get(color)}` );
return this.offset.debug();
};
module.exports = {
mkEvent,
IO,
Mouse,
Keyboard,
Framebuffer,
};