Repository navigation
Expand file tree
/
Copy pathVirtualController.cpp
More file actions
451 lines (374 loc) · 15 KB
/
Copy pathVirtualController.cpp
File metadata and controls
451 lines (374 loc) · 15 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
/***************************************************************************************************
* Xidi
* DirectInput interface for XInput controllers.
***************************************************************************************************
* Authored by Samuel Grossman
* Copyright (c) 2016-2026
***********************************************************************************************//**
* @file VirtualController.cpp
* Implementation of a complete virtual controller.
**************************************************************************************************/
#include "VirtualController.h"
#include <cstdint>
#include <stop_token>
#include <thread>
#include <Infra/Core/Message.h>
#include "ForceFeedbackTypes.h"
#include "ImportApiWinMM.h"
#include "Mapper.h"
#include "PhysicalController.h"
#include "VirtualControllerTypes.h"
namespace Xidi
{
namespace Controller
{
/// Maps a value in one range to its corresponding value in another range.
/// Ranges are specified as origin values and displacements, essentially one-dimensional vectors
/// with direction either positive (maximum displacement value is greater than origin value) or
/// negative (maximum displacement value is less than origin value). It is not necessary that
/// the direction of the vectors be the same for both old and new range.
/// @param [in] oldRangeValue Raw value to transform in the old range.
/// @param [in] oldRangeOrigin Origin value of the old range.
/// @param [in] oldRangeDispMax Maximum displacement value in the old range.
/// @param [in] newRangeOrigin Origin value of the new range.
/// @param [in] newRangeDispMax Maximum displacement value in the new range.
/// @return Result of mapping the input value from the old range to the new range.
static inline int32_t MapValueInRangeToRange(
int32_t oldRangeValue,
int32_t oldRangeOrigin,
int32_t oldRangeDispMax,
int32_t newRangeOrigin,
int32_t newRangeDispMax)
{
const int64_t oldRangeValueDisp = (int64_t)oldRangeValue - (int64_t)oldRangeOrigin;
const int64_t newRangeMagnitudeMax = (int64_t)newRangeDispMax - (int64_t)newRangeOrigin;
const int64_t oldRangeMagnitudeMax = (int64_t)oldRangeDispMax - (int64_t)oldRangeOrigin;
return newRangeOrigin +
(int32_t)((oldRangeValueDisp * newRangeMagnitudeMax) / oldRangeMagnitudeMax);
}
/// Monitors for changes in an associated physical controller's state and, on state change,
/// causes a virtual controller to refresh its state. Intended to be the entry point for
/// per-virtual-controller background threads.
/// @param [in] thisController Controller object for which state is to be monitored.
/// @param [in] initialState Initial physical state of the controller. Used as the basis for
/// looking for changes.
/// @param [in] stopMonitoringToken Used to indicate that the monitoring should stop and the
/// thread should exit.
static void MonitorPhysicalControllerState(
VirtualController* thisController,
const SState& initialState,
std::stop_token stopMonitoringToken)
{
const TControllerIdentifier controllerIdentifier = thisController->GetIdentifier();
SState state = initialState;
while (false == stopMonitoringToken.stop_requested())
{
if (true ==
WaitForRawVirtualControllerStateChange(
controllerIdentifier, state, stopMonitoringToken))
{
if (true == thisController->RefreshState(state)) thisController->SignalStateChangeEvent();
}
}
}
/// Looks for differences between two virtual controller state objects and submits them as
/// events to the specified event buffer. Events are only submitted if the associated virtual
/// controller element is included in the event filter.
/// @param [in] oldState Old controller state, the baseline.
/// @param [in] newState New controller state, which is compared with the old controller state.
/// If different, controller element values submitted to the event buffer come from this object.
/// @param [in] eventFilter Filter which specifies which virtual controller elements are allowed
/// to generate events.
/// @param [in,out] eventBuffer Event buffer object to which events are submitted.
static inline void SubmitStateChangeEvents(
const SState& oldState,
const SState& newState,
const VirtualController::EventFilter& eventFilter,
StateChangeEventBuffer& eventBuffer)
{
if (true == eventBuffer.IsEnabled())
{
const uint32_t timestamp = ImportApiWinMM::timeGetTime();
for (unsigned int i = 0; i < oldState.axis.size(); ++i)
{
if (oldState.axis[i] != newState.axis[i])
{
const SElementIdentifier axisElement = {.type = EElementType::Axis, .axis = (EAxis)i};
if (eventFilter.Contains(axisElement))
eventBuffer.AppendEvent(
{.element = axisElement, .value = {.axis = newState.axis[i]}}, timestamp);
}
}
for (unsigned int i = 0; i < oldState.button.size(); ++i)
{
if (oldState.button[i] != newState.button[i])
{
const SElementIdentifier buttonElement = {
.type = EElementType::Button, .button = (EButton)i};
if (eventFilter.Contains(buttonElement))
eventBuffer.AppendEvent(
{.element = buttonElement, .value = {.button = newState.button[i]}}, timestamp);
}
}
if (oldState.povDirection.all != newState.povDirection.all)
{
const SElementIdentifier povElement = {.type = EElementType::Pov};
if (eventFilter.Contains(povElement))
eventBuffer.AppendEvent(
{.element = povElement,
.value = {.povDirection = {.all = newState.povDirection.all}}},
timestamp);
}
}
}
/// Transforms a raw axis value using the supplied axis properties.
/// @param [in] axisValueRaw Raw axis value as obtained from a mapper.
/// @param [in] axisProperties Axis properties to apply.
/// @return Axis value that results from applying the transformation.
static int32_t TransformAxisValue(
int32_t axisValueRaw, const VirtualController::SAxisProperties& axisProperties)
{
if (true != axisProperties.transformationsEnabled) return axisValueRaw;
if (axisValueRaw > kAnalogValueNeutral)
{
if (axisValueRaw <= axisProperties.deadzoneRawCutoffPositive)
return axisProperties.rangeNeutral;
else if (axisValueRaw >= axisProperties.saturationRawCutoffPositive)
return axisProperties.rangeMax;
else
return MapValueInRangeToRange(
axisValueRaw,
axisProperties.deadzoneRawCutoffPositive,
axisProperties.saturationRawCutoffPositive,
axisProperties.rangeNeutral,
axisProperties.rangeMax);
}
else
{
if (axisValueRaw >= axisProperties.deadzoneRawCutoffNegative)
return axisProperties.rangeNeutral;
else if (axisValueRaw <= axisProperties.saturationRawCutoffNegative)
return axisProperties.rangeMin;
else
return MapValueInRangeToRange(
axisValueRaw,
axisProperties.deadzoneRawCutoffNegative,
axisProperties.saturationRawCutoffNegative,
axisProperties.rangeNeutral,
axisProperties.rangeMin);
}
}
VirtualController::VirtualController(TControllerIdentifier controllerId)
: kControllerIdentifier(controllerId),
controllerMutex(),
eventBuffer(),
eventFilter(),
properties(),
stateRaw(),
stateProcessed(),
stateChangeEventHandle(NULL),
physicalControllerMonitor(),
physicalControllerMonitorStop(),
physicalControllerForceFeedbackBuffer()
{
const SState initialState = GetCurrentRawVirtualControllerState(kControllerIdentifier);
RefreshState(initialState);
ReapplyProperties();
physicalControllerMonitor = std::thread(
MonitorPhysicalControllerState,
this,
initialState,
physicalControllerMonitorStop.get_token());
Infra::Message::OutputFormatted(
Infra::Message::ESeverity::Info,
L"Created virtual controller object with identifier %u.",
(1 + kControllerIdentifier));
}
VirtualController::~VirtualController(void)
{
ForceFeedbackUnregister();
physicalControllerMonitorStop.request_stop();
physicalControllerMonitor.join();
Infra::Message::OutputFormatted(
Infra::Message::ESeverity::Info,
L"Destroyed virtual controller object with identifier %u.",
(1 + kControllerIdentifier));
}
TControllerIdentifier VirtualController::GetActualCount(void)
{
static const TControllerIdentifier kActualVirtualControllerCount = std::min(
kVirtualControllerMaxCount, GetPhysicalControllerBackend()->MaxPhysicalControllerCount());
return kActualVirtualControllerCount;
}
void VirtualController::ApplyProperties(SState& controllerState) const
{
const SCapabilities capabilities = GetCapabilities();
for (int i = 0; i < capabilities.numAxes; ++i)
{
const EAxis axis = capabilities.axisCapabilities[i].type;
controllerState[axis] = TransformAxisValue(controllerState[axis], properties[axis]);
}
}
bool VirtualController::ForceFeedbackRegister(void)
{
auto lock = Lock();
if (nullptr == physicalControllerForceFeedbackBuffer)
physicalControllerForceFeedbackBuffer =
PhysicalControllerForceFeedbackRegister(kControllerIdentifier, this);
return ForceFeedbackIsRegistered();
}
void VirtualController::ForceFeedbackUnregister(void)
{
auto lock = Lock();
PhysicalControllerForceFeedbackUnregister(kControllerIdentifier, this);
physicalControllerForceFeedbackBuffer = nullptr;
}
SCapabilities VirtualController::GetCapabilities(void) const
{
return GetVirtualControllerCapabilities(kControllerIdentifier);
}
SState VirtualController::GetState(void)
{
auto lock = Lock();
return stateProcessed;
}
void VirtualController::PopEventBufferOldestEvents(uint32_t numEventsToPop)
{
auto lock = Lock();
eventBuffer.PopOldestEvents(numEventsToPop);
}
void VirtualController::ReapplyProperties(void)
{
stateProcessed = stateRaw;
ApplyProperties(stateProcessed);
}
bool VirtualController::RefreshState(SState newStateRaw)
{
auto lock = Lock();
stateRaw = newStateRaw;
SState newStateProcessed = newStateRaw;
ApplyProperties(newStateProcessed);
// Based on the mapper and the applied properties, a change in raw virtual controller state
// might not necessarily mean a change in processed virtual controller state. For example,
// deadzone might result in filtering out changes in analog stick position, or if a particular
// XInput controller element is ignored by the mapper then a change in that element does not
// influence the virtual controller state.
if (newStateProcessed == stateProcessed) return false;
SubmitStateChangeEvents(stateProcessed, newStateProcessed, eventFilter, eventBuffer);
stateProcessed = newStateProcessed;
return true;
}
bool VirtualController::SetAxisDeadzone(EAxis axis, uint32_t deadzone)
{
if ((deadzone >= kAxisDeadzoneMin) && (deadzone <= kAxisDeadzoneMax))
{
auto lock = Lock();
properties[axis].SetDeadzone(deadzone);
ReapplyProperties();
return true;
}
return false;
}
bool VirtualController::SetAxisRange(EAxis axis, int32_t rangeMin, int32_t rangeMax)
{
if (rangeMax > rangeMin)
{
auto lock = Lock();
properties[axis].SetRange(rangeMin, rangeMax);
ReapplyProperties();
return true;
}
return false;
}
bool VirtualController::SetAxisSaturation(EAxis axis, uint32_t saturation)
{
if ((saturation >= kAxisSaturationMin) && (saturation <= kAxisSaturationMax))
{
auto lock = Lock();
properties[axis].SetSaturation(saturation);
ReapplyProperties();
return true;
}
return false;
}
void VirtualController::SetAxisTransformationsEnabled(EAxis axis, bool transformationsEnabled)
{
auto lock = Lock();
properties[axis].SetTransformationsEnabled(transformationsEnabled);
ReapplyProperties();
}
bool VirtualController::SetAllAxisDeadzone(uint32_t deadzone)
{
if ((deadzone >= kAxisDeadzoneMin) && (deadzone <= kAxisDeadzoneMax))
{
auto lock = Lock();
for (auto& axis : properties.axis)
axis.SetDeadzone(deadzone);
ReapplyProperties();
return true;
}
return false;
}
bool VirtualController::SetAllAxisRange(int32_t rangeMin, int32_t rangeMax)
{
if (rangeMax > rangeMin)
{
auto lock = Lock();
for (auto& axis : properties.axis)
axis.SetRange(rangeMin, rangeMax);
ReapplyProperties();
return true;
}
return false;
}
bool VirtualController::SetAllAxisSaturation(uint32_t saturation)
{
if ((saturation >= kAxisSaturationMin) && (saturation <= kAxisSaturationMax))
{
auto lock = Lock();
for (auto& axis : properties.axis)
axis.SetSaturation(saturation);
ReapplyProperties();
return true;
}
return false;
}
void VirtualController::SetAllAxisTransformationsEnabled(bool transformationsEnabled)
{
auto lock = Lock();
for (auto& axis : properties.axis)
axis.SetTransformationsEnabled(transformationsEnabled);
ReapplyProperties();
}
bool VirtualController::SetEventBufferCapacity(uint32_t capacity)
{
if (capacity != eventBuffer.GetCapacity())
{
auto lock = Lock();
eventBuffer.SetCapacity(capacity);
}
return true;
}
bool VirtualController::SetForceFeedbackGain(uint32_t ffGain)
{
const ForceFeedback::TEffectValue newFfGain = (ForceFeedback::TEffectValue)ffGain;
if ((newFfGain >= kFfGainMin) && (newFfGain <= kFfGainMax))
{
auto lock = Lock();
properties.device.SetFfGain(newFfGain);
return true;
}
return false;
}
void VirtualController::SetStateChangeEvent(HANDLE eventHandle)
{
stateChangeEventHandle = eventHandle;
}
void VirtualController::SignalStateChangeEvent(void)
{
const HANDLE eventHandleToSignal = stateChangeEventHandle;
if ((NULL != eventHandleToSignal) && (INVALID_HANDLE_VALUE != eventHandleToSignal))
SetEvent(eventHandleToSignal);
}
} // namespace Controller
} // namespace Xidi