@wasm-gaming/sonic3air-wasm 0.0.0 → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/sonic3air/LICENSE +674 -0
- package/dist/sonic3air/THIRD_PARTY_NOTICES.md +79 -0
- package/dist/sonic3air/app/app.css +104 -0
- package/dist/sonic3air/app/app.js +305 -0
- package/dist/sonic3air/engine-specs.js +1546 -0
- package/dist/sonic3air/sonic3air.data +0 -0
- package/dist/sonic3air/sonic3air.data.json +64 -0
- package/dist/sonic3air/sonic3air.js +42 -0
- package/dist/sonic3air/sonic3air.options.d.ts +68 -0
- package/dist/sonic3air/sonic3air.options.d.ts.map +1 -0
- package/dist/sonic3air/sonic3air.options.js +35 -0
- package/dist/sonic3air/sonic3air.options.js.map +1 -0
- package/dist/sonic3air/sonic3air.sdk.d.ts +100 -0
- package/dist/sonic3air/sonic3air.sdk.d.ts.map +1 -0
- package/dist/sonic3air/sonic3air.sdk.js +604 -0
- package/dist/sonic3air/sonic3air.sdk.js.map +1 -0
- package/dist/sonic3air/sonic3air.wasm +0 -0
- package/package.json +1 -1
- package/src/sonic3air.sdk.ts +1 -1
|
@@ -0,0 +1,1546 @@
|
|
|
1
|
+
// ---- Introspectable property definitions ----
|
|
2
|
+
/**
|
|
3
|
+
* The listener bookkeeping, shipped rather than described — the one piece of runtime
|
|
4
|
+
* code in this package.
|
|
5
|
+
*
|
|
6
|
+
* It is a **convenience, not a requirement**: the contract stays structural, so an
|
|
7
|
+
* engine that already owns an emitter satisfies {@link EngineSurface} without this.
|
|
8
|
+
* What it saves is the part everyone gets subtly wrong — iterating a copy, so a
|
|
9
|
+
* listener that unsubscribes mid-emit does not corrupt the loop; de-duplicating a
|
|
10
|
+
* listener registered twice; and keeping one throwing listener from silencing the
|
|
11
|
+
* rest.
|
|
12
|
+
*
|
|
13
|
+
* Hold it **privately** and hand the same instance to every carrier. That is what
|
|
14
|
+
* makes `sdk.on(…)` and `play.on(…)` one channel rather than two, lets a host
|
|
15
|
+
* subscribe before the engine exists, and keeps `emit` out of the public API — a host
|
|
16
|
+
* must not be able to forge an engine event.
|
|
17
|
+
*/
|
|
18
|
+
export class EventEmitter {
|
|
19
|
+
#listeners = new Map();
|
|
20
|
+
/** @param listeners Registered immediately — what `EngineInit.on` carries. */
|
|
21
|
+
constructor(listeners) {
|
|
22
|
+
for (const type of Object.keys(listeners ?? {})) {
|
|
23
|
+
const listener = listeners?.[type];
|
|
24
|
+
if (listener)
|
|
25
|
+
this.on(type, listener);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** Registering the same listener twice registers it once, as `EventTarget` does. */
|
|
29
|
+
on(type, listener) {
|
|
30
|
+
let set = this.#listeners.get(type);
|
|
31
|
+
if (!set)
|
|
32
|
+
this.#listeners.set(type, (set = new Set()));
|
|
33
|
+
set.add(listener);
|
|
34
|
+
return this;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The listener is required, as in `EventTarget`. A convenience `off(type)` dropping
|
|
38
|
+
* every listener for a type is a footgun on a page where two components subscribed
|
|
39
|
+
* independently: one unsubscribing would silence the other.
|
|
40
|
+
*/
|
|
41
|
+
off(type, listener) {
|
|
42
|
+
const set = this.#listeners.get(type);
|
|
43
|
+
if (set?.delete(listener) && set.size === 0) {
|
|
44
|
+
this.#listeners.delete(type);
|
|
45
|
+
}
|
|
46
|
+
return this;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Takes the **detail**, and wraps it. The rest tuple is what lets an event with no
|
|
50
|
+
* detail be emitted as `emit('exit')` while still checking the ones that have one.
|
|
51
|
+
*/
|
|
52
|
+
emit(type, ...[detail]) {
|
|
53
|
+
const set = this.#listeners.get(type);
|
|
54
|
+
if (!set)
|
|
55
|
+
return;
|
|
56
|
+
// Built once and frozen: every listener gets this same object, so a mutable one
|
|
57
|
+
// would let the first rewrite what the rest read.
|
|
58
|
+
const event = Object.freeze({ type, detail: detail });
|
|
59
|
+
// A copy: a listener may call `off()` — on itself or another — while this runs.
|
|
60
|
+
for (const listener of [...set]) {
|
|
61
|
+
try {
|
|
62
|
+
listener(event);
|
|
63
|
+
}
|
|
64
|
+
catch (thrown) {
|
|
65
|
+
// One bad listener must neither silence the rest nor vanish. Rethrowing on a
|
|
66
|
+
// fresh task puts it in front of `window.onerror` with its stack intact.
|
|
67
|
+
queueMicrotask(() => {
|
|
68
|
+
throw thrown;
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Wrap a promise of a live engine in the chainable surface.
|
|
76
|
+
*
|
|
77
|
+
* Exported because it is the single most duplicated function in an engine, and an
|
|
78
|
+
* engine that does not extend {@link EnginePlayBase} still needs exactly this.
|
|
79
|
+
*
|
|
80
|
+
* `on` and `off` do **not** go through the chain: they reach the channel now, so a
|
|
81
|
+
* listener is live before the promise settles. Routing them through it would bind
|
|
82
|
+
* after the session opened and lose whatever was emitted while it was opening.
|
|
83
|
+
*/
|
|
84
|
+
export function hydratePlay(inner, events) {
|
|
85
|
+
const chain = (step) => hydratePlay(inner.then(async (play) => {
|
|
86
|
+
await step(play);
|
|
87
|
+
return play;
|
|
88
|
+
}), events);
|
|
89
|
+
const hydrated = {
|
|
90
|
+
then: (onfulfilled, onrejected) => inner.then(onfulfilled, onrejected),
|
|
91
|
+
catch: (onrejected) => inner.catch(onrejected),
|
|
92
|
+
finally: (onfinally) => inner.finally(onfinally),
|
|
93
|
+
[Symbol.toStringTag]: 'PromisePlay',
|
|
94
|
+
config: ((patch) => patch === undefined
|
|
95
|
+
? inner.then((play) => play.config())
|
|
96
|
+
: chain((play) => play.config(patch))),
|
|
97
|
+
options: ((patch) => patch === undefined
|
|
98
|
+
? inner.then((play) => play.options())
|
|
99
|
+
: chain((play) => play.options(patch))),
|
|
100
|
+
assets: ((patch) => patch === undefined
|
|
101
|
+
? inner.then((play) => play.assets())
|
|
102
|
+
: chain((play) => play.assets(patch))),
|
|
103
|
+
storage: ((patch) => patch === undefined
|
|
104
|
+
? inner.then((play) => play.storage())
|
|
105
|
+
: chain((play) => play.storage(patch))),
|
|
106
|
+
mount: (target) => chain((play) => play.mount(target)),
|
|
107
|
+
on: (type, listener) => {
|
|
108
|
+
events.on(type, listener);
|
|
109
|
+
return hydrated;
|
|
110
|
+
},
|
|
111
|
+
off: (type, listener) => {
|
|
112
|
+
events.off(type, listener);
|
|
113
|
+
return hydrated;
|
|
114
|
+
},
|
|
115
|
+
restart: (options) => chain((play) => play.restart(options)),
|
|
116
|
+
destroy: () => inner.then((play) => play.destroy()),
|
|
117
|
+
};
|
|
118
|
+
return hydrated;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* The live engine, with everything the contract prescribes already written: state,
|
|
122
|
+
* the cumulative merge, the descriptors, the chainable promise, and the channel.
|
|
123
|
+
*
|
|
124
|
+
* A subclass supplies what only it can know — {@link EnginePlayBase.open} and
|
|
125
|
+
* {@link EnginePlayBase.close}, optionally {@link EnginePlayBase.mounted} and
|
|
126
|
+
* {@link EnginePlayBase.patched} — and its properties as an {@link EngineSpec}.
|
|
127
|
+
*
|
|
128
|
+
* The spec arrives as a **constructor argument**, not an abstract field, and that is
|
|
129
|
+
* not a style choice: a subclass field initialiser runs *after* `super()`, so a
|
|
130
|
+
* `protected abstract spec` would still be `undefined` while this constructor seeded
|
|
131
|
+
* state from it. Passing it up makes the ordering trap impossible rather than merely
|
|
132
|
+
* avoided.
|
|
133
|
+
*/
|
|
134
|
+
export class EnginePlayBase {
|
|
135
|
+
#spec;
|
|
136
|
+
#state;
|
|
137
|
+
#events;
|
|
138
|
+
#target;
|
|
139
|
+
/** The target {@link EnginePlayBase.mounted} has already been told about. */
|
|
140
|
+
#attached;
|
|
141
|
+
/**
|
|
142
|
+
* @param events The factory's channel. Omitted only when a play is built on its
|
|
143
|
+
* own; the factory always passes its own, which is what makes `sdk.on(…)` and
|
|
144
|
+
* `play.on(…)` one channel rather than two.
|
|
145
|
+
*/
|
|
146
|
+
constructor(spec, init, events) {
|
|
147
|
+
this.#spec = spec;
|
|
148
|
+
this.#events = events ?? new EventEmitter(init?.on);
|
|
149
|
+
this.#state = {
|
|
150
|
+
config: seed(spec.config, init?.config),
|
|
151
|
+
options: seed(spec.options, init?.options),
|
|
152
|
+
assets: seed(spec.assets, init?.assets),
|
|
153
|
+
storage: seed(spec.storage, init?.storage),
|
|
154
|
+
};
|
|
155
|
+
// Recorded, not applied. `mounted()` is overridable, and a subclass's own fields
|
|
156
|
+
// are still uninitialised while this constructor runs — so the hook is deferred to
|
|
157
|
+
// the first `restart()`, by which point the subclass is whole.
|
|
158
|
+
this.#target = init?.mount;
|
|
159
|
+
}
|
|
160
|
+
/** The element is already recorded when this runs. */
|
|
161
|
+
mounted(target) {
|
|
162
|
+
void target;
|
|
163
|
+
}
|
|
164
|
+
/** A payload changed on a running engine — apply what is `live`, ignore the rest. */
|
|
165
|
+
patched(kind, patch) {
|
|
166
|
+
void kind;
|
|
167
|
+
void patch;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Emit one of this engine's own events.
|
|
171
|
+
*
|
|
172
|
+
* `protected`, so a typed host cannot forge an engine event — but be exact about
|
|
173
|
+
* what that buys: TypeScript erases `protected`, so this is a compile-time guard,
|
|
174
|
+
* not a capability boundary. Plain JavaScript can still reach it. Only the `#`
|
|
175
|
+
* fields below — the channel and the state — are unreachable at runtime.
|
|
176
|
+
*/
|
|
177
|
+
emit(type, ...detail) {
|
|
178
|
+
this.#events.emit(type, ...detail);
|
|
179
|
+
}
|
|
180
|
+
/** Where the picture is, for a subclass that needs the element after `mounted()`. */
|
|
181
|
+
get target() {
|
|
182
|
+
return this.#target;
|
|
183
|
+
}
|
|
184
|
+
config(patch) {
|
|
185
|
+
// `arguments.length`, not `patch === undefined`: `config(undefined)` is a write of
|
|
186
|
+
// nothing, not a read.
|
|
187
|
+
if (arguments.length === 0)
|
|
188
|
+
return Promise.resolve(this.#describe('config'));
|
|
189
|
+
return this.#patch('config', patch);
|
|
190
|
+
}
|
|
191
|
+
options(patch) {
|
|
192
|
+
if (arguments.length === 0)
|
|
193
|
+
return Promise.resolve(this.#describe('options'));
|
|
194
|
+
return this.#patch('options', patch);
|
|
195
|
+
}
|
|
196
|
+
assets(patch) {
|
|
197
|
+
if (arguments.length === 0)
|
|
198
|
+
return Promise.resolve(this.#describe('assets'));
|
|
199
|
+
return this.#patch('assets', patch);
|
|
200
|
+
}
|
|
201
|
+
storage(patch) {
|
|
202
|
+
if (arguments.length === 0)
|
|
203
|
+
return Promise.resolve(this.#describe('storage'));
|
|
204
|
+
return this.#patch('storage', patch);
|
|
205
|
+
}
|
|
206
|
+
mount(target) {
|
|
207
|
+
this.#target = target;
|
|
208
|
+
return this.#run(() => this.#attach());
|
|
209
|
+
}
|
|
210
|
+
on(type, listener) {
|
|
211
|
+
this.#events.on(type, listener);
|
|
212
|
+
return hydratePlay(Promise.resolve(this), this.#events);
|
|
213
|
+
}
|
|
214
|
+
off(type, listener) {
|
|
215
|
+
this.#events.off(type, listener);
|
|
216
|
+
return hydratePlay(Promise.resolve(this), this.#events);
|
|
217
|
+
}
|
|
218
|
+
restart(options) {
|
|
219
|
+
return this.#run(async () => {
|
|
220
|
+
if (options)
|
|
221
|
+
Object.assign(this.#state.options, options);
|
|
222
|
+
// A target supplied to the constructor lands here, which is what makes
|
|
223
|
+
// `new Sdk({ mount: el }).start()` and `new Sdk().mount(el).start()` the same
|
|
224
|
+
// call — the rule the contract states for everything on the surface.
|
|
225
|
+
await this.#attach();
|
|
226
|
+
const opened = { ...this.#state.options };
|
|
227
|
+
await this.open(opened);
|
|
228
|
+
this.#emitCore('start', opened);
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
async destroy() {
|
|
232
|
+
await this.#guard(async () => {
|
|
233
|
+
await this.close();
|
|
234
|
+
this.#target = undefined;
|
|
235
|
+
this.#attached = undefined;
|
|
236
|
+
this.#emitCore('exit', undefined);
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
/** Tell the engine where it is, once per distinct target. Reparenting is legal. */
|
|
240
|
+
async #attach() {
|
|
241
|
+
if (!this.#target || this.#target === this.#attached)
|
|
242
|
+
return;
|
|
243
|
+
this.#attached = this.#target;
|
|
244
|
+
await this.mounted(this.#target);
|
|
245
|
+
}
|
|
246
|
+
// ---- Shared machinery ----
|
|
247
|
+
/** One getter's answer: the spec, with the current value written into each entry. */
|
|
248
|
+
#describe(kind) {
|
|
249
|
+
const spec = this.#spec[kind];
|
|
250
|
+
const state = this.#state[kind];
|
|
251
|
+
const out = {};
|
|
252
|
+
for (const key of Object.keys(spec)) {
|
|
253
|
+
out[key] = { ...spec[key], value: state[key] };
|
|
254
|
+
}
|
|
255
|
+
return out;
|
|
256
|
+
}
|
|
257
|
+
/** Cumulative, merged flat, one level — `undefined` is a value, not "leave alone". */
|
|
258
|
+
#patch(kind, patch) {
|
|
259
|
+
Object.assign(this.#state[kind], patch);
|
|
260
|
+
return this.#run(async () => {
|
|
261
|
+
await this.patched(kind, patch ?? {});
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
/** A step, as a link in the chain — and as an `error` event if it throws. */
|
|
265
|
+
#run(step) {
|
|
266
|
+
return hydratePlay(this.#guard(step), this.#events);
|
|
267
|
+
}
|
|
268
|
+
/**
|
|
269
|
+
* The rule that errors reach a host **both ways**: the promise rejects *and*
|
|
270
|
+
* `error` is emitted. Written once here rather than at every throw site.
|
|
271
|
+
*/
|
|
272
|
+
async #guard(step) {
|
|
273
|
+
try {
|
|
274
|
+
await step();
|
|
275
|
+
return this;
|
|
276
|
+
}
|
|
277
|
+
catch (thrown) {
|
|
278
|
+
const error = thrown instanceof Error ? thrown : new Error(String(thrown));
|
|
279
|
+
this.#emitCore('error', error);
|
|
280
|
+
throw error;
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* The core events, emitted from here rather than by a subclass.
|
|
285
|
+
*
|
|
286
|
+
* The cast is the one thing TypeScript will not check here: `emit` takes a rest
|
|
287
|
+
* tuple that is conditional on the detail type, and that conditional stays
|
|
288
|
+
* unresolved while `P` is still a type parameter. It is sound — `EventsOf<P>`
|
|
289
|
+
* always contains `CoreEvents<P>` by construction — and confining it to this one
|
|
290
|
+
* method is why the three call sites above read plainly.
|
|
291
|
+
*/
|
|
292
|
+
#emitCore(type, detail) {
|
|
293
|
+
// Cast the channel, not the method: pulling `emit` out into a variable would call
|
|
294
|
+
// it unbound, and it reads its listeners off `this`.
|
|
295
|
+
const events = this.#events;
|
|
296
|
+
events.emit(type, detail);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
/** Starting state: every `default` the spec declares, then whatever `init` overrides. */
|
|
300
|
+
function seed(spec, patch) {
|
|
301
|
+
const state = {};
|
|
302
|
+
for (const [key, property] of Object.entries(spec)) {
|
|
303
|
+
if (property.default !== undefined)
|
|
304
|
+
state[key] = property.default;
|
|
305
|
+
}
|
|
306
|
+
return Object.assign(state, patch);
|
|
307
|
+
}
|
|
308
|
+
/**
|
|
309
|
+
* The factory, with everything the contract prescribes already written: the
|
|
310
|
+
* cumulative init, the synchronous chain, the channel that outlives every session,
|
|
311
|
+
* and one live engine per factory.
|
|
312
|
+
*
|
|
313
|
+
* A subclass supplies its static identity and {@link EngineSDKBase.createPlay}.
|
|
314
|
+
*/
|
|
315
|
+
export class EngineSDKBase {
|
|
316
|
+
#init;
|
|
317
|
+
#play;
|
|
318
|
+
/**
|
|
319
|
+
* Created before any engine exists and handed to every carrier downstream. That is
|
|
320
|
+
* what lets a host subscribe to an error thrown while the first session opens.
|
|
321
|
+
*/
|
|
322
|
+
events;
|
|
323
|
+
constructor(init) {
|
|
324
|
+
this.#init = { ...init };
|
|
325
|
+
this.events = new EventEmitter(init?.on);
|
|
326
|
+
}
|
|
327
|
+
config(patch) {
|
|
328
|
+
if (arguments.length === 0)
|
|
329
|
+
return this.#pending().config();
|
|
330
|
+
return this.#patch('config', patch);
|
|
331
|
+
}
|
|
332
|
+
options(patch) {
|
|
333
|
+
if (arguments.length === 0)
|
|
334
|
+
return this.#pending().options();
|
|
335
|
+
return this.#patch('options', patch);
|
|
336
|
+
}
|
|
337
|
+
assets(patch) {
|
|
338
|
+
if (arguments.length === 0)
|
|
339
|
+
return this.#pending().assets();
|
|
340
|
+
return this.#patch('assets', patch);
|
|
341
|
+
}
|
|
342
|
+
storage(patch) {
|
|
343
|
+
if (arguments.length === 0)
|
|
344
|
+
return this.#pending().storage();
|
|
345
|
+
return this.#patch('storage', patch);
|
|
346
|
+
}
|
|
347
|
+
/** Recorded now, applied when the engine exists — same call as `new Sdk({ mount })`. */
|
|
348
|
+
mount(target) {
|
|
349
|
+
this.#init.mount = target;
|
|
350
|
+
this.#play?.mount(target);
|
|
351
|
+
return this;
|
|
352
|
+
}
|
|
353
|
+
on(type, listener) {
|
|
354
|
+
this.events.on(type, listener);
|
|
355
|
+
return this;
|
|
356
|
+
}
|
|
357
|
+
off(type, listener) {
|
|
358
|
+
this.events.off(type, listener);
|
|
359
|
+
return this;
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* The only way in. On a live engine it reopens the session rather than building a
|
|
363
|
+
* second one: a factory governs at most one engine.
|
|
364
|
+
*/
|
|
365
|
+
start(options) {
|
|
366
|
+
this.#play ??= this.createPlay(this.#init, this.events);
|
|
367
|
+
return this.#play.restart(options);
|
|
368
|
+
}
|
|
369
|
+
/** Answers a read before there is an engine: the settings the next one will use. */
|
|
370
|
+
#pending() {
|
|
371
|
+
return this.#play ?? this.createPlay(this.#init, this.events);
|
|
372
|
+
}
|
|
373
|
+
#patch(kind, patch) {
|
|
374
|
+
this.#init[kind] = { ...this.#init[kind], ...patch };
|
|
375
|
+
// A live engine gets it too, so the factory does not silently describe a state
|
|
376
|
+
// the engine is not in.
|
|
377
|
+
if (this.#play && patch)
|
|
378
|
+
this.#play[kind](patch);
|
|
379
|
+
return this;
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
/** Keyboard → action (`KeyboardEvent.key`). */
|
|
383
|
+
export const UI_KEYMAP = Object.freeze({
|
|
384
|
+
ArrowUp: 'up',
|
|
385
|
+
ArrowDown: 'down',
|
|
386
|
+
ArrowLeft: 'left',
|
|
387
|
+
ArrowRight: 'right',
|
|
388
|
+
Enter: 'accept',
|
|
389
|
+
' ': 'accept',
|
|
390
|
+
Escape: 'back',
|
|
391
|
+
Backspace: 'back',
|
|
392
|
+
Tab: 'more',
|
|
393
|
+
v: 'more',
|
|
394
|
+
V: 'more',
|
|
395
|
+
ContextMenu: 'more',
|
|
396
|
+
q: 'prev',
|
|
397
|
+
Q: 'prev',
|
|
398
|
+
e: 'next',
|
|
399
|
+
E: 'next',
|
|
400
|
+
F1: 'menu',
|
|
401
|
+
});
|
|
402
|
+
/**
|
|
403
|
+
* Gamepad button index (W3C "standard" mapping) → action. A = 0, B = 1, X = 2, Y = 3,
|
|
404
|
+
* LB = 4, RB = 5, Select = 8, Start = 9, d-pad = 12–15. Select + Start together is
|
|
405
|
+
* `menu` as well (see {@link createInput}).
|
|
406
|
+
*/
|
|
407
|
+
export const UI_PADMAP = Object.freeze({
|
|
408
|
+
0: 'accept',
|
|
409
|
+
1: 'back',
|
|
410
|
+
2: 'more',
|
|
411
|
+
3: 'more',
|
|
412
|
+
4: 'prev',
|
|
413
|
+
5: 'next',
|
|
414
|
+
9: 'menu',
|
|
415
|
+
12: 'up',
|
|
416
|
+
13: 'down',
|
|
417
|
+
14: 'left',
|
|
418
|
+
15: 'right',
|
|
419
|
+
});
|
|
420
|
+
/** Hold-to-repeat for directions: first repeat after `delay` ms, then every `interval` ms. */
|
|
421
|
+
export const UI_REPEAT = Object.freeze({ delay: 380, interval: 110, axis: 0.6 });
|
|
422
|
+
const DIRECTIONS = new Set(['up', 'down', 'left', 'right']);
|
|
423
|
+
const isEditable = (target) => {
|
|
424
|
+
const element = target;
|
|
425
|
+
if (!element)
|
|
426
|
+
return false;
|
|
427
|
+
if (element.isContentEditable)
|
|
428
|
+
return true;
|
|
429
|
+
return element.tagName === 'INPUT' || element.tagName === 'TEXTAREA' || element.tagName === 'SELECT';
|
|
430
|
+
};
|
|
431
|
+
/**
|
|
432
|
+
* The scheme's runtime: keyboard and gamepads become {@link UiAction}s.
|
|
433
|
+
*
|
|
434
|
+
* Keyboard: `keydown` mapped through {@link UI_KEYMAP} (keys typed into form fields
|
|
435
|
+
* are left alone). Gamepads: polled each frame through {@link UI_PADMAP} and the left
|
|
436
|
+
* stick; directions repeat with {@link UI_REPEAT}; Select + Start together is `menu`
|
|
437
|
+
* (and then neither fires on its own). While {@link UiInput.suspend | suspended} (in
|
|
438
|
+
* game) the game gets every input except the menu combo: Select + Start and the
|
|
439
|
+
* `menuKeys` (Escape, F1) still arrive, as `menu`, so the pause menu can always open.
|
|
440
|
+
*/
|
|
441
|
+
export function createInput(options = {}) {
|
|
442
|
+
const target = options.target ?? globalThis;
|
|
443
|
+
const capture = options.capture ?? true;
|
|
444
|
+
const swallow = options.swallow ?? true;
|
|
445
|
+
const keymap = options.keymap ?? UI_KEYMAP;
|
|
446
|
+
const menuKeys = new Set(options.menuKeys ?? ['Escape', 'F1']);
|
|
447
|
+
const padmap = options.padmap ?? UI_PADMAP;
|
|
448
|
+
const now = options.now ?? (() => globalThis.performance?.now() ?? Date.now());
|
|
449
|
+
const gamepads = options.gamepads ??
|
|
450
|
+
(() => (globalThis.navigator?.getGamepads?.() ?? []));
|
|
451
|
+
const schedule = options.schedule === undefined
|
|
452
|
+
? (globalThis.requestAnimationFrame?.bind(globalThis) ?? null)
|
|
453
|
+
: options.schedule;
|
|
454
|
+
const listeners = new Set();
|
|
455
|
+
const suspendListeners = new Set();
|
|
456
|
+
let suspended = false;
|
|
457
|
+
let destroyed = false;
|
|
458
|
+
let polling = false;
|
|
459
|
+
const held = new Map();
|
|
460
|
+
// A snapshot: a listener that subscribes another one (a screen opening the next)
|
|
461
|
+
// must not hand it the same action — a Set also visits entries added while it is
|
|
462
|
+
// being iterated, so one Enter would open a screen and activate its focused item.
|
|
463
|
+
// A listener removed by an earlier one in the same dispatch is skipped.
|
|
464
|
+
const fire = (action, detail) => {
|
|
465
|
+
for (const listener of [...listeners]) {
|
|
466
|
+
if (listeners.has(listener))
|
|
467
|
+
listener(action, detail);
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
const onKey = (event) => {
|
|
471
|
+
if (destroyed)
|
|
472
|
+
return;
|
|
473
|
+
const key = event;
|
|
474
|
+
if (suspended) {
|
|
475
|
+
if (!menuKeys.has(key.key) || key.repeat)
|
|
476
|
+
return;
|
|
477
|
+
key.preventDefault();
|
|
478
|
+
key.stopPropagation();
|
|
479
|
+
fire('menu', { source: 'keyboard', repeat: false });
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
if (isEditable(key.target) && key.key !== 'Escape')
|
|
483
|
+
return;
|
|
484
|
+
const action = keymap[key.key];
|
|
485
|
+
if (!action)
|
|
486
|
+
return;
|
|
487
|
+
if (swallow) {
|
|
488
|
+
key.preventDefault();
|
|
489
|
+
key.stopPropagation();
|
|
490
|
+
}
|
|
491
|
+
fire(action, { source: 'keyboard', repeat: key.repeat === true });
|
|
492
|
+
};
|
|
493
|
+
const pressed = (pad) => {
|
|
494
|
+
const actions = new Set();
|
|
495
|
+
const select = pad.buttons[8]?.pressed === true;
|
|
496
|
+
const start = pad.buttons[9]?.pressed === true;
|
|
497
|
+
if (select && start)
|
|
498
|
+
actions.add('menu');
|
|
499
|
+
pad.buttons.forEach((button, index) => {
|
|
500
|
+
if (!button.pressed)
|
|
501
|
+
return;
|
|
502
|
+
if ((index === 8 || index === 9) && select && start)
|
|
503
|
+
return;
|
|
504
|
+
const action = padmap[index];
|
|
505
|
+
if (action)
|
|
506
|
+
actions.add(action);
|
|
507
|
+
});
|
|
508
|
+
const [x = 0, y = 0] = pad.axes;
|
|
509
|
+
if (x < -UI_REPEAT.axis)
|
|
510
|
+
actions.add('left');
|
|
511
|
+
if (x > UI_REPEAT.axis)
|
|
512
|
+
actions.add('right');
|
|
513
|
+
if (y < -UI_REPEAT.axis)
|
|
514
|
+
actions.add('up');
|
|
515
|
+
if (y > UI_REPEAT.axis)
|
|
516
|
+
actions.add('down');
|
|
517
|
+
return actions;
|
|
518
|
+
};
|
|
519
|
+
const poll = () => {
|
|
520
|
+
if (destroyed)
|
|
521
|
+
return;
|
|
522
|
+
const t = now();
|
|
523
|
+
const active = new Set();
|
|
524
|
+
for (const pad of gamepads())
|
|
525
|
+
if (pad)
|
|
526
|
+
for (const action of pressed(pad))
|
|
527
|
+
active.add(action);
|
|
528
|
+
for (const action of active) {
|
|
529
|
+
const state = held.get(action);
|
|
530
|
+
if (!state) {
|
|
531
|
+
held.set(action, { since: t, last: t });
|
|
532
|
+
// In game only the Select + Start combo gets through (plain Start is the game's).
|
|
533
|
+
const combo = action === 'menu' && gamepads().some((p) => p?.buttons[8]?.pressed && p.buttons[9]?.pressed);
|
|
534
|
+
if (!suspended || combo)
|
|
535
|
+
fire(action, { source: 'gamepad', repeat: false });
|
|
536
|
+
}
|
|
537
|
+
else if (DIRECTIONS.has(action) &&
|
|
538
|
+
t - state.since >= UI_REPEAT.delay &&
|
|
539
|
+
t - state.last >= UI_REPEAT.interval) {
|
|
540
|
+
state.last = t;
|
|
541
|
+
if (!suspended)
|
|
542
|
+
fire(action, { source: 'gamepad', repeat: true });
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
for (const action of [...held.keys()])
|
|
546
|
+
if (!active.has(action))
|
|
547
|
+
held.delete(action);
|
|
548
|
+
};
|
|
549
|
+
const loop = () => {
|
|
550
|
+
if (destroyed || !schedule)
|
|
551
|
+
return;
|
|
552
|
+
poll();
|
|
553
|
+
schedule(loop);
|
|
554
|
+
};
|
|
555
|
+
const startPolling = () => {
|
|
556
|
+
if (polling || !schedule)
|
|
557
|
+
return;
|
|
558
|
+
polling = true;
|
|
559
|
+
schedule(loop);
|
|
560
|
+
};
|
|
561
|
+
const setSuspended = (value) => {
|
|
562
|
+
if (destroyed || suspended === value)
|
|
563
|
+
return;
|
|
564
|
+
suspended = value;
|
|
565
|
+
for (const listener of [...suspendListeners]) {
|
|
566
|
+
if (suspendListeners.has(listener))
|
|
567
|
+
listener(value);
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
target.addEventListener('keydown', onKey, { capture });
|
|
571
|
+
target.addEventListener('gamepadconnected', startPolling);
|
|
572
|
+
if (gamepads().some(Boolean))
|
|
573
|
+
startPolling();
|
|
574
|
+
return {
|
|
575
|
+
on(listener) {
|
|
576
|
+
listeners.add(listener);
|
|
577
|
+
return () => listeners.delete(listener);
|
|
578
|
+
},
|
|
579
|
+
suspend() {
|
|
580
|
+
setSuspended(true);
|
|
581
|
+
},
|
|
582
|
+
resume() {
|
|
583
|
+
setSuspended(false);
|
|
584
|
+
},
|
|
585
|
+
get suspended() {
|
|
586
|
+
return suspended;
|
|
587
|
+
},
|
|
588
|
+
onSuspend(listener) {
|
|
589
|
+
suspendListeners.add(listener);
|
|
590
|
+
return () => suspendListeners.delete(listener);
|
|
591
|
+
},
|
|
592
|
+
trigger(action, detail = { source: 'touch', repeat: false }) {
|
|
593
|
+
if (destroyed)
|
|
594
|
+
return;
|
|
595
|
+
if (suspended && action !== 'menu')
|
|
596
|
+
return;
|
|
597
|
+
fire(action, detail);
|
|
598
|
+
},
|
|
599
|
+
poll,
|
|
600
|
+
destroy() {
|
|
601
|
+
destroyed = true;
|
|
602
|
+
listeners.clear();
|
|
603
|
+
suspendListeners.clear();
|
|
604
|
+
held.clear();
|
|
605
|
+
target.removeEventListener('keydown', onKey, { capture });
|
|
606
|
+
target.removeEventListener('gamepadconnected', startPolling);
|
|
607
|
+
},
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
/**
|
|
611
|
+
* Spatial navigation: the candidate a direction leads to from `from`, or null.
|
|
612
|
+
*
|
|
613
|
+
* Only candidates whose centre lies ahead in that direction count; among them the
|
|
614
|
+
* nearest wins, with sideways distance weighted double so "down" prefers the item
|
|
615
|
+
* straight below over a closer one off to the side.
|
|
616
|
+
*/
|
|
617
|
+
export function nextFocus(from, candidates, direction) {
|
|
618
|
+
const centre = (el) => {
|
|
619
|
+
const r = el.getBoundingClientRect();
|
|
620
|
+
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
|
|
621
|
+
};
|
|
622
|
+
const origin = centre(from);
|
|
623
|
+
let best = null;
|
|
624
|
+
let bestScore = Infinity;
|
|
625
|
+
for (const candidate of candidates) {
|
|
626
|
+
if (candidate === from)
|
|
627
|
+
continue;
|
|
628
|
+
const c = centre(candidate);
|
|
629
|
+
const dx = c.x - origin.x;
|
|
630
|
+
const dy = c.y - origin.y;
|
|
631
|
+
const ahead = direction === 'up' ? -dy : direction === 'down' ? dy : direction === 'left' ? -dx : dx;
|
|
632
|
+
if (ahead <= 0.5)
|
|
633
|
+
continue;
|
|
634
|
+
const side = direction === 'up' || direction === 'down' ? Math.abs(dx) : Math.abs(dy);
|
|
635
|
+
const score = ahead + side * 2;
|
|
636
|
+
if (score < bestScore) {
|
|
637
|
+
bestScore = score;
|
|
638
|
+
best = candidate;
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
return best;
|
|
642
|
+
}
|
|
643
|
+
/**
|
|
644
|
+
* The look every menu shares, as CSS custom properties: the focus ring, radii, type
|
|
645
|
+
* faces, colours and spacing. Apps read them with `var(--wg-…)`; {@link uiTokensCss}
|
|
646
|
+
* writes them into a stylesheet.
|
|
647
|
+
*/
|
|
648
|
+
export const UI_TOKENS = Object.freeze({
|
|
649
|
+
'--wg-bg': '#07080c',
|
|
650
|
+
'--wg-surface': 'rgb(18 20 28 / 0.78)',
|
|
651
|
+
'--wg-line': 'rgb(255 255 255 / 0.12)',
|
|
652
|
+
'--wg-text': '#f4f6fb',
|
|
653
|
+
'--wg-muted': '#8e97a9',
|
|
654
|
+
'--wg-ok': '#4ade80',
|
|
655
|
+
'--wg-danger': '#f87171',
|
|
656
|
+
'--wg-focus': '#ffffff',
|
|
657
|
+
'--wg-focus-ring': '0 0 0 3px #ffffff',
|
|
658
|
+
'--wg-radius': '22px',
|
|
659
|
+
'--wg-radius-small': '12px',
|
|
660
|
+
'--wg-gap': '16px',
|
|
661
|
+
'--wg-font-display': "'Unbounded Variable', 'Unbounded', system-ui, sans-serif",
|
|
662
|
+
'--wg-font-ui': "'Inter Variable', 'Inter', system-ui, -apple-system, 'Segoe UI', sans-serif",
|
|
663
|
+
'--wg-ease': 'cubic-bezier(0.2, 0.8, 0.2, 1)',
|
|
664
|
+
'--wg-safe-top': 'env(safe-area-inset-top, 0px)',
|
|
665
|
+
'--wg-safe-bottom': 'env(safe-area-inset-bottom, 0px)',
|
|
666
|
+
});
|
|
667
|
+
/** `UI_TOKENS` as a CSS rule, e.g. for a `<style>` an app injects. */
|
|
668
|
+
export function uiTokensCss(selector = ':root') {
|
|
669
|
+
const body = Object.entries(UI_TOKENS)
|
|
670
|
+
.map(([name, value]) => ` ${name}: ${value};`)
|
|
671
|
+
.join('\n');
|
|
672
|
+
return `${selector} {\n${body}\n}\n`;
|
|
673
|
+
}
|
|
674
|
+
/** Standard-mapping indices the pad uses. */
|
|
675
|
+
const PAD = Object.freeze({ up: 12, down: 13, left: 14, right: 15 });
|
|
676
|
+
const PAD_BUTTONS = 17;
|
|
677
|
+
const PAD_AXES = 4;
|
|
678
|
+
/**
|
|
679
|
+
* One layout per system. Each label presses the standard button that the system's
|
|
680
|
+
* emulator binds to that console button by default, so no emulator is reconfigured:
|
|
681
|
+
*
|
|
682
|
+
* - Mega Drive (BlastEm `default.cfg`): A=0, B=1, C=5 (right shoulder), X=2, Y=3,
|
|
683
|
+
* Z=4 (left shoulder), Mode=8, Start=9. Six buttons: the launcher plugs 6-button
|
|
684
|
+
* pads, and a 3-button game ignores X Y Z.
|
|
685
|
+
* - Neo Geo (FBNeo: "fire N" is joystick button N-1): A=0, B=1, C=2, D=3 — drawn
|
|
686
|
+
* as the Neo Geo CD pad's diamond (A bottom, B right, C left, D top), which is
|
|
687
|
+
* where those indices sit on a standard pad.
|
|
688
|
+
* - SNES (snes9x, by position): B=0, A=1, Y=2, X=3, L=4, R=5.
|
|
689
|
+
* - GBA / GBC / GB (mGBA): A=0, B=1, L=4, R=5.
|
|
690
|
+
*
|
|
691
|
+
* Everywhere Select = 8 and Start = 9.
|
|
692
|
+
*/
|
|
693
|
+
export const TOUCH_LAYOUTS = Object.freeze({
|
|
694
|
+
megadrive: {
|
|
695
|
+
system: 'megadrive',
|
|
696
|
+
title: 'Mega Drive',
|
|
697
|
+
aspect: 4 / 3,
|
|
698
|
+
faces: [
|
|
699
|
+
{ label: 'X', index: 2, x: 0.18, y: 0.32, size: 0.25 },
|
|
700
|
+
{ label: 'Y', index: 3, x: 0.5, y: 0.26, size: 0.25 },
|
|
701
|
+
{ label: 'Z', index: 4, x: 0.82, y: 0.2, size: 0.25 },
|
|
702
|
+
{ label: 'A', index: 0, x: 0.18, y: 0.7, size: 0.3 },
|
|
703
|
+
{ label: 'B', index: 1, x: 0.5, y: 0.64, size: 0.3 },
|
|
704
|
+
{ label: 'C', index: 5, x: 0.82, y: 0.58, size: 0.3 },
|
|
705
|
+
],
|
|
706
|
+
start: { label: 'Start', index: 9 },
|
|
707
|
+
},
|
|
708
|
+
neogeo: {
|
|
709
|
+
system: 'neogeo',
|
|
710
|
+
title: 'Neo Geo',
|
|
711
|
+
aspect: 4 / 3,
|
|
712
|
+
faces: [
|
|
713
|
+
// The Neo Geo CD pad's diamond: D top, C left, B right, A bottom.
|
|
714
|
+
{ label: 'D', index: 3, x: 0.5, y: 0.18, size: 0.32, color: '#3b82f6' },
|
|
715
|
+
{ label: 'C', index: 2, x: 0.18, y: 0.5, size: 0.32, color: '#22c55e' },
|
|
716
|
+
{ label: 'B', index: 1, x: 0.82, y: 0.5, size: 0.32, color: '#facc15' },
|
|
717
|
+
{ label: 'A', index: 0, x: 0.5, y: 0.82, size: 0.32, color: '#ef4444' },
|
|
718
|
+
],
|
|
719
|
+
select: { label: 'Select', index: 8 },
|
|
720
|
+
start: { label: 'Start', index: 9 },
|
|
721
|
+
},
|
|
722
|
+
snes: {
|
|
723
|
+
system: 'snes',
|
|
724
|
+
title: 'Super Nintendo',
|
|
725
|
+
aspect: 4 / 3,
|
|
726
|
+
faces: [
|
|
727
|
+
{ label: 'X', index: 3, x: 0.5, y: 0.18, size: 0.32, color: '#3b82f6' },
|
|
728
|
+
{ label: 'Y', index: 2, x: 0.18, y: 0.5, size: 0.32, color: '#22c55e' },
|
|
729
|
+
{ label: 'A', index: 1, x: 0.82, y: 0.5, size: 0.32, color: '#ef4444' },
|
|
730
|
+
{ label: 'B', index: 0, x: 0.5, y: 0.82, size: 0.32, color: '#facc15' },
|
|
731
|
+
],
|
|
732
|
+
l: { label: 'L', index: 4 },
|
|
733
|
+
r: { label: 'R', index: 5 },
|
|
734
|
+
select: { label: 'Select', index: 8 },
|
|
735
|
+
start: { label: 'Start', index: 9 },
|
|
736
|
+
},
|
|
737
|
+
gba: {
|
|
738
|
+
system: 'gba',
|
|
739
|
+
title: 'Game Boy Advance',
|
|
740
|
+
aspect: 3 / 2,
|
|
741
|
+
faces: [
|
|
742
|
+
{ label: 'B', index: 1, x: 0.28, y: 0.64, size: 0.38 },
|
|
743
|
+
{ label: 'A', index: 0, x: 0.72, y: 0.4, size: 0.38 },
|
|
744
|
+
],
|
|
745
|
+
l: { label: 'L', index: 4 },
|
|
746
|
+
r: { label: 'R', index: 5 },
|
|
747
|
+
select: { label: 'Select', index: 8 },
|
|
748
|
+
start: { label: 'Start', index: 9 },
|
|
749
|
+
},
|
|
750
|
+
gbc: {
|
|
751
|
+
system: 'gbc',
|
|
752
|
+
title: 'Game Boy Color',
|
|
753
|
+
aspect: 10 / 9,
|
|
754
|
+
faces: [
|
|
755
|
+
{ label: 'B', index: 1, x: 0.28, y: 0.64, size: 0.38 },
|
|
756
|
+
{ label: 'A', index: 0, x: 0.72, y: 0.4, size: 0.38 },
|
|
757
|
+
],
|
|
758
|
+
select: { label: 'Select', index: 8 },
|
|
759
|
+
start: { label: 'Start', index: 9 },
|
|
760
|
+
},
|
|
761
|
+
gb: {
|
|
762
|
+
system: 'gb',
|
|
763
|
+
title: 'Game Boy',
|
|
764
|
+
aspect: 10 / 9,
|
|
765
|
+
faces: [
|
|
766
|
+
{ label: 'B', index: 1, x: 0.28, y: 0.64, size: 0.38 },
|
|
767
|
+
{ label: 'A', index: 0, x: 0.72, y: 0.4, size: 0.38 },
|
|
768
|
+
],
|
|
769
|
+
select: { label: 'Select', index: 8 },
|
|
770
|
+
start: { label: 'Start', index: 9 },
|
|
771
|
+
},
|
|
772
|
+
});
|
|
773
|
+
/** Smallest touch target (UX.md rule 8). */
|
|
774
|
+
const TOUCH_MIN = 48;
|
|
775
|
+
/** The d-pad is drawn at this fraction of its slot, centred; the buttons fill theirs. */
|
|
776
|
+
const DPAD_SCALE = 0.8;
|
|
777
|
+
/** A square of `fraction` of `slot`'s side, centred in it. */
|
|
778
|
+
const shrink = (slot, fraction) => {
|
|
779
|
+
const side = Math.round(slot.width * fraction);
|
|
780
|
+
return rect(slot.x + (slot.width - side) / 2, slot.y + (slot.height - side) / 2, side, side);
|
|
781
|
+
};
|
|
782
|
+
const clamp = (value, min, max) => Math.min(max, Math.max(min, value));
|
|
783
|
+
const rect = (x, y, width, height) => ({
|
|
784
|
+
x: Math.round(x),
|
|
785
|
+
y: Math.round(y),
|
|
786
|
+
width: Math.round(width),
|
|
787
|
+
height: Math.round(height),
|
|
788
|
+
});
|
|
789
|
+
/**
|
|
790
|
+
* Lays a pad out. **Portrait**: the pad takes the bottom half — shoulders and the
|
|
791
|
+
* pause button along its top, the d-pad left, the buttons right, Select / Start
|
|
792
|
+
* along its bottom — and the game gets the top half. **Landscape**: the game is
|
|
793
|
+
* centred and the controls sit on its sides — L and the d-pad and Select on the
|
|
794
|
+
* left; pause, R, the buttons and Start on the right. When sides wide enough would
|
|
795
|
+
* shrink the game below `minGameScale` of the screen's height (a 4:3 tablet), the
|
|
796
|
+
* game keeps the whole screen and the controls overlay its edges.
|
|
797
|
+
*/
|
|
798
|
+
export function placeTouchPad(layout, viewport, options = {}) {
|
|
799
|
+
const scale = clamp(options.scale ?? 1, 0.75, 1.4);
|
|
800
|
+
const minGameScale = options.minGameScale ?? 0.7;
|
|
801
|
+
const { width: W, height: H } = viewport;
|
|
802
|
+
const safe = viewport.safe ?? { top: 0, right: 0, bottom: 0, left: 0 };
|
|
803
|
+
const faces = (cluster) => layout.faces.map((face) => ({
|
|
804
|
+
label: face.label,
|
|
805
|
+
index: face.index,
|
|
806
|
+
cx: Math.round(cluster.x + face.x * cluster.width),
|
|
807
|
+
cy: Math.round(cluster.y + face.y * cluster.height),
|
|
808
|
+
r: Math.round((face.size * cluster.width) / 2),
|
|
809
|
+
...(face.color ? { color: face.color } : {}),
|
|
810
|
+
}));
|
|
811
|
+
const key = (id, spec, at) => (spec ? [{ id, label: spec.label, index: spec.index, rect: at }] : []);
|
|
812
|
+
if (H >= W) {
|
|
813
|
+
// ---- portrait: the bottom half
|
|
814
|
+
const half = Math.round(H / 2);
|
|
815
|
+
const zone = rect(0, half, W, H - half);
|
|
816
|
+
const inner = rect(safe.left, half, W - safe.left - safe.right, H - half - safe.bottom);
|
|
817
|
+
const m = Math.round(clamp(inner.width * 0.04, 10, 24));
|
|
818
|
+
const rowH = TOUCH_MIN;
|
|
819
|
+
const top = inner.y + m;
|
|
820
|
+
const bottom = inner.y + inner.height - m - rowH;
|
|
821
|
+
const middleTop = top + rowH + Math.round(m / 2);
|
|
822
|
+
const middleH = bottom - Math.round(m / 2) - middleTop;
|
|
823
|
+
// The d-pad and the cluster are squares of the same side: as big as the half
|
|
824
|
+
// allows, capped for tablets, then scaled — never beyond the room there is.
|
|
825
|
+
const side = Math.round(Math.min(middleH, inner.width * 0.47, Math.min(middleH, inner.width * 0.44, 240) * scale));
|
|
826
|
+
const dpad = shrink(rect(inner.x + m, middleTop + (middleH - side) / 2, side, side), DPAD_SCALE);
|
|
827
|
+
const cluster = rect(inner.x + inner.width - m - side, middleTop + (middleH - side) / 2, side, side);
|
|
828
|
+
const shoulderW = clamp(inner.width * 0.28, 88, 160);
|
|
829
|
+
const pillW = clamp(inner.width * 0.2, 72, 112);
|
|
830
|
+
const pauseW = 56;
|
|
831
|
+
const centre = inner.x + inner.width / 2;
|
|
832
|
+
return {
|
|
833
|
+
orientation: 'portrait',
|
|
834
|
+
overlay: false,
|
|
835
|
+
gameArea: rect(safe.left, safe.top, W - safe.left - safe.right, half - safe.top),
|
|
836
|
+
zones: [zone],
|
|
837
|
+
dpad,
|
|
838
|
+
cluster,
|
|
839
|
+
faces: faces(cluster),
|
|
840
|
+
keys: [
|
|
841
|
+
...key('l', layout.l, rect(inner.x + m, top, shoulderW, rowH)),
|
|
842
|
+
...key('r', layout.r, rect(inner.x + inner.width - m - shoulderW, top, shoulderW, rowH)),
|
|
843
|
+
{ id: 'pause', label: 'Pause', index: null, rect: rect(centre - pauseW / 2, top, pauseW, rowH) },
|
|
844
|
+
...key('select', layout.select, rect(centre - 8 - pillW, bottom, pillW, rowH)),
|
|
845
|
+
...key('start', layout.start, rect(layout.select ? centre + 8 : centre - pillW / 2, bottom, pillW, rowH)),
|
|
846
|
+
],
|
|
847
|
+
};
|
|
848
|
+
}
|
|
849
|
+
// ---- landscape: the sides
|
|
850
|
+
const fullH = H - safe.top - safe.bottom;
|
|
851
|
+
const usableW = W - safe.left - safe.right;
|
|
852
|
+
const m = Math.round(clamp(fullH * 0.035, 8, 20));
|
|
853
|
+
const rowH = TOUCH_MIN;
|
|
854
|
+
const control = Math.round(clamp(Math.min(fullH * 0.42, 200), 112, 200) * scale);
|
|
855
|
+
const sideNeeded = control + 2 * m;
|
|
856
|
+
const gameWFull = Math.min(usableW, fullH * layout.aspect);
|
|
857
|
+
let gameW = gameWFull;
|
|
858
|
+
let overlay = false;
|
|
859
|
+
if ((usableW - gameWFull) / 2 < sideNeeded) {
|
|
860
|
+
const shrunkW = usableW - 2 * sideNeeded;
|
|
861
|
+
const shrunkScale = shrunkW / layout.aspect / fullH;
|
|
862
|
+
if (shrunkScale >= minGameScale)
|
|
863
|
+
gameW = shrunkW;
|
|
864
|
+
else
|
|
865
|
+
overlay = true;
|
|
866
|
+
}
|
|
867
|
+
const sideW = overlay ? sideNeeded : (usableW - gameW) / 2;
|
|
868
|
+
const gameH = overlay ? fullH : Math.min(fullH, gameW / layout.aspect);
|
|
869
|
+
const gameArea = overlay
|
|
870
|
+
? rect(safe.left, safe.top, usableW, fullH)
|
|
871
|
+
: rect(safe.left + sideW, safe.top + (fullH - gameH) / 2, gameW, gameH);
|
|
872
|
+
const leftX = safe.left;
|
|
873
|
+
const rightX = W - safe.right - sideW;
|
|
874
|
+
const top = safe.top + m;
|
|
875
|
+
const bottom = H - safe.bottom - m - rowH;
|
|
876
|
+
// The top row always exists — it holds the pause button, and the shoulders when
|
|
877
|
+
// the console has them.
|
|
878
|
+
const middleTop = top + rowH + m;
|
|
879
|
+
const middleH = bottom - m - middleTop;
|
|
880
|
+
const side = Math.round(Math.min(control, middleH, sideW - 2 * m));
|
|
881
|
+
const dpad = shrink(rect(leftX + (sideW - side) / 2, middleTop + (middleH - side) / 2, side, side), DPAD_SCALE);
|
|
882
|
+
const cluster = rect(rightX + (sideW - side) / 2, middleTop + (middleH - side) / 2, side, side);
|
|
883
|
+
const pauseW = 48;
|
|
884
|
+
const shoulderW = clamp(sideW - 2 * m - (pauseW + m), 64, 140);
|
|
885
|
+
const pillW = clamp(sideW * 0.5, 72, 112);
|
|
886
|
+
return {
|
|
887
|
+
orientation: 'landscape',
|
|
888
|
+
overlay,
|
|
889
|
+
gameArea,
|
|
890
|
+
zones: [rect(0, 0, leftX + sideW, H), rect(rightX, 0, W - rightX, H)],
|
|
891
|
+
dpad,
|
|
892
|
+
cluster,
|
|
893
|
+
faces: faces(cluster),
|
|
894
|
+
keys: [
|
|
895
|
+
...key('l', layout.l, rect(leftX + m, top, shoulderW, rowH)),
|
|
896
|
+
...key('r', layout.r, rect(rightX + m, top, shoulderW, rowH)),
|
|
897
|
+
{ id: 'pause', label: 'Pause', index: null, rect: rect(rightX + sideW - m - pauseW, top, pauseW, rowH) },
|
|
898
|
+
...key('select', layout.select, rect(leftX + (sideW - pillW) / 2, bottom, pillW, rowH)),
|
|
899
|
+
...key('start', layout.start, rect(rightX + (sideW - pillW) / 2, bottom, pillW, rowH)),
|
|
900
|
+
],
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
/** The pad's `Gamepad.id`. */
|
|
904
|
+
export const TOUCH_PAD_ID = 'wasm-gaming touch pad (STANDARD GAMEPAD)';
|
|
905
|
+
/** A finger landing this close to a key (px) still takes it. */
|
|
906
|
+
const KEY_SLOP = 8;
|
|
907
|
+
/** Standard d-pad indices for a point, from its angle around the d-pad's centre. */
|
|
908
|
+
export function touchDpadAt(dpad, x, y) {
|
|
909
|
+
const dx = x - (dpad.x + dpad.width / 2);
|
|
910
|
+
const dy = y - (dpad.y + dpad.height / 2);
|
|
911
|
+
// A dead zone in the middle: resting the thumb on the hub presses nothing.
|
|
912
|
+
if (Math.hypot(dx, dy) < dpad.width * 0.11)
|
|
913
|
+
return [];
|
|
914
|
+
// Eight sectors of 45°, the cardinal ones centred on their axis.
|
|
915
|
+
const sector = (Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) + 8) % 8;
|
|
916
|
+
return [
|
|
917
|
+
[PAD.right],
|
|
918
|
+
[PAD.right, PAD.down],
|
|
919
|
+
[PAD.down],
|
|
920
|
+
[PAD.down, PAD.left],
|
|
921
|
+
[PAD.left],
|
|
922
|
+
[PAD.left, PAD.up],
|
|
923
|
+
[PAD.up],
|
|
924
|
+
[PAD.up, PAD.right],
|
|
925
|
+
][sector];
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Face buttons under a point. Each takes a circle a little larger than it is drawn
|
|
929
|
+
* (never under the 48 px minimum), so the gap between two neighbours presses both —
|
|
930
|
+
* the arcade "roll" — and a thumb slides from one to the next without lifting.
|
|
931
|
+
*/
|
|
932
|
+
export function touchFacesAt(placement, x, y) {
|
|
933
|
+
const out = [];
|
|
934
|
+
for (const face of placement.faces) {
|
|
935
|
+
const reach = Math.max(face.r * 1.18, TOUCH_MIN / 2);
|
|
936
|
+
if (Math.hypot(x - face.cx, y - face.cy) <= reach)
|
|
937
|
+
out.push(face.index);
|
|
938
|
+
}
|
|
939
|
+
return out;
|
|
940
|
+
}
|
|
941
|
+
const inside = (r, x, y, slop = 0) => x >= r.x - slop && x <= r.x + r.width + slop && y >= r.y - slop && y <= r.y + r.height + slop;
|
|
942
|
+
const grow = (r, by) => ({
|
|
943
|
+
x: r.x - r.width * by,
|
|
944
|
+
y: r.y - r.height * by,
|
|
945
|
+
width: r.width * (1 + 2 * by),
|
|
946
|
+
height: r.height * (1 + 2 * by),
|
|
947
|
+
});
|
|
948
|
+
export function createTouchPadCore(options = {}) {
|
|
949
|
+
const now = options.now ?? (() => globalThis.performance?.now() ?? Date.now());
|
|
950
|
+
const minHold = options.minHold ?? 50;
|
|
951
|
+
const gamepad = {
|
|
952
|
+
id: TOUCH_PAD_ID,
|
|
953
|
+
index: 0,
|
|
954
|
+
connected: false,
|
|
955
|
+
mapping: 'standard',
|
|
956
|
+
timestamp: 0,
|
|
957
|
+
buttons: Array.from({ length: PAD_BUTTONS }, () => ({ pressed: false, touched: false, value: 0 })),
|
|
958
|
+
axes: Array.from({ length: PAD_AXES }, () => 0),
|
|
959
|
+
vibrationActuator: null,
|
|
960
|
+
};
|
|
961
|
+
let placement = null;
|
|
962
|
+
const fingers = new Map();
|
|
963
|
+
/** When each pressed index went down. */
|
|
964
|
+
const since = new Map();
|
|
965
|
+
/** Latched: released early, held until then. */
|
|
966
|
+
const latched = new Map();
|
|
967
|
+
const changeListeners = new Set();
|
|
968
|
+
const pauseListeners = new Set();
|
|
969
|
+
const live = () => {
|
|
970
|
+
const set = new Set();
|
|
971
|
+
for (const finger of fingers.values())
|
|
972
|
+
for (const index of finger.indices)
|
|
973
|
+
set.add(index);
|
|
974
|
+
return set;
|
|
975
|
+
};
|
|
976
|
+
const sync = () => {
|
|
977
|
+
const t = now();
|
|
978
|
+
const held = live();
|
|
979
|
+
for (const [index, until] of [...latched])
|
|
980
|
+
if (until <= t || held.has(index))
|
|
981
|
+
latched.delete(index);
|
|
982
|
+
for (const index of [...since.keys()]) {
|
|
983
|
+
if (held.has(index))
|
|
984
|
+
continue;
|
|
985
|
+
const start = since.get(index) ?? t;
|
|
986
|
+
if (t < start + minHold)
|
|
987
|
+
latched.set(index, start + minHold);
|
|
988
|
+
since.delete(index);
|
|
989
|
+
}
|
|
990
|
+
const effective = new Set([...held, ...latched.keys()]);
|
|
991
|
+
const wentDown = [];
|
|
992
|
+
let changed = false;
|
|
993
|
+
gamepad.buttons.forEach((button, index) => {
|
|
994
|
+
const on = effective.has(index);
|
|
995
|
+
if (on === button.pressed)
|
|
996
|
+
return;
|
|
997
|
+
changed = true;
|
|
998
|
+
button.pressed = on;
|
|
999
|
+
button.touched = on;
|
|
1000
|
+
button.value = on ? 1 : 0;
|
|
1001
|
+
if (on)
|
|
1002
|
+
wentDown.push(index);
|
|
1003
|
+
});
|
|
1004
|
+
for (const index of held)
|
|
1005
|
+
if (!since.has(index))
|
|
1006
|
+
since.set(index, t);
|
|
1007
|
+
if (!changed)
|
|
1008
|
+
return;
|
|
1009
|
+
gamepad.timestamp = t;
|
|
1010
|
+
for (const listener of [...changeListeners])
|
|
1011
|
+
listener(wentDown);
|
|
1012
|
+
};
|
|
1013
|
+
const indicesFor = (control, x, y) => {
|
|
1014
|
+
if (!placement)
|
|
1015
|
+
return [];
|
|
1016
|
+
if (control === 'dpad')
|
|
1017
|
+
return touchDpadAt(placement.dpad, x, y);
|
|
1018
|
+
if (control === 'cluster')
|
|
1019
|
+
return touchFacesAt(placement, x, y);
|
|
1020
|
+
const key = placement.keys.find((k) => k.id === control);
|
|
1021
|
+
if (!key || key.index === null)
|
|
1022
|
+
return [];
|
|
1023
|
+
return inside(key.rect, x, y, KEY_SLOP) ? [key.index] : [];
|
|
1024
|
+
};
|
|
1025
|
+
const controlAt = (x, y) => {
|
|
1026
|
+
if (!placement)
|
|
1027
|
+
return null;
|
|
1028
|
+
for (const key of placement.keys)
|
|
1029
|
+
if (inside(key.rect, x, y, KEY_SLOP))
|
|
1030
|
+
return key.id;
|
|
1031
|
+
const { dpad, cluster } = placement;
|
|
1032
|
+
const nearDpad = inside(grow(dpad, 0.2), x, y);
|
|
1033
|
+
const nearCluster = inside(grow(cluster, 0.12), x, y) || touchFacesAt(placement, x, y).length > 0;
|
|
1034
|
+
if (nearDpad && nearCluster) {
|
|
1035
|
+
// On a narrow phone the two margins meet: the nearer one, by its own size.
|
|
1036
|
+
const reach = (r) => Math.hypot(x - (r.x + r.width / 2), y - (r.y + r.height / 2)) / (r.width / 2);
|
|
1037
|
+
return reach(dpad) <= reach(cluster) ? 'dpad' : 'cluster';
|
|
1038
|
+
}
|
|
1039
|
+
if (nearDpad)
|
|
1040
|
+
return 'dpad';
|
|
1041
|
+
if (nearCluster)
|
|
1042
|
+
return 'cluster';
|
|
1043
|
+
return null;
|
|
1044
|
+
};
|
|
1045
|
+
return {
|
|
1046
|
+
gamepad,
|
|
1047
|
+
get placement() {
|
|
1048
|
+
return placement;
|
|
1049
|
+
},
|
|
1050
|
+
place(next) {
|
|
1051
|
+
placement = next;
|
|
1052
|
+
// A new geometry is a clean slate: nothing latched survives it.
|
|
1053
|
+
fingers.clear();
|
|
1054
|
+
latched.clear();
|
|
1055
|
+
since.clear();
|
|
1056
|
+
sync();
|
|
1057
|
+
},
|
|
1058
|
+
down(pointerId, x, y) {
|
|
1059
|
+
const control = controlAt(x, y);
|
|
1060
|
+
if (!control)
|
|
1061
|
+
return null;
|
|
1062
|
+
fingers.set(pointerId, { control, indices: indicesFor(control, x, y) });
|
|
1063
|
+
if (control === 'pause')
|
|
1064
|
+
for (const listener of [...pauseListeners])
|
|
1065
|
+
listener();
|
|
1066
|
+
sync();
|
|
1067
|
+
return control;
|
|
1068
|
+
},
|
|
1069
|
+
move(pointerId, x, y) {
|
|
1070
|
+
const finger = fingers.get(pointerId);
|
|
1071
|
+
if (!finger || finger.control === 'pause')
|
|
1072
|
+
return;
|
|
1073
|
+
finger.indices = indicesFor(finger.control, x, y);
|
|
1074
|
+
sync();
|
|
1075
|
+
},
|
|
1076
|
+
up(pointerId) {
|
|
1077
|
+
if (!fingers.delete(pointerId))
|
|
1078
|
+
return;
|
|
1079
|
+
sync();
|
|
1080
|
+
},
|
|
1081
|
+
releaseAll() {
|
|
1082
|
+
fingers.clear();
|
|
1083
|
+
latched.clear();
|
|
1084
|
+
since.clear();
|
|
1085
|
+
sync();
|
|
1086
|
+
},
|
|
1087
|
+
pressed() {
|
|
1088
|
+
const set = new Set();
|
|
1089
|
+
gamepad.buttons.forEach((button, index) => button.pressed && set.add(index));
|
|
1090
|
+
return set;
|
|
1091
|
+
},
|
|
1092
|
+
get deadline() {
|
|
1093
|
+
return latched.size ? Math.min(...latched.values()) : null;
|
|
1094
|
+
},
|
|
1095
|
+
tick: sync,
|
|
1096
|
+
onChange(listener) {
|
|
1097
|
+
changeListeners.add(listener);
|
|
1098
|
+
return () => changeListeners.delete(listener);
|
|
1099
|
+
},
|
|
1100
|
+
onPause(listener) {
|
|
1101
|
+
pauseListeners.add(listener);
|
|
1102
|
+
return () => pauseListeners.delete(listener);
|
|
1103
|
+
},
|
|
1104
|
+
};
|
|
1105
|
+
}
|
|
1106
|
+
/**
|
|
1107
|
+
* Puts the pad in `navigator.getGamepads()`, at the first index no physical pad
|
|
1108
|
+
* holds (index 0 when there is none — snes9x and mGBA read only that one), and
|
|
1109
|
+
* announces it with `gamepadconnected`. Install it **before** the engine starts, so
|
|
1110
|
+
* SDL's start-up enumeration finds it. If a physical pad later takes its index, the
|
|
1111
|
+
* pad moves to the next free one (disconnected, then connected again).
|
|
1112
|
+
*
|
|
1113
|
+
* The events are plain `Event`s carrying a `gamepad` property — a `GamepadEvent`
|
|
1114
|
+
* cannot be built around an object that is not a real `Gamepad` — which is the shape
|
|
1115
|
+
* Emscripten's handler and `createInput()` read. Returns `release()`, which restores
|
|
1116
|
+
* `getGamepads` and announces the pad gone.
|
|
1117
|
+
*/
|
|
1118
|
+
export function exposeAsGamepad(source, options = {}) {
|
|
1119
|
+
const pad = 'gamepad' in source ? source.gamepad : source;
|
|
1120
|
+
const nav = (options.navigator ?? globalThis.navigator);
|
|
1121
|
+
const target = options.target ?? globalThis;
|
|
1122
|
+
if (!nav)
|
|
1123
|
+
return () => { };
|
|
1124
|
+
const own = Object.getOwnPropertyDescriptor(nav, 'getGamepads');
|
|
1125
|
+
const original = nav.getGamepads ? nav.getGamepads.bind(nav) : () => [];
|
|
1126
|
+
const announce = (type) => {
|
|
1127
|
+
const event = new Event(type);
|
|
1128
|
+
Object.defineProperty(event, 'gamepad', { value: pad, enumerable: true });
|
|
1129
|
+
target.dispatchEvent(event);
|
|
1130
|
+
};
|
|
1131
|
+
const physical = () => Array.from(original() ?? [], (entry) => (entry === pad ? null : entry ?? null));
|
|
1132
|
+
const freeIndex = (pads) => {
|
|
1133
|
+
let index = 0;
|
|
1134
|
+
while (pads[index])
|
|
1135
|
+
index++;
|
|
1136
|
+
return index;
|
|
1137
|
+
};
|
|
1138
|
+
let moving = false;
|
|
1139
|
+
const wrapped = () => {
|
|
1140
|
+
const pads = physical();
|
|
1141
|
+
if (pads[pad.index] && !moving) {
|
|
1142
|
+
// A physical pad took our slot. Move, announcing outside the caller's poll.
|
|
1143
|
+
moving = true;
|
|
1144
|
+
queueMicrotask(() => {
|
|
1145
|
+
announce('gamepaddisconnected');
|
|
1146
|
+
pad.index = freeIndex(physical());
|
|
1147
|
+
moving = false;
|
|
1148
|
+
announce('gamepadconnected');
|
|
1149
|
+
});
|
|
1150
|
+
}
|
|
1151
|
+
const out = pads.slice();
|
|
1152
|
+
if (!moving) {
|
|
1153
|
+
while (out.length <= pad.index)
|
|
1154
|
+
out.push(null);
|
|
1155
|
+
out[pad.index] = pad;
|
|
1156
|
+
}
|
|
1157
|
+
return out;
|
|
1158
|
+
};
|
|
1159
|
+
pad.index = freeIndex(physical());
|
|
1160
|
+
pad.connected = true;
|
|
1161
|
+
Object.defineProperty(nav, 'getGamepads', { value: wrapped, configurable: true, writable: true });
|
|
1162
|
+
announce('gamepadconnected');
|
|
1163
|
+
let released = false;
|
|
1164
|
+
return () => {
|
|
1165
|
+
if (released)
|
|
1166
|
+
return;
|
|
1167
|
+
released = true;
|
|
1168
|
+
if (own)
|
|
1169
|
+
Object.defineProperty(nav, 'getGamepads', own);
|
|
1170
|
+
else
|
|
1171
|
+
delete nav.getGamepads;
|
|
1172
|
+
pad.connected = false;
|
|
1173
|
+
announce('gamepaddisconnected');
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
const TOUCH_STYLE_ID = 'wg-touch-pad-style';
|
|
1177
|
+
const TOUCH_CSS = `
|
|
1178
|
+
.wg-tp { position: fixed; inset: 0; z-index: 9000; pointer-events: none; display: none;
|
|
1179
|
+
-webkit-user-select: none; user-select: none; -webkit-touch-callout: none;
|
|
1180
|
+
font-family: var(--wg-font-ui, system-ui, sans-serif); color: #fff; }
|
|
1181
|
+
.wg-tp.is-visible { display: block; }
|
|
1182
|
+
.wg-tp-zone { position: absolute; pointer-events: auto; touch-action: none; overscroll-behavior: none;
|
|
1183
|
+
-webkit-tap-highlight-color: transparent; }
|
|
1184
|
+
.wg-tp-art { position: absolute; inset: 0; opacity: var(--wg-tp-opacity, 0.6); }
|
|
1185
|
+
.wg-tp.is-overlay .wg-tp-art { opacity: calc(var(--wg-tp-opacity, 0.6) * 0.75); }
|
|
1186
|
+
.wg-tp-face, .wg-tp-key, .wg-tp-arm, .wg-tp-hub { position: absolute; box-sizing: border-box;
|
|
1187
|
+
background: rgb(255 255 255 / 0.12); border: 1.5px solid rgb(255 255 255 / 0.55);
|
|
1188
|
+
display: grid; place-items: center; font-weight: 700; letter-spacing: 0.02em;
|
|
1189
|
+
text-shadow: 0 1px 2px rgb(0 0 0 / 0.6); }
|
|
1190
|
+
.wg-tp-face { border-radius: 50%; --c: #ffffff; border-color: color-mix(in srgb, var(--c) 70%, white);
|
|
1191
|
+
background: color-mix(in srgb, var(--c) 22%, transparent); }
|
|
1192
|
+
.wg-tp-key { border-radius: 999px; font-size: 13px; font-weight: 600; }
|
|
1193
|
+
.wg-tp-key.is-shoulder { border-radius: 14px; font-size: 16px; font-weight: 700; }
|
|
1194
|
+
.wg-tp-key.is-pause::before, .wg-tp-key.is-pause::after { content: ''; position: absolute; top: 34%; bottom: 34%;
|
|
1195
|
+
width: 4px; border-radius: 2px; background: currentColor; }
|
|
1196
|
+
.wg-tp-key.is-pause::before { left: calc(50% - 7px); }
|
|
1197
|
+
.wg-tp-key.is-pause::after { right: calc(50% - 7px); }
|
|
1198
|
+
.wg-tp-arm { border-radius: 6px; }
|
|
1199
|
+
.wg-tp-hub { border-radius: 4px; border-width: 0; background: rgb(255 255 255 / 0.12); }
|
|
1200
|
+
.wg-tp .is-on { background: rgb(255 255 255 / 0.55); transform: scale(0.96); color: #0b0d12; text-shadow: none; }
|
|
1201
|
+
.wg-tp-face.is-on { background: color-mix(in srgb, var(--c) 70%, white); }
|
|
1202
|
+
`;
|
|
1203
|
+
/**
|
|
1204
|
+
* The touch pad: draws {@link TOUCH_LAYOUTS | a console's pad} over `target`'s
|
|
1205
|
+
* viewport and turns fingers into a {@link VirtualGamepad}. Pair it with
|
|
1206
|
+
* {@link exposeAsGamepad} (the engines) and {@link connectTouchPad} (the shared
|
|
1207
|
+
* input). Pointer Events, any number of fingers; a finger keeps the control it
|
|
1208
|
+
* landed on — it slides around the d-pad, or across the buttons — and every finger
|
|
1209
|
+
* is let go on blur, on a hidden page, and when the pad hides: never a stuck button.
|
|
1210
|
+
*/
|
|
1211
|
+
export function createTouchPad(target, options) {
|
|
1212
|
+
const doc = target.ownerDocument;
|
|
1213
|
+
const win = doc.defaultView ?? globalThis;
|
|
1214
|
+
const resolve = (layout) => typeof layout === 'string' ? TOUCH_LAYOUTS[layout] : layout;
|
|
1215
|
+
let layout = resolve(options.layout);
|
|
1216
|
+
const haptics = options.haptics ?? true;
|
|
1217
|
+
const mode = options.mode ?? 'auto';
|
|
1218
|
+
const placeOptions = {
|
|
1219
|
+
...(options.scale !== undefined ? { scale: options.scale } : {}),
|
|
1220
|
+
...(options.minGameScale !== undefined ? { minGameScale: options.minGameScale } : {}),
|
|
1221
|
+
};
|
|
1222
|
+
const core = createTouchPadCore(options.minHold !== undefined ? { minHold: options.minHold } : {});
|
|
1223
|
+
if (!doc.getElementById(TOUCH_STYLE_ID)) {
|
|
1224
|
+
const style = doc.createElement('style');
|
|
1225
|
+
style.id = TOUCH_STYLE_ID;
|
|
1226
|
+
style.textContent = TOUCH_CSS;
|
|
1227
|
+
doc.head.appendChild(style);
|
|
1228
|
+
}
|
|
1229
|
+
const root = doc.createElement('div');
|
|
1230
|
+
root.className = 'wg-tp';
|
|
1231
|
+
root.style.setProperty('--wg-tp-opacity', String(clamp(options.opacity ?? 0.6, 0.2, 1)));
|
|
1232
|
+
const art = doc.createElement('div');
|
|
1233
|
+
art.className = 'wg-tp-art';
|
|
1234
|
+
// Reads `env(safe-area-inset-*)` back as pixels.
|
|
1235
|
+
const probe = doc.createElement('div');
|
|
1236
|
+
probe.style.cssText =
|
|
1237
|
+
'position:fixed;inset:0;visibility:hidden;pointer-events:none;' +
|
|
1238
|
+
'padding:env(safe-area-inset-top,0px) env(safe-area-inset-right,0px) env(safe-area-inset-bottom,0px) env(safe-area-inset-left,0px)';
|
|
1239
|
+
root.append(art, probe);
|
|
1240
|
+
target.appendChild(root);
|
|
1241
|
+
let shown = options.shown ?? false;
|
|
1242
|
+
let active = mode === 'always' || (win.matchMedia?.('(pointer: coarse)').matches ?? false);
|
|
1243
|
+
let destroyed = false;
|
|
1244
|
+
let zones = [];
|
|
1245
|
+
let arms = null;
|
|
1246
|
+
const parts = new Map();
|
|
1247
|
+
const layoutListeners = new Set();
|
|
1248
|
+
let timer = null;
|
|
1249
|
+
const visible = () => shown && active && !destroyed;
|
|
1250
|
+
const viewport = () => {
|
|
1251
|
+
const css = win.getComputedStyle(probe);
|
|
1252
|
+
const px = (value) => Number.parseFloat(value) || 0;
|
|
1253
|
+
return {
|
|
1254
|
+
width: win.innerWidth,
|
|
1255
|
+
height: win.innerHeight,
|
|
1256
|
+
safe: { top: px(css.paddingTop), right: px(css.paddingRight), bottom: px(css.paddingBottom), left: px(css.paddingLeft) },
|
|
1257
|
+
};
|
|
1258
|
+
};
|
|
1259
|
+
const gameArea = () => core.placement?.gameArea ?? { x: 0, y: 0, width: win.innerWidth, height: win.innerHeight };
|
|
1260
|
+
const box = (el, r) => {
|
|
1261
|
+
el.style.left = `${r.x}px`;
|
|
1262
|
+
el.style.top = `${r.y}px`;
|
|
1263
|
+
el.style.width = `${r.width}px`;
|
|
1264
|
+
el.style.height = `${r.height}px`;
|
|
1265
|
+
};
|
|
1266
|
+
const register = (index, el) => {
|
|
1267
|
+
parts.set(index, [...(parts.get(index) ?? []), el]);
|
|
1268
|
+
};
|
|
1269
|
+
const paint = () => {
|
|
1270
|
+
const on = core.pressed();
|
|
1271
|
+
for (const [index, els] of parts)
|
|
1272
|
+
for (const el of els)
|
|
1273
|
+
el.classList.toggle('is-on', on.has(index));
|
|
1274
|
+
if (arms) {
|
|
1275
|
+
arms.up.classList.toggle('is-on', on.has(PAD.up));
|
|
1276
|
+
arms.down.classList.toggle('is-on', on.has(PAD.down));
|
|
1277
|
+
arms.left.classList.toggle('is-on', on.has(PAD.left));
|
|
1278
|
+
arms.right.classList.toggle('is-on', on.has(PAD.right));
|
|
1279
|
+
}
|
|
1280
|
+
};
|
|
1281
|
+
const build = (placement) => {
|
|
1282
|
+
for (const zone of zones)
|
|
1283
|
+
zone.remove();
|
|
1284
|
+
art.replaceChildren();
|
|
1285
|
+
parts.clear();
|
|
1286
|
+
root.classList.toggle('is-overlay', placement.overlay);
|
|
1287
|
+
// The d-pad: a cross of four arms around a hub.
|
|
1288
|
+
const d = placement.dpad;
|
|
1289
|
+
const third = d.width / 3;
|
|
1290
|
+
const arm = (dir, x, y) => {
|
|
1291
|
+
const el = doc.createElement('div');
|
|
1292
|
+
el.className = 'wg-tp-arm';
|
|
1293
|
+
box(el, rect(d.x + x * third, d.y + y * third, third, third));
|
|
1294
|
+
art.appendChild(el);
|
|
1295
|
+
return el;
|
|
1296
|
+
};
|
|
1297
|
+
arms = { up: arm('up', 1, 0), left: arm('left', 0, 1), right: arm('right', 2, 1), down: arm('down', 1, 2) };
|
|
1298
|
+
const hub = doc.createElement('div');
|
|
1299
|
+
hub.className = 'wg-tp-hub';
|
|
1300
|
+
box(hub, rect(d.x + third, d.y + third, third, third));
|
|
1301
|
+
art.appendChild(hub);
|
|
1302
|
+
for (const face of placement.faces) {
|
|
1303
|
+
const el = doc.createElement('div');
|
|
1304
|
+
el.className = 'wg-tp-face';
|
|
1305
|
+
el.textContent = face.label;
|
|
1306
|
+
el.style.fontSize = `${Math.round(clamp(face.r * 0.7, 14, 28))}px`;
|
|
1307
|
+
if (face.color)
|
|
1308
|
+
el.style.setProperty('--c', face.color);
|
|
1309
|
+
box(el, rect(face.cx - face.r, face.cy - face.r, face.r * 2, face.r * 2));
|
|
1310
|
+
art.appendChild(el);
|
|
1311
|
+
register(face.index, el);
|
|
1312
|
+
}
|
|
1313
|
+
for (const key of placement.keys) {
|
|
1314
|
+
const el = doc.createElement('div');
|
|
1315
|
+
el.className = `wg-tp-key is-${key.id}${key.id === 'l' || key.id === 'r' ? ' is-shoulder' : ''}`;
|
|
1316
|
+
if (key.id === 'pause')
|
|
1317
|
+
el.setAttribute('aria-label', key.label);
|
|
1318
|
+
else
|
|
1319
|
+
el.textContent = key.label;
|
|
1320
|
+
box(el, key.rect);
|
|
1321
|
+
art.appendChild(el);
|
|
1322
|
+
if (key.index !== null)
|
|
1323
|
+
register(key.index, el);
|
|
1324
|
+
}
|
|
1325
|
+
zones = placement.zones.map((r) => {
|
|
1326
|
+
const zone = doc.createElement('div');
|
|
1327
|
+
zone.className = 'wg-tp-zone';
|
|
1328
|
+
box(zone, r);
|
|
1329
|
+
zone.addEventListener('pointerdown', onDown);
|
|
1330
|
+
// Cancelling the touch itself is what stops the browser's click after it.
|
|
1331
|
+
zone.addEventListener('touchstart', cancelTouch, { passive: false });
|
|
1332
|
+
zone.addEventListener('touchmove', cancelTouch, { passive: false });
|
|
1333
|
+
zone.addEventListener('touchend', cancelTouch, { passive: false });
|
|
1334
|
+
zone.addEventListener('pointermove', onMove);
|
|
1335
|
+
zone.addEventListener('pointerup', onUp);
|
|
1336
|
+
zone.addEventListener('pointercancel', onUp);
|
|
1337
|
+
zone.addEventListener('lostpointercapture', onUp);
|
|
1338
|
+
root.appendChild(zone);
|
|
1339
|
+
return zone;
|
|
1340
|
+
});
|
|
1341
|
+
};
|
|
1342
|
+
const relayout = () => {
|
|
1343
|
+
if (destroyed)
|
|
1344
|
+
return;
|
|
1345
|
+
root.classList.toggle('is-visible', visible());
|
|
1346
|
+
if (visible()) {
|
|
1347
|
+
const placement = placeTouchPad(layout, viewport(), placeOptions);
|
|
1348
|
+
core.place(placement);
|
|
1349
|
+
build(placement);
|
|
1350
|
+
}
|
|
1351
|
+
else {
|
|
1352
|
+
core.place(null);
|
|
1353
|
+
}
|
|
1354
|
+
paint();
|
|
1355
|
+
const area = gameArea();
|
|
1356
|
+
for (const listener of [...layoutListeners])
|
|
1357
|
+
listener(area, core.placement);
|
|
1358
|
+
};
|
|
1359
|
+
const schedule = () => {
|
|
1360
|
+
if (timer)
|
|
1361
|
+
clearTimeout(timer);
|
|
1362
|
+
timer = null;
|
|
1363
|
+
const due = core.deadline;
|
|
1364
|
+
if (due === null)
|
|
1365
|
+
return;
|
|
1366
|
+
timer = setTimeout(() => {
|
|
1367
|
+
timer = null;
|
|
1368
|
+
core.tick();
|
|
1369
|
+
paint();
|
|
1370
|
+
schedule();
|
|
1371
|
+
}, Math.max(0, due - (win.performance?.now() ?? Date.now())));
|
|
1372
|
+
};
|
|
1373
|
+
/**
|
|
1374
|
+
* Where and when the pad last handled a finger. A touch that opens a menu (the pause
|
|
1375
|
+
* button) hides the pad, and the click the browser sends after the lift would land on
|
|
1376
|
+
* whatever the menu put under the finger — and pick it. Clicks right there, right
|
|
1377
|
+
* then, are the pad's and are dropped.
|
|
1378
|
+
*/
|
|
1379
|
+
let lastTouch = { at: -Infinity, x: 0, y: 0 };
|
|
1380
|
+
const now = () => win.performance?.now() ?? Date.now();
|
|
1381
|
+
const remember = (event) => {
|
|
1382
|
+
lastTouch = { at: now(), x: event.clientX, y: event.clientY };
|
|
1383
|
+
};
|
|
1384
|
+
const cancelTouch = (event) => {
|
|
1385
|
+
if (event.cancelable)
|
|
1386
|
+
event.preventDefault();
|
|
1387
|
+
};
|
|
1388
|
+
const dropGhostClick = (event) => {
|
|
1389
|
+
if (now() - lastTouch.at > 400)
|
|
1390
|
+
return;
|
|
1391
|
+
if (Math.hypot(event.clientX - lastTouch.x, event.clientY - lastTouch.y) > TOUCH_MIN)
|
|
1392
|
+
return;
|
|
1393
|
+
event.preventDefault();
|
|
1394
|
+
event.stopImmediatePropagation();
|
|
1395
|
+
};
|
|
1396
|
+
function onDown(event) {
|
|
1397
|
+
event.preventDefault();
|
|
1398
|
+
remember(event);
|
|
1399
|
+
const zone = event.currentTarget;
|
|
1400
|
+
if (core.down(event.pointerId, event.clientX, event.clientY) === null)
|
|
1401
|
+
return;
|
|
1402
|
+
try {
|
|
1403
|
+
zone.setPointerCapture(event.pointerId);
|
|
1404
|
+
}
|
|
1405
|
+
catch {
|
|
1406
|
+
/* a synthetic pointer cannot be captured; it still works, minus sliding off the zone */
|
|
1407
|
+
}
|
|
1408
|
+
paint();
|
|
1409
|
+
schedule();
|
|
1410
|
+
}
|
|
1411
|
+
function onMove(event) {
|
|
1412
|
+
core.move(event.pointerId, event.clientX, event.clientY);
|
|
1413
|
+
paint();
|
|
1414
|
+
}
|
|
1415
|
+
function onUp(event) {
|
|
1416
|
+
remember(event);
|
|
1417
|
+
core.up(event.pointerId);
|
|
1418
|
+
paint();
|
|
1419
|
+
schedule();
|
|
1420
|
+
}
|
|
1421
|
+
const releaseAll = () => {
|
|
1422
|
+
core.releaseAll();
|
|
1423
|
+
paint();
|
|
1424
|
+
};
|
|
1425
|
+
const onVisibility = () => {
|
|
1426
|
+
if (doc.visibilityState === 'hidden')
|
|
1427
|
+
releaseAll();
|
|
1428
|
+
};
|
|
1429
|
+
const onAnyPointer = (event) => {
|
|
1430
|
+
if (mode === 'auto' && event.pointerType === 'touch' && !active) {
|
|
1431
|
+
active = true;
|
|
1432
|
+
relayout();
|
|
1433
|
+
}
|
|
1434
|
+
};
|
|
1435
|
+
const onAnyKey = (event) => {
|
|
1436
|
+
// Only a real keyboard hides the pad: an SDK that drives its engine with synthetic key
|
|
1437
|
+
// events (jgenesis reads the keyboard only) must not hide the pad it is listening to.
|
|
1438
|
+
if (event?.type === 'keydown' && !event.isTrusted)
|
|
1439
|
+
return;
|
|
1440
|
+
if (mode === 'auto' && active) {
|
|
1441
|
+
active = false;
|
|
1442
|
+
relayout();
|
|
1443
|
+
}
|
|
1444
|
+
};
|
|
1445
|
+
const onPadConnected = (event) => {
|
|
1446
|
+
if (event.gamepad !== core.gamepad)
|
|
1447
|
+
onAnyKey();
|
|
1448
|
+
};
|
|
1449
|
+
let frame = 0;
|
|
1450
|
+
const onResize = () => {
|
|
1451
|
+
if (frame)
|
|
1452
|
+
return;
|
|
1453
|
+
frame = win.requestAnimationFrame(() => {
|
|
1454
|
+
frame = 0;
|
|
1455
|
+
if (visible())
|
|
1456
|
+
relayout();
|
|
1457
|
+
});
|
|
1458
|
+
};
|
|
1459
|
+
const preventMenu = (event) => event.preventDefault();
|
|
1460
|
+
core.onChange((wentDown) => {
|
|
1461
|
+
if (haptics && wentDown.length)
|
|
1462
|
+
win.navigator.vibrate?.(8);
|
|
1463
|
+
});
|
|
1464
|
+
win.addEventListener('blur', releaseAll);
|
|
1465
|
+
win.addEventListener('click', dropGhostClick, { capture: true });
|
|
1466
|
+
doc.addEventListener('visibilitychange', onVisibility);
|
|
1467
|
+
win.addEventListener('pointerdown', onAnyPointer, { capture: true, passive: true });
|
|
1468
|
+
win.addEventListener('keydown', onAnyKey, { capture: true, passive: true });
|
|
1469
|
+
win.addEventListener('gamepadconnected', onPadConnected);
|
|
1470
|
+
win.addEventListener('resize', onResize);
|
|
1471
|
+
win.addEventListener('orientationchange', onResize);
|
|
1472
|
+
root.addEventListener('contextmenu', preventMenu);
|
|
1473
|
+
relayout();
|
|
1474
|
+
return {
|
|
1475
|
+
gamepad: core.gamepad,
|
|
1476
|
+
get layout() {
|
|
1477
|
+
return layout;
|
|
1478
|
+
},
|
|
1479
|
+
setLayout(next) {
|
|
1480
|
+
layout = resolve(next);
|
|
1481
|
+
relayout();
|
|
1482
|
+
},
|
|
1483
|
+
show() {
|
|
1484
|
+
if (shown)
|
|
1485
|
+
return;
|
|
1486
|
+
shown = true;
|
|
1487
|
+
relayout();
|
|
1488
|
+
},
|
|
1489
|
+
hide() {
|
|
1490
|
+
if (!shown)
|
|
1491
|
+
return;
|
|
1492
|
+
shown = false;
|
|
1493
|
+
relayout();
|
|
1494
|
+
},
|
|
1495
|
+
get visible() {
|
|
1496
|
+
return visible();
|
|
1497
|
+
},
|
|
1498
|
+
get placement() {
|
|
1499
|
+
return core.placement;
|
|
1500
|
+
},
|
|
1501
|
+
get gameArea() {
|
|
1502
|
+
return gameArea();
|
|
1503
|
+
},
|
|
1504
|
+
onLayout(listener) {
|
|
1505
|
+
layoutListeners.add(listener);
|
|
1506
|
+
return () => layoutListeners.delete(listener);
|
|
1507
|
+
},
|
|
1508
|
+
onPause: (listener) => core.onPause(listener),
|
|
1509
|
+
destroy() {
|
|
1510
|
+
if (destroyed)
|
|
1511
|
+
return;
|
|
1512
|
+
destroyed = true;
|
|
1513
|
+
core.place(null);
|
|
1514
|
+
if (timer)
|
|
1515
|
+
clearTimeout(timer);
|
|
1516
|
+
if (frame)
|
|
1517
|
+
win.cancelAnimationFrame(frame);
|
|
1518
|
+
win.removeEventListener('blur', releaseAll);
|
|
1519
|
+
win.removeEventListener('click', dropGhostClick, { capture: true });
|
|
1520
|
+
doc.removeEventListener('visibilitychange', onVisibility);
|
|
1521
|
+
win.removeEventListener('pointerdown', onAnyPointer, { capture: true });
|
|
1522
|
+
win.removeEventListener('keydown', onAnyKey, { capture: true });
|
|
1523
|
+
win.removeEventListener('gamepadconnected', onPadConnected);
|
|
1524
|
+
win.removeEventListener('resize', onResize);
|
|
1525
|
+
win.removeEventListener('orientationchange', onResize);
|
|
1526
|
+
layoutListeners.clear();
|
|
1527
|
+
root.remove();
|
|
1528
|
+
},
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
/**
|
|
1532
|
+
* The host's one-liner: the pad shows while the game has the controls (the shared
|
|
1533
|
+
* input is suspended) and hides while a menu is open, and its pause button opens
|
|
1534
|
+
* the menu. Returns the function that undoes it.
|
|
1535
|
+
*/
|
|
1536
|
+
export function connectTouchPad(pad, input) {
|
|
1537
|
+
const follow = (suspended) => (suspended ? pad.show() : pad.hide());
|
|
1538
|
+
follow(input.suspended);
|
|
1539
|
+
const offSuspend = input.onSuspend(follow);
|
|
1540
|
+
const offPause = pad.onPause(() => input.trigger('menu', { source: 'touch', repeat: false }));
|
|
1541
|
+
return () => {
|
|
1542
|
+
offSuspend();
|
|
1543
|
+
offPause();
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
//# sourceMappingURL=engine-specs.js.map
|