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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
|
/*
* Copyright (C) 2014-2018 Team Kodi
* This file is part of Kodi - https://kodi.tv
*
* SPDX-License-Identifier: GPL-2.0-or-later
* See LICENSES/README.md for more information.
*/
#include "ButtonMapping.h"
#include "ServiceBroker.h"
#include "games/controllers/Controller.h"
#include "games/controllers/ControllerManager.h"
#include "games/controllers/input/PhysicalFeature.h"
#include "input/IKeymap.h"
#include "input/InputTranslator.h"
#include "input/Key.h"
#include "input/joysticks/DriverPrimitive.h"
#include "input/joysticks/JoystickTranslator.h"
#include "input/joysticks/JoystickUtils.h"
#include "input/joysticks/interfaces/IButtonMap.h"
#include "input/joysticks/interfaces/IButtonMapper.h"
#include "utils/log.h"
#include <algorithm>
#include <assert.h>
#include <cmath>
using namespace KODI;
using namespace JOYSTICK;
#define MAPPING_COOLDOWN_MS 50 // Guard against repeated input
#define AXIS_THRESHOLD 0.75f // Axis must exceed this value to be mapped
#define TRIGGER_DELAY_MS \
200 // Delay trigger detection to handle anomalous triggers with non-zero center
// --- CPrimitiveDetector ------------------------------------------------------
CPrimitiveDetector::CPrimitiveDetector(CButtonMapping* buttonMapping)
: m_buttonMapping(buttonMapping)
{
}
bool CPrimitiveDetector::MapPrimitive(const CDriverPrimitive& primitive)
{
if (primitive.IsValid())
return m_buttonMapping->MapPrimitive(primitive);
return false;
}
// --- CButtonDetector ---------------------------------------------------------
CButtonDetector::CButtonDetector(CButtonMapping* buttonMapping, unsigned int buttonIndex)
: CPrimitiveDetector(buttonMapping), m_buttonIndex(buttonIndex)
{
}
bool CButtonDetector::OnMotion(bool bPressed)
{
if (bPressed)
return MapPrimitive(CDriverPrimitive(PRIMITIVE_TYPE::BUTTON, m_buttonIndex));
return false;
}
// --- CHatDetector ------------------------------------------------------------
CHatDetector::CHatDetector(CButtonMapping* buttonMapping, unsigned int hatIndex)
: CPrimitiveDetector(buttonMapping), m_hatIndex(hatIndex)
{
}
bool CHatDetector::OnMotion(HAT_STATE state)
{
return MapPrimitive(CDriverPrimitive(m_hatIndex, static_cast<HAT_DIRECTION>(state)));
}
// --- CAxisDetector -----------------------------------------------------------
CAxisDetector::CAxisDetector(CButtonMapping* buttonMapping,
unsigned int axisIndex,
const AxisConfiguration& config)
: CPrimitiveDetector(buttonMapping),
m_axisIndex(axisIndex),
m_config(config),
m_state(AXIS_STATE::INACTIVE),
m_type(AXIS_TYPE::UNKNOWN),
m_initialPositionKnown(false),
m_initialPosition(0.0f),
m_initialPositionChanged(false)
{
}
bool CAxisDetector::OnMotion(float position)
{
DetectType(position);
if (m_type != AXIS_TYPE::UNKNOWN)
{
// Update position if this axis is an anomalous trigger
if (m_type == AXIS_TYPE::OFFSET)
position = (position - m_config.center) / m_config.range;
// Reset state if position crosses zero
if (m_state == AXIS_STATE::MAPPED)
{
SEMIAXIS_DIRECTION activatedDir = m_activatedPrimitive.SemiAxisDirection();
SEMIAXIS_DIRECTION newDir = CJoystickTranslator::PositionToSemiAxisDirection(position);
if (activatedDir != newDir)
m_state = AXIS_STATE::INACTIVE;
}
// Check if axis has become activated
if (m_state == AXIS_STATE::INACTIVE)
{
if (std::abs(position) >= AXIS_THRESHOLD)
m_state = AXIS_STATE::ACTIVATED;
if (m_state == AXIS_STATE::ACTIVATED)
{
// Range is set later for anomalous triggers
m_activatedPrimitive =
CDriverPrimitive(m_axisIndex, m_config.center,
CJoystickTranslator::PositionToSemiAxisDirection(position), 1);
m_activationTimeMs = std::chrono::steady_clock::now();
}
}
}
return true;
}
void CAxisDetector::ProcessMotion()
{
// Process newly-activated axis
if (m_state == AXIS_STATE::ACTIVATED)
{
// Ignore anomalous triggers for a bit so we can detect the full range
bool bIgnore = false;
if (m_type == AXIS_TYPE::OFFSET)
{
auto now = std::chrono::steady_clock::now();
auto duration =
std::chrono::duration_cast<std::chrono::milliseconds>(now - m_activationTimeMs);
if (duration.count() < TRIGGER_DELAY_MS)
bIgnore = true;
}
if (!bIgnore)
{
// Update driver primitive's range if we're mapping an anomalous trigger
if (m_type == AXIS_TYPE::OFFSET)
{
m_activatedPrimitive =
CDriverPrimitive(m_activatedPrimitive.Index(), m_activatedPrimitive.Center(),
m_activatedPrimitive.SemiAxisDirection(), m_config.range);
}
// Map primitive
if (!MapPrimitive(m_activatedPrimitive))
{
if (m_type == AXIS_TYPE::OFFSET)
CLog::Log(LOGDEBUG, "Mapping offset axis {} failed", m_axisIndex);
else
CLog::Log(LOGDEBUG, "Mapping normal axis {} failed", m_axisIndex);
}
m_state = AXIS_STATE::MAPPED;
}
}
}
void CAxisDetector::SetEmitted(const CDriverPrimitive& activePrimitive)
{
m_state = AXIS_STATE::MAPPED;
m_activatedPrimitive = activePrimitive;
}
void CAxisDetector::DetectType(float position)
{
// Some platforms don't report a value until the axis is first changed.
// Detection relies on an initial value, so this axis will be disabled until
// the user begins button mapping again.
if (m_config.bLateDiscovery)
return;
// Update range if a range of > 1 is observed
if (std::abs(position - m_config.center) > 1.0f)
m_config.range = 2;
if (m_type != AXIS_TYPE::UNKNOWN)
return;
if (m_config.bKnown)
{
if (m_config.center == 0)
m_type = AXIS_TYPE::NORMAL;
else
m_type = AXIS_TYPE::OFFSET;
}
if (m_type != AXIS_TYPE::UNKNOWN)
return;
if (!m_initialPositionKnown)
{
m_initialPositionKnown = true;
m_initialPosition = position;
}
if (position != m_initialPosition)
m_initialPositionChanged = true;
if (m_initialPositionChanged)
{
// Calculate center based on initial position.
if (m_initialPosition < -0.5f)
{
m_config.center = -1;
m_type = AXIS_TYPE::OFFSET;
CLog::Log(LOGDEBUG, "Anomalous trigger detected on axis {} with center {}", m_axisIndex,
m_config.center);
}
else if (m_initialPosition > 0.5f)
{
m_config.center = 1;
m_type = AXIS_TYPE::OFFSET;
CLog::Log(LOGDEBUG, "Anomalous trigger detected on axis {} with center {}", m_axisIndex,
m_config.center);
}
else
{
m_type = AXIS_TYPE::NORMAL;
CLog::Log(LOGDEBUG, "Normal axis detected on axis {}", m_axisIndex);
}
}
}
// --- CKeyDetector ---------------------------------------------------------
CKeyDetector::CKeyDetector(CButtonMapping* buttonMapping, XBMCKey keycode)
: CPrimitiveDetector(buttonMapping), m_keycode(keycode)
{
}
bool CKeyDetector::OnMotion(bool bPressed)
{
if (bPressed)
return MapPrimitive(CDriverPrimitive(m_keycode));
return false;
}
// --- CMouseButtonDetector ----------------------------------------------------
CMouseButtonDetector::CMouseButtonDetector(CButtonMapping* buttonMapping,
MOUSE::BUTTON_ID buttonIndex)
: CPrimitiveDetector(buttonMapping), m_buttonIndex(buttonIndex)
{
}
bool CMouseButtonDetector::OnMotion(bool bPressed)
{
if (bPressed)
return MapPrimitive(CDriverPrimitive(m_buttonIndex));
return false;
}
// --- CPointerDetector --------------------------------------------------------
CPointerDetector::CPointerDetector(CButtonMapping* buttonMapping)
: CPrimitiveDetector(buttonMapping)
{
}
bool CPointerDetector::OnMotion(int x, int y)
{
if (!m_bStarted)
{
m_bStarted = true;
m_startX = x;
m_startY = y;
m_frameCount = 0;
}
if (m_frameCount++ >= MIN_FRAME_COUNT)
{
int dx = x - m_startX;
int dy = y - m_startY;
INPUT::INTERCARDINAL_DIRECTION dir = GetPointerDirection(dx, dy);
CDriverPrimitive primitive(static_cast<RELATIVE_POINTER_DIRECTION>(dir));
if (primitive.IsValid())
{
if (MapPrimitive(primitive))
m_bStarted = false;
}
}
return true;
}
KODI::INPUT::INTERCARDINAL_DIRECTION CPointerDetector::GetPointerDirection(int x, int y)
{
using namespace INPUT;
// Translate from left-handed coordinate system to right-handed coordinate system
y *= -1;
return CInputTranslator::VectorToIntercardinalDirection(static_cast<float>(x),
static_cast<float>(y));
}
// --- CButtonMapping ----------------------------------------------------------
CButtonMapping::CButtonMapping(IButtonMapper* buttonMapper, IButtonMap* buttonMap, IKeymap* keymap)
: m_buttonMapper(buttonMapper), m_buttonMap(buttonMap), m_keymap(keymap), m_frameCount(0)
{
assert(m_buttonMapper != nullptr);
assert(m_buttonMap != nullptr);
// Make sure axes mapped to Select are centered before they can be mapped.
// This ensures that they are not immediately mapped to the first button.
if (m_keymap)
{
using namespace GAME;
CControllerManager& controllerManager = CServiceBroker::GetGameControllerManager();
ControllerPtr controller = controllerManager.GetController(m_keymap->ControllerID());
const auto& features = controller->Features();
for (const auto& feature : features)
{
bool bIsSelectAction = false;
const auto& actions =
m_keymap->GetActions(CJoystickUtils::MakeKeyName(feature.Name())).actions;
if (!actions.empty() && actions.begin()->actionId == ACTION_SELECT_ITEM)
bIsSelectAction = true;
if (!bIsSelectAction)
continue;
CDriverPrimitive primitive;
if (!m_buttonMap->GetScalar(feature.Name(), primitive))
continue;
if (primitive.Type() != PRIMITIVE_TYPE::SEMIAXIS)
continue;
// Set initial config, as detection will fail because axis is already activated
AxisConfiguration axisConfig;
axisConfig.bKnown = true;
axisConfig.center = primitive.Center();
axisConfig.range = primitive.Range();
GetAxis(primitive.Index(), static_cast<float>(primitive.Center()), axisConfig)
.SetEmitted(primitive);
}
}
}
bool CButtonMapping::OnButtonMotion(unsigned int buttonIndex, bool bPressed)
{
if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::BUTTON))
return false;
return GetButton(buttonIndex).OnMotion(bPressed);
}
bool CButtonMapping::OnHatMotion(unsigned int hatIndex, HAT_STATE state)
{
if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::HAT))
return false;
return GetHat(hatIndex).OnMotion(state);
}
bool CButtonMapping::OnAxisMotion(unsigned int axisIndex,
float position,
int center,
unsigned int range)
{
if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::SEMIAXIS))
return false;
return GetAxis(axisIndex, position).OnMotion(position);
}
void CButtonMapping::OnInputFrame(void)
{
for (auto& axis : m_axes)
axis.second.ProcessMotion();
m_buttonMapper->OnEventFrame(m_buttonMap, IsMapping());
m_frameCount++;
}
bool CButtonMapping::OnKeyPress(const CKey& key)
{
if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::KEY))
return false;
return GetKey(static_cast<XBMCKey>(key.GetKeycode())).OnMotion(true);
}
bool CButtonMapping::OnPosition(int x, int y)
{
if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::RELATIVE_POINTER))
return false;
return GetPointer().OnMotion(x, y);
}
bool CButtonMapping::OnButtonPress(MOUSE::BUTTON_ID button)
{
if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::MOUSE_BUTTON))
return false;
return GetMouseButton(button).OnMotion(true);
}
void CButtonMapping::OnButtonRelease(MOUSE::BUTTON_ID button)
{
if (!m_buttonMapper->AcceptsPrimitive(PRIMITIVE_TYPE::MOUSE_BUTTON))
return;
GetMouseButton(button).OnMotion(false);
}
void CButtonMapping::SaveButtonMap()
{
m_buttonMap->SaveButtonMap();
}
void CButtonMapping::ResetIgnoredPrimitives()
{
std::vector<CDriverPrimitive> empty;
m_buttonMap->SetIgnoredPrimitives(empty);
}
void CButtonMapping::RevertButtonMap()
{
m_buttonMap->RevertButtonMap();
}
bool CButtonMapping::MapPrimitive(const CDriverPrimitive& primitive)
{
bool bHandled = false;
auto now = std::chrono::steady_clock::now();
bool bTimeoutElapsed = true;
if (m_buttonMapper->NeedsCooldown())
bTimeoutElapsed = (now >= m_lastAction + std::chrono::milliseconds(MAPPING_COOLDOWN_MS));
if (bTimeoutElapsed)
{
bHandled = m_buttonMapper->MapPrimitive(m_buttonMap, m_keymap, primitive);
if (bHandled)
m_lastAction = std::chrono::steady_clock::now();
}
else if (m_buttonMap->IsIgnored(primitive))
{
bHandled = true;
}
else
{
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(now - m_lastAction);
CLog::Log(LOGDEBUG, "Button mapping: rapid input after {}ms dropped for profile \"{}\"",
duration.count(), m_buttonMapper->ControllerID());
bHandled = true;
}
return bHandled;
}
bool CButtonMapping::IsMapping() const
{
for (auto itAxis : m_axes)
{
if (itAxis.second.IsMapping())
return true;
}
return false;
}
CButtonDetector& CButtonMapping::GetButton(unsigned int buttonIndex)
{
auto itButton = m_buttons.find(buttonIndex);
if (itButton == m_buttons.end())
{
m_buttons.insert(std::make_pair(buttonIndex, CButtonDetector(this, buttonIndex)));
itButton = m_buttons.find(buttonIndex);
}
return itButton->second;
}
CHatDetector& CButtonMapping::GetHat(unsigned int hatIndex)
{
auto itHat = m_hats.find(hatIndex);
if (itHat == m_hats.end())
{
m_hats.insert(std::make_pair(hatIndex, CHatDetector(this, hatIndex)));
itHat = m_hats.find(hatIndex);
}
return itHat->second;
}
CAxisDetector& CButtonMapping::GetAxis(
unsigned int axisIndex,
float position,
const AxisConfiguration& initialConfig /* = AxisConfiguration() */)
{
auto itAxis = m_axes.find(axisIndex);
if (itAxis == m_axes.end())
{
AxisConfiguration config(initialConfig);
if (m_frameCount >= 2)
{
config.bLateDiscovery = true;
OnLateDiscovery(axisIndex);
}
// Report axis
CLog::Log(LOGDEBUG, "Axis {} discovered at position {:.4f} after {} frames", axisIndex,
position, static_cast<unsigned long>(m_frameCount));
m_axes.insert(std::make_pair(axisIndex, CAxisDetector(this, axisIndex, config)));
itAxis = m_axes.find(axisIndex);
}
return itAxis->second;
}
CKeyDetector& CButtonMapping::GetKey(XBMCKey keycode)
{
auto itKey = m_keys.find(keycode);
if (itKey == m_keys.end())
{
m_keys.insert(std::make_pair(keycode, CKeyDetector(this, keycode)));
itKey = m_keys.find(keycode);
}
return itKey->second;
}
CMouseButtonDetector& CButtonMapping::GetMouseButton(MOUSE::BUTTON_ID buttonIndex)
{
auto itButton = m_mouseButtons.find(buttonIndex);
if (itButton == m_mouseButtons.end())
{
m_mouseButtons.insert(std::make_pair(buttonIndex, CMouseButtonDetector(this, buttonIndex)));
itButton = m_mouseButtons.find(buttonIndex);
}
return itButton->second;
}
CPointerDetector& CButtonMapping::GetPointer()
{
if (!m_pointer)
m_pointer.reset(new CPointerDetector(this));
return *m_pointer;
}
void CButtonMapping::OnLateDiscovery(unsigned int axisIndex)
{
m_buttonMapper->OnLateAxis(m_buttonMap, axisIndex);
}
|