forked from mattgodbolt/jsbeeb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
touchscreen.js
79 lines (75 loc) · 2.38 KB
/
touchscreen.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
"use strict";
import * as utils from "./utils.js";
export function TouchScreen(scheduler) {
const self = this;
const PollHz = 8; // Made up
const PollCycles = (2 * 1000 * 1000) / PollHz;
this.scheduler = scheduler;
this.mouse = [];
this.outBuffer = new utils.Fifo(16);
this.delay = 0;
this.mode = 0;
this.onMouse = function (x, y, button) {
this.mouse = { x: x, y: y, button: button };
};
this.poll = function () {
self.doRead();
self.pollTask.reschedule(PollCycles);
};
this.pollTask = this.scheduler.newTask(this.poll);
this.onTransmit = function (val) {
switch (String.fromCharCode(val)) {
case "M":
self.mode = 0;
break;
case "0":
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
self.mode = 10 * self.mode + val - "0".charCodeAt(0);
break;
case ".":
break;
case "?":
if (self.mode === 1) self.doRead();
break;
}
self.pollTask.ensureScheduled(self.mode === 129 || self.mode === 130, PollCycles);
};
this.tryReceive = function (rts) {
if (self.outBuffer.size && rts) return self.outBuffer.get();
return -1;
};
this.store = function (byte) {
self.outBuffer.put(byte);
};
function doScale(val, scale, margin) {
val = (val - margin) / (1 - 2 * margin);
return val * scale;
}
this.doRead = function () {
const scaleX = 120,
marginX = 0.13;
const scaleY = 100,
marginY = 0.03;
const scaledX = doScale(self.mouse.x, scaleX, marginX);
const scaledY = doScale(1 - self.mouse.y, scaleY, marginY);
const toSend = [0x4f, 0x4f, 0x4f, 0x4f];
const x = Math.min(255, Math.max(0, scaledX)) | 0;
const y = Math.min(255, Math.max(0, scaledY)) | 0;
if (self.mouse.button) {
toSend[0] = 0x40 | ((x & 0xf0) >>> 4);
toSend[1] = 0x40 | (x & 0x0f);
toSend[2] = 0x40 | ((y & 0xf0) >>> 4);
toSend[3] = 0x40 | (y & 0x0f);
}
for (let i = 0; i < 4; ++i) self.store(toSend[i]);
self.store(".".charCodeAt(0));
};
}