-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVirtualTouchscreenZone.cs
More file actions
512 lines (420 loc) · 23.7 KB
/
VirtualTouchscreenZone.cs
File metadata and controls
512 lines (420 loc) · 23.7 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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
// VirtualTouchscreenZone.cs
// MIT-style utility: mirror *real* Touchscreen samples into a per-zone "virtual" Touchscreen.
// Primary use: single-device local multiplayer on one phone/tablet by spawning one Player per UI zone.
//
// What it gives you
// • A concrete InputSystem layout ("VirtualTouchscreen") that behaves like Touchscreen.
// • A MonoBehaviour you drop on a RectTransform; it hit-tests pointer begins to *claim* a finger.
// • It mirrors only the real Touchscreen into this zone’s VirtualTouchscreen (VTS) with same timestamps.
// • Optional auto-join: calls PlayerInputManager.JoinPlayer on first Began inside the zone.
// • Throttling, move-epsilon, and detailed logging so you don’t blow the per-frame event queue.
//
// Requirements
// • Project setting “Active Input Handling” = Input System (New).
// • Place this on a RectTransform under a Canvas (Overlay or Camera Space).
// • Do NOT enable Mouse→Touch simulation or EnhancedTouch while mirroring, or you’ll double-feed.
//
// Notes
// • Many simulators only update primaryTouch. Use `forceUsePrimaryTouch = true` if touches[] are unreliable.
// • This component ignores its own VTS events to prevent bounce.
// • Each zone owns exactly one VTS device. Pair that device to a Player to isolate inputs per zone.
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.InputSystem.Layouts;
using UnityEngine.InputSystem.LowLevel;
using UnityEngine.InputSystem.Users;
using SysTouchPhase = UnityEngine.InputSystem.TouchPhase;
/// <summary>
/// Concrete layout identical to <see cref="Touchscreen"/> so control schemes can target it.
/// The layout name is "VirtualTouchscreen".
/// </summary>
[InputControlLayout(stateType = typeof(TouchState), displayName = "VirtualTouchscreen")]
public class VirtualTouchscreen : Touchscreen {}
/// <summary>
/// Drop this on a RectTransform to create a per-zone virtual Touchscreen (VTS) and mirror real Touchscreen samples
/// into it when a finger begins inside the zone. Designed for one-device local multiplayer with PlayerInputManager.
/// </summary>
[DisallowMultipleComponent]
[RequireComponent(typeof(RectTransform))]
public class VirtualTouchscreenZone : MonoBehaviour
{
// ────────────────────────────────────────────────────────────────────────────
// Layout bootstrap
// Registers the "VirtualTouchscreen" layout before scene load so PlayerInput control schemes can reference it.
// ────────────────────────────────────────────────────────────────────────────
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void RegisterLayout()
{
const string layoutName = "VirtualTouchscreen";
if (!InputSystem.ListLayouts().Contains(layoutName))
InputSystem.RegisterLayout<VirtualTouchscreen>(layoutName);
}
// ────────────────────────────────────────────────────────────────────────────
// Inspector configuration
// ────────────────────────────────────────────────────────────────────────────
[Header("Enable/Toggles")]
[Tooltip("Master toggle for this component. When false, nothing is created or mirrored.")]
[SerializeField] private bool behaviorEnabled = true;
[Tooltip("When false, the device exists but no mirroring occurs.")]
[SerializeField] private bool mirroringEnabled = true;
[Header("Simulator quirks")]
[Tooltip("Prefer primaryTouch over touches[]. Some simulators only update primaryTouch.")]
[SerializeField] private bool forceUsePrimaryTouch = true; // do NOT mix with touches[]
[Header("Throttle")]
[Tooltip("Hard cap on samples queued by THIS zone per frame. Prevents queue overflow.")]
[SerializeField] private int maxQueuedPerFrame = 64;
[Tooltip("Minimum pixel delta to emit a Moved sample. 0 disables filtering.")]
[SerializeField] private float moveEpsilonPixels = 1f;
[Header("Zone (UI hit-test)")]
[Tooltip("RectTransform that defines the touchable region for this zone. Defaults to this component's RectTransform.")]
[SerializeField] private RectTransform zoneRect;
private Camera _uiCamera; // set from Canvas (null for ScreenSpaceOverlay)
[Header("Virtual device")]
[Tooltip("Layout name for the virtual device. Default is \"VirtualTouchscreen\".")]
[SerializeField] private string vtsLayoutName = "VirtualTouchscreen";
[Tooltip("Optional device name override. If empty, an auto name is used.")]
[SerializeField] private string deviceName = "";
[Tooltip("Remove and destroy the VTS device when this component is disabled.")]
[SerializeField] private bool removeDeviceOnDisable = true;
[Header("Manual join (PlayerInputManager)")]
[Tooltip("On first Began inside this zone, call PlayerInputManager.JoinPlayer paired to this VTS.")]
[SerializeField] private bool autoJoinOnPress = true;
[Tooltip("Optional control scheme to force during JoinPlayer. Leave empty for automatic.")]
[SerializeField] private string joinControlScheme = "";
[Tooltip("Only attempt join if this VTS is not already paired to a user.")]
[SerializeField] private bool joinOnlyIfUnpaired = true;
[Tooltip("Only attempt join once during this component's lifetime.")]
[SerializeField] private bool joinOncePerZone = true;
[Header("Logging (set either Instance or Global)")]
[Tooltip("Enable logging for this instance. You can also flip GlobalLoggingEnabled at runtime.")]
[SerializeField] private bool instanceLoggingEnabled = true;
/// <summary>Set true at runtime to force logging from all zones regardless of instance toggle.</summary>
public static bool GlobalLoggingEnabled = false;
[SerializeField] private bool logLifecycleEvents = true;
[SerializeField] private bool logInputEvents = true;
[SerializeField] private bool logClaimsAndReleases = true;
[SerializeField] private bool logQueuedSamples = true;
[SerializeField] private bool logSkippedTouches = true;
[SerializeField] private bool logWarnings = true;
[SerializeField] private bool logThrottle = true;
/// <summary>Access the virtual device owned by this zone. Null until <see cref="EnsureDevice"/> runs.</summary>
public VirtualTouchscreen Device => _vtsDevice;
// ────────────────────────────────────────────────────────────────────────────
// Internal state
// ────────────────────────────────────────────────────────────────────────────
private VirtualTouchscreen _vtsDevice;
private RectTransform _zoneRectCached;
// Mapping real finger id -> virtual touch id, and claim set for routing.
private readonly Dictionary<int, int> _realToVirtualTouchId = new(); // realPid -> vtsTid
private readonly HashSet<int> _claimedRealTouchIds = new();
// Per-finger last known values for epsilon filtering and bookkeeping.
private readonly Dictionary<int, Vector2> _lastPosByPid = new();
private readonly Dictionary<int, SysTouchPhase> _lastPhaseByPid = new();
private int _nextVirtualTouchId = 1;
private int _primaryRealPid = -1;
private int _queuedThisFrame;
private float _moveEpsSqr;
// Keep a stable delegate so we can unsubscribe cleanly.
private System.Action _beforeUpdateHandler;
private PlayerInput _joinedPlayer;
// ────────────────────────────────────────────────────────────────────────────
// Unity lifecycle
// ────────────────────────────────────────────────────────────────────────────
private void Reset()
{
// Auto-wire the zone RectTransform for convenience.
if (!zoneRect) zoneRect = GetComponent<RectTransform>();
}
private void Awake()
{
if (!behaviorEnabled) return;
_zoneRectCached = zoneRect ? zoneRect : GetComponent<RectTransform>();
_moveEpsSqr = Mathf.Max(0f, moveEpsilonPixels) * Mathf.Max(0f, moveEpsilonPixels);
EnsureDevice();
LogIf(logLifecycleEvents, $"Awake → device ensured; maxQueuedEventsPerUpdate={InputSystem.settings.maxQueuedEventsPerUpdate}");
}
private void OnEnable()
{
if (!behaviorEnabled) return;
// Determine which camera to use for ScreenPointToLocalPointInRectangle.
var canvas = _zoneRectCached.GetComponentInParent<Canvas>();
_uiCamera = canvas && canvas.renderMode != RenderMode.ScreenSpaceOverlay ? Camera.main : null;
EnsureDevice();
if (_beforeUpdateHandler == null) _beforeUpdateHandler = OnBeforeUpdate;
InputSystem.onBeforeUpdate += _beforeUpdateHandler; // resets per-frame counters
InputSystem.onEvent += OnEvent; // mirrors source events
LogIf(logLifecycleEvents, "OnEnable → subscribed onBeforeUpdate + onEvent");
}
private void OnDisable()
{
if (!behaviorEnabled) return;
InputSystem.onEvent -= OnEvent;
if (_beforeUpdateHandler != null) InputSystem.onBeforeUpdate -= _beforeUpdateHandler;
CancelAll(); // emit Canceled for any active virtual touches, then reset device
if (removeDeviceOnDisable && _vtsDevice != null && _vtsDevice.added)
{
LogIf(logLifecycleEvents, $"OnDisable → removing device {_vtsDevice}");
InputSystem.RemoveDevice(_vtsDevice);
_vtsDevice = null;
}
LogIf(logLifecycleEvents, "OnDisable → unsubscribed, canceled, cleaned");
}
private void OnDestroy()
{
if (!behaviorEnabled) return;
InputSystem.onEvent -= OnEvent;
if (_beforeUpdateHandler != null) InputSystem.onBeforeUpdate -= _beforeUpdateHandler;
}
/// <summary>
/// Per-update reset of per-frame counters. Keeps throttling deterministic.
/// </summary>
private void OnBeforeUpdate()
{
if (_queuedThisFrame > 0)
LogIf(logThrottle, $"Frame end: queued={_queuedThisFrame} (cap={maxQueuedPerFrame})");
_queuedThisFrame = 0;
}
// ────────────────────────────────────────────────────────────────────────────
// Device creation and reuse
// ────────────────────────────────────────────────────────────────────────────
/// <summary>
/// Ensures this zone has a VirtualTouchscreen device. Reuses an existing device by name if present.
/// </summary>
private void EnsureDevice()
{
if (_vtsDevice != null && _vtsDevice.added) return;
if (!InputSystem.ListLayouts().Contains(vtsLayoutName))
InputSystem.RegisterLayout<VirtualTouchscreen>(vtsLayoutName);
string resolvedName = string.IsNullOrEmpty(deviceName) ? $"{vtsLayoutName}-{GetInstanceID()}" : deviceName;
// Find existing VTS with same name to avoid duplicates across domain reloads.
_vtsDevice = InputSystem.devices
.FirstOrDefault(d => d is VirtualTouchscreen && d.name == resolvedName) as VirtualTouchscreen;
if (_vtsDevice == null)
_vtsDevice = (VirtualTouchscreen)InputSystem.AddDevice(vtsLayoutName, resolvedName);
else if (!_vtsDevice.added)
InputSystem.AddDevice(_vtsDevice);
LogIf(logLifecycleEvents, $"EnsureDevice → Using VTS: {_vtsDevice}");
}
// ────────────────────────────────────────────────────────────────────────────
// Mirroring core
// ────────────────────────────────────────────────────────────────────────────
/// <summary>
/// InputSystem global event hook. Mirrors *only* the real Touchscreen into this zone’s VTS.
/// Ignores events from the VTS itself to prevent feedback.
/// </summary>
private void OnEvent(InputEventPtr evt, InputDevice src)
{
if (!behaviorEnabled || !mirroringEnabled) return;
if (_vtsDevice == null || _zoneRectCached == null) { LogIf(logWarnings, "OnEvent: VTS/zone null"); return; }
// Handle only the *real* Touchscreen. Ignore this zone's own VTS and any non-touch device.
if (src is not Touchscreen real || ReferenceEquals(src, _vtsDevice)) return;
bool isState = evt.IsA<StateEvent>();
bool isDelta = evt.IsA<DeltaStateEvent>();
if (!isState && !isDelta) return;
LogIf(logInputEvents, $"OnEvent [{(isState ? "State" : "Delta")} @ {evt.time:F6}] dev={src.name} layout={src.layout}");
int handled = 0;
// Path 1: touches[] changes when available and enabled.
if (!forceUsePrimaryTouch)
{
foreach (var control in evt.EnumerateChangedControls(src))
{
if (control is not TouchControl t) continue;
handled += HandleTouchFromEvent(t, evt);
if (_queuedThisFrame >= maxQueuedPerFrame)
{
LogIf(logThrottle, $"Cap hit in touches[] path. queued={_queuedThisFrame}/{maxQueuedPerFrame}");
break;
}
}
}
// Path 2: primaryTouch fallback or explicit preference.
if (forceUsePrimaryTouch || handled == 0)
{
var pt = real.primaryTouch;
var ph = pt.phase.ReadValueFromEvent(evt);
var pos = pt.position.ReadValueFromEvent(evt);
var pid = pt.touchId.ReadValueFromEvent(evt);
// Fallback to committed state when payload omits fields.
if (ph == SysTouchPhase.None) ph = pt.phase.ReadValue();
if (pos == default) pos = pt.position.ReadValue();
if (pid == 0) pid = pt.touchId.ReadValue();
if (ph != SysTouchPhase.None)
{
LogIf(logInputEvents, $" primaryTouch pid={pid} phase={ph} pos={pos}");
HandleTouchRecord(pid, ph, pos, evt.time, "primary");
handled++;
}
else
{
LogIf(logSkippedTouches, " primaryTouch has no phase in payload/committed state");
}
}
if (handled == 0)
LogIf(logSkippedTouches, " no touch data handled this event");
}
/// <summary>
/// Mirrors a single <see cref="TouchControl"/> sample from the event payload.
/// </summary>
private int HandleTouchFromEvent(TouchControl touch, InputEventPtr evt)
{
var ph = touch.phase.ReadValueFromEvent(evt);
var pos = touch.position.ReadValueFromEvent(evt);
int pid = touch.touchId.ReadValueFromEvent(evt);
if (ph == SysTouchPhase.None) ph = touch.phase.ReadValue();
if (pos == default) pos = touch.position.ReadValue();
if (pid == 0) pid = touch.touchId.ReadValue();
string origin = touch.path; // e.g. "/Touchscreen/touch0"
LogIf(logInputEvents, $" changed {origin} pid={pid} phase={ph} pos={pos}");
HandleTouchRecord(pid, ph, pos, evt.time, origin);
return 1;
}
/// <summary>
/// Core routing and queueing. Claims fingers on Began inside the zone. Applies move epsilon and frame cap.
/// Writes a <see cref="TouchState"/> to the zone's VTS with the event timestamp.
/// </summary>
private void HandleTouchRecord(int realPid, SysTouchPhase phase, Vector2 pos, double time, string originTag)
{
// Per-frame cap to avoid "maxQueuedEventsPerUpdate" overflow.
if (_queuedThisFrame >= maxQueuedPerFrame)
{
LogIf(logThrottle, $"SKIP [{originTag}] cap reached. pid={realPid} phase={phase} pos={pos}");
return;
}
// Primary id tracking for isPrimaryTouch flag.
if (phase == SysTouchPhase.Began && _primaryRealPid == -1) _primaryRealPid = realPid;
if ((phase == SysTouchPhase.Ended || phase == SysTouchPhase.Canceled) && _primaryRealPid == realPid) _primaryRealPid = -1;
// Only begin inside this zone.
if (phase == SysTouchPhase.Began && !ScreenPointInZone(pos))
{
LogIf(logSkippedTouches, $"SKIP [{originTag}] Began outside zone. pid={realPid} pos={pos}");
return;
}
// Non-begins must be previously claimed by this zone.
if (phase != SysTouchPhase.Began && !_claimedRealTouchIds.Contains(realPid))
{
LogIf(logSkippedTouches, $"SKIP [{originTag}] Unclaimed pid on {phase}. pid={realPid}");
return;
}
// Epsilon filter for Moved.
if (phase == SysTouchPhase.Moved && _lastPosByPid.TryGetValue(realPid, out var lastPos))
{
if (_moveEpsSqr > 0f && (pos - lastPos).sqrMagnitude < _moveEpsSqr)
{
LogIf(logSkippedTouches, $"SKIP [{originTag}] Move < epsilon. pid={realPid} Δ={(pos-lastPos)}");
_lastPhaseByPid[realPid] = SysTouchPhase.Moved;
return;
}
}
// Claim mapping and optional Player join on the first sample for this finger.
_claimedRealTouchIds.Add(realPid);
if (!_realToVirtualTouchId.ContainsKey(realPid))
{
TryManualJoinIfNeeded();
_realToVirtualTouchId[realPid] = _nextVirtualTouchId++;
LogIf(logClaimsAndReleases, $"Claim [{originTag}] realPid={realPid} → vtsTid={_realToVirtualTouchId[realPid]}");
}
_lastPosByPid[realPid] = pos;
_lastPhaseByPid[realPid] = phase;
var vtsSample = new TouchState
{
touchId = _realToVirtualTouchId[realPid],
phase = phase,
position = pos,
pressure = (phase == SysTouchPhase.Ended || phase == SysTouchPhase.Canceled) ? 0f : 1f,
displayIndex = 0,
isIndirectTouch = false,
isPrimaryTouch = (realPid == _primaryRealPid)
};
// Queue with the source event's timestamp to preserve order within the frame.
InputSystem.QueueStateEvent(_vtsDevice, vtsSample, time);
_queuedThisFrame++;
LogIf(logQueuedSamples, $" → QUEUE [{originTag}] tid={vtsSample.touchId} {phase} pos={pos} t={time:F6} queuedThisFrame={_queuedThisFrame}");
// Release bookkeeping on End/Cancel.
if (phase == SysTouchPhase.Ended || phase == SysTouchPhase.Canceled)
{
_claimedRealTouchIds.Remove(realPid);
_lastPosByPid.Remove(realPid);
_lastPhaseByPid.Remove(realPid);
LogIf(logClaimsAndReleases, $"Release [{originTag}] realPid={realPid} tid={vtsSample.touchId}");
}
}
// ────────────────────────────────────────────────────────────────────────────
// Player join
// ────────────────────────────────────────────────────────────────────────────
/// <summary>
/// Optionally call <see cref="PlayerInputManager.JoinPlayer"/> and pair it with this zone's VTS.
/// Respects <see cref="joinOnlyIfUnpaired"/> and <see cref="joinOncePerZone"/>.
/// </summary>
private void TryManualJoinIfNeeded()
{
if (!autoJoinOnPress) return;
if (joinOnlyIfUnpaired)
{
var user = InputUser.FindUserPairedToDevice(_vtsDevice);
if (user.HasValue)
{
LogIf(logClaimsAndReleases, "Join skipped: VTS already paired");
return;
}
}
if (joinOncePerZone && _joinedPlayer != null)
{
LogIf(logClaimsAndReleases, "Join skipped: already joined once");
return;
}
var pim = PlayerInputManager.instance;
if (pim == null)
{
LogIf(logWarnings, "Join requested but no PlayerInputManager.instance");
return;
}
string scheme = string.IsNullOrEmpty(joinControlScheme) ? null : joinControlScheme;
try
{
var player = pim.JoinPlayer(-1, -1, scheme, _vtsDevice);
_joinedPlayer = player;
LogIf(logLifecycleEvents, $"Manual join → Player {player.playerIndex} device='{_vtsDevice.name}' scheme={(scheme ?? "<auto>")}");
}
catch (System.SystemException e)
{
LogIf(logWarnings, $"JoinPlayer failed: {e.Message}");
}
}
// ────────────────────────────────────────────────────────────────────────────
// Utilities
// ────────────────────────────────────────────────────────────────────────────
/// <summary>
/// Rect hit-test in screen space. Began must be inside the zone. Movement is routed to the claiming zone.
/// </summary>
private bool ScreenPointInZone(Vector2 screenPoint)
{
RectTransformUtility.ScreenPointToLocalPointInRectangle(_zoneRectCached, screenPoint, _uiCamera, out var local);
return _zoneRectCached.rect.Contains(local);
}
/// <summary>
/// Emit Canceled for all active virtual touches and reset the device to a clean state.
/// </summary>
private void CancelAll()
{
if (_vtsDevice == null) return;
foreach (var pair in _realToVirtualTouchId)
InputSystem.QueueStateEvent(_vtsDevice, new TouchState { touchId = pair.Value, phase = SysTouchPhase.Canceled });
_realToVirtualTouchId.Clear();
_claimedRealTouchIds.Clear();
_lastPosByPid.Clear();
_lastPhaseByPid.Clear();
InputSystem.ResetDevice(_vtsDevice);
LogIf(logLifecycleEvents, "CancelAll → emitted Canceled and reset device");
}
/// <summary>
/// Conditional logger honoring instance and global toggles.
/// </summary>
private void LogIf(bool categoryEnabled, string message)
{
if (!(categoryEnabled && (instanceLoggingEnabled || GlobalLoggingEnabled))) return;
Debug.Log($"[VTSZone#{GetInstanceID()}] {message}", this);
}
}