Repository navigation
Expand file tree
/
Copy pathpointer-jump-fix.js
More file actions
234 lines (205 loc) · 7.52 KB
/
Copy pathpointer-jump-fix.js
File metadata and controls
234 lines (205 loc) · 7.52 KB
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
/* Pointer Jump Fix: prevents jump-causing mouse deltas in Web 3D games. */
(function () {
'use strict';
var DEFAULTS = {
unadjustedMovement: true,
clampEnabled: true,
maxDelta: 0,
resetOnRelock: true,
resetOnFocus: true,
recoverMs: 120,
stallMs: 250,
spikeFloor: 256,
spikeRatio: 6,
spikeMaxGapMs: 64,
autoRelock: false,
relockGraceMs: 1500,
debug: false
};
var CONFIG = {};
var source = window.__PLFIX__ || window.pointerLockFixConfig || {};
for (var key in DEFAULTS) {
if (!Object.prototype.hasOwnProperty.call(DEFAULTS, key)) continue;
CONFIG[key] = Object.prototype.hasOwnProperty.call(source, key) ? source[key] : DEFAULTS[key];
}
var stats = { clamped: 0, spiked: 0, stalled: 0, recovered: 0, rawLocks: 0 };
var enabled = true;
var history = [[], []];
var lastEventAt = 0;
var resetUntil = 0;
var eventMemo = typeof WeakMap === 'function' ? new WeakMap() : null;
function debug(message) {
if (CONFIG.debug && window.console) window.console.log('[pointerlock-fix] ' + message);
}
function getLimit() {
return CONFIG.maxDelta > 0
? CONFIG.maxDelta
: Math.max(window.innerWidth || 1920, window.innerHeight || 1080) * 2;
}
function meanAbs(list) {
if (!list.length) return 0;
var sum = 0;
for (var i = 0; i < list.length; i++) sum += list[i];
return sum / list.length;
}
/* ---- movementX / movementY getters ---- */
var proto = window.MouseEvent && window.MouseEvent.prototype;
if (proto && !Object.prototype.hasOwnProperty.call(proto, '__PLFIX_INSTALLED__')) {
try {
Object.defineProperty(proto, '__PLFIX_INSTALLED__', { value: true, configurable: true });
} catch (e) {}
function prepareEvent(event) {
var state = eventMemo.get(event);
if (state) return state;
var nowAt = Date.now();
var move = event.type === 'mousemove';
var locked = move && !!(typeof document !== 'undefined' && document.pointerLockElement);
var dt = 0;
var stalled = 0;
if (move) {
if (locked && lastEventAt) dt = nowAt - lastEventAt;
stalled = dt > CONFIG.stallMs;
lastEventAt = nowAt;
}
state = { locked: locked, dt: dt, stalled: stalled };
eventMemo.set(event, state);
return state;
}
function patchGetter(axis) {
var name = axis === 0 ? 'movementX' : 'movementY';
var descriptor = Object.getOwnPropertyDescriptor(proto, name);
if (!descriptor || typeof descriptor.get !== 'function') return;
var original = descriptor.get;
var hist = history[axis];
Object.defineProperty(proto, name, {
configurable: true,
enumerable: descriptor.enumerable,
get: function () {
var value = original.call(this);
if (!enabled) return value;
if (!CONFIG.clampEnabled) return value;
var state = prepareEvent(this);
var nowAt = Date.now();
if (state.stalled) {
stats.stalled++;
resetUntil = Math.max(resetUntil, nowAt + CONFIG.recoverMs);
debug('stall cut (' + name + '=' + value + ')');
return 0;
}
if (nowAt <= resetUntil) {
stats.recovered++;
debug('recover (' + name + '=' + value + ')');
return 0;
}
var abs = Math.abs(value);
if (abs > getLimit()) {
stats.clamped++;
debug('clamp (' + name + '=' + value + ')');
return 0;
}
if (state.locked && abs > CONFIG.spikeFloor && state.dt <= CONFIG.spikeMaxGapMs) {
var avg = meanAbs(hist);
if (avg > 0 && abs / avg > CONFIG.spikeRatio) {
stats.spiked++;
debug('spike (' + name + '=' + value + ' vs avg ' + avg + ')');
return 0;
}
}
if (abs > 0) {
hist.push(abs);
if (hist.length > 4) hist.shift();
}
return value;
}
});
}
patchGetter(0);
patchGetter(1);
}
/* ---- recovery windows ---- */
function scheduleReset(reason) {
resetUntil = Date.now() + CONFIG.recoverMs;
debug('recover until ' + resetUntil + ' (' + reason + ')');
}
if (typeof document !== 'undefined' && CONFIG.resetOnRelock) {
document.addEventListener('pointerlockchange', function () {
scheduleReset('pointerlockchange');
}, true);
document.addEventListener('pointerlockerror', function () { scheduleReset('pointerlockerror'); }, true);
}
if (typeof window !== 'undefined' && CONFIG.resetOnFocus) {
window.addEventListener('focus', function () { scheduleReset('focus'); });
document.addEventListener('visibilitychange', function () {
if (document.visibilityState === 'visible') scheduleReset('visible');
});
}
/* ---- requestPointerLock({ unadjustedMovement: true }) ---- */
function patchPointerLock() {
var elementProto = window.Element && window.Element.prototype;
if (!elementProto || Object.prototype.hasOwnProperty.call(elementProto, '__PLFIX_RPL__')) return;
try {
Object.defineProperty(elementProto, '__PLFIX_RPL__', { value: true, configurable: true });
} catch (e) { return; }
var orig = elementProto.requestPointerLock || elementProto.webkitRequestPointerLock;
if (typeof orig !== 'function') return;
function rawLock() {
var target = this;
var options = arguments[0];
if (!enabled) return orig.apply(target, arguments);
if (options && typeof options === 'object') return orig.call(target, options);
stats.rawLocks++;
var result;
try {
result = orig.call(target, { unadjustedMovement: true });
} catch (err) {
result = orig.call(target);
}
if (result && typeof result.catch === 'function') {
return result.catch(function (err) {
if (err && err.name === 'NotSupportedError') return orig.call(this);
throw err;
}.bind(target));
}
return result;
}
try {
Object.defineProperty(elementProto, 'requestPointerLock', {
configurable: true,
writable: true,
value: rawLock
});
elementProto.webkitRequestPointerLock = rawLock;
} catch (e) {}
}
patchPointerLock();
/* ---- auto-relock ---- */
if (typeof document !== 'undefined' && CONFIG.autoRelock) {
var graceUntil = 0;
window.addEventListener('pointerdown', function () {
if (!enabled) return;
if (!document.pointerLockElement && Date.now() >= graceUntil && document.body && typeof document.body.requestPointerLock === 'function') {
try { document.body.requestPointerLock(); } catch (e) {}
}
}, true);
window.addEventListener('keydown', function (event) {
if (event.key === 'Escape' || event.keyCode === 27) graceUntil = Date.now() + CONFIG.relockGraceMs;
}, true);
}
/* ---- enable / disable (host app message bridge) ---- */
window.addEventListener('message', function (event) {
if (!event.data || event.source !== window || event.data.source !== '__PLFIX_EXT__') return;
enabled = !!event.data.enabled;
debug('enabled = ' + enabled);
});
/* ---- stats ---- */
window.__PLFIX__stats = {
clamped: function () { return stats.clamped; },
spiked: function () { return stats.spiked; },
stalled: function () { return stats.stalled; },
recovered: function () { return stats.recovered; },
rawLocks: function () { return stats.rawLocks; },
enabled: function () { return enabled; },
config: CONFIG
};
debug('installed');
})();