| 1 | // Copyright 2022 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "InputCommon/ControllerInterface/MappingCommon.h" |
| 5 | |
| 6 | #include <algorithm> |
| 7 | #include <chrono> |
| 8 | #include <cmath> |
| 9 | #include <ranges> |
| 10 | #include <string> |
| 11 | #include <vector> |
| 12 | |
| 13 | #include <fmt/format.h> |
| 14 | #include <fmt/ranges.h> |
| 15 | |
| 16 | #include "Common/MathUtil.h" |
| 17 | #include "Common/StringUtil.h" |
| 18 | |
| 19 | #include "InputCommon/ControllerEmu/ControllerEmu.h" |
| 20 | #include "InputCommon/ControllerEmu/StickGate.h" |
| 21 | #include "InputCommon/ControllerInterface/ControllerInterface.h" |
| 22 | #include "InputCommon/ControllerInterface/CoreDevice.h" |
| 23 | #include "InputCommon/InputConfig.h" |
| 24 | |
| 25 | namespace ciface::MappingCommon |
| 26 | { |
| 27 | // Pressing inputs at the same time will result in the & operator vs a hotkey expression. |
| 28 | constexpr auto HOTKEY_VS_CONJUNCION_THRESHOLD = std::chrono::milliseconds(50); |
| 29 | |
| 30 | // Some devices (e.g. DS4) provide an analog and digital input for the trigger. |
| 31 | // We prefer just the analog input for simultaneous digital+analog input detections. |
| 32 | constexpr auto SPURIOUS_TRIGGER_COMBO_THRESHOLD = std::chrono::milliseconds(150); |
| 33 | |
| 34 | std::string GetExpressionForControl(const std::string& control_name, |
| 35 | const ciface::Core::DeviceQualifier& control_device, |
| 36 | const ciface::Core::DeviceQualifier& default_device, |
| 37 | Quote quote) |
| 38 | { |
| 39 | std::string expr; |
| 40 | |
| 41 | // non-default device |
| 42 | if (control_device != default_device) |
| 43 | { |
| 44 | expr += control_device.ToString(); |
| 45 | expr += ':'; |
| 46 | } |
| 47 | |
| 48 | // append the control name |
| 49 | expr += control_name; |
| 50 | |
| 51 | if (quote == Quote::On) |
| 52 | { |
| 53 | // If our expression contains any non-alpha characters |
| 54 | // we should quote it |
| 55 | if (!std::ranges::all_of(expr, Common::IsAlpha)) |
| 56 | expr = fmt::format("`{}`", expr); |
| 57 | } |
| 58 | |
| 59 | return expr; |
| 60 | } |
| 61 | |
| 62 | std::string BuildExpression(const Core::InputDetector::Results& detections, |
| 63 | const ciface::Core::DeviceQualifier& default_device, Quote quote) |
| 64 | { |
| 65 | std::vector<const Core::InputDetector::Detection*> pressed_inputs; |
| 66 | |
| 67 | std::vector<std::string> alternations; |
| 68 | |
| 69 | const auto get_control_expression = [&](auto& detection) { |
| 70 | // Return the parent-most name if there is one for better hotkey strings. |
| 71 | // Detection of L/R_Ctrl will be changed to just Ctrl. |
| 72 | // Users can manually map L_Ctrl if they so desire. |
| 73 | const auto input = (quote == Quote::On) ? |
| 74 | detection.device->GetParentMostInput(detection.input) : |
| 75 | detection.input; |
| 76 | |
| 77 | ciface::Core::DeviceQualifier device_qualifier; |
| 78 | device_qualifier.FromDevice(detection.device.get()); |
| 79 | |
| 80 | return MappingCommon::GetExpressionForControl(input->GetName(), device_qualifier, |
| 81 | default_device, quote); |
| 82 | }; |
| 83 | |
| 84 | bool new_alternation = false; |
| 85 | |
| 86 | const auto handle_press = [&](auto& detection) { |
| 87 | pressed_inputs.emplace_back(&detection); |
| 88 | new_alternation = true; |
| 89 | }; |
| 90 | |
| 91 | const auto handle_release = [&] { |
| 92 | if (!new_alternation) |
| 93 | return; |
| 94 | |
| 95 | new_alternation = false; |
| 96 | |
| 97 | std::vector<std::string> alternation; |
| 98 | for (auto* input : pressed_inputs) |
| 99 | alternation.push_back(get_control_expression(*input)); |
| 100 | |
| 101 | const bool is_hotkey = pressed_inputs.size() >= 2 && |
| 102 | (pressed_inputs[1]->press_time - pressed_inputs[0]->press_time) > |
| 103 | HOTKEY_VS_CONJUNCION_THRESHOLD; |
| 104 | |
| 105 | if (is_hotkey) |
| 106 | { |
| 107 | alternations.push_back(fmt::format("@({})", fmt::join(alternation, "+"))); |
| 108 | } |
| 109 | else |
| 110 | { |
| 111 | std::ranges::sort(alternation); |
| 112 | alternations.push_back(fmt::to_string(fmt::join(alternation, "&"))); |
| 113 | } |
| 114 | }; |
| 115 | |
| 116 | for (auto& detection : detections) |
| 117 | { |
| 118 | // Remove since-released inputs. |
| 119 | for (auto it = pressed_inputs.begin(); it != pressed_inputs.end();) |
| 120 | { |
| 121 | if ((*it)->release_time && (*it)->release_time <= detection.press_time) |
| 122 | { |
| 123 | handle_release(); |
| 124 | it = pressed_inputs.erase(it); |
| 125 | } |
| 126 | else |
| 127 | { |
| 128 | ++it; |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | handle_press(detection); |
| 133 | } |
| 134 | |
| 135 | handle_release(); |
| 136 | |
| 137 | // Remove duplicates |
| 138 | std::ranges::sort(alternations); |
| 139 | const auto unique_result = std::ranges::unique(alternations); |
| 140 | alternations.erase(unique_result.begin(), unique_result.end()); |
| 141 | |
| 142 | return fmt::to_string(fmt::join(alternations, "|")); |
| 143 | } |
| 144 | |
| 145 | void RemoveSpuriousTriggerCombinations(Core::InputDetector::Results* detections) |
| 146 | { |
| 147 | const auto is_spurious = [&](const auto& detection) { |
| 148 | return std::ranges::any_of(*detections, [&](const auto& d) { |
| 149 | // This is a spurious digital detection if a "smooth" (analog) detection is temporally near. |
| 150 | return &d != &detection && d.IsAnalogPress() && !detection.IsAnalogPress() && |
| 151 | abs(d.press_time - detection.press_time) < SPURIOUS_TRIGGER_COMBO_THRESHOLD; |
| 152 | }); |
| 153 | }; |
| 154 | |
| 155 | std::erase_if(*detections, is_spurious); |
| 156 | } |
| 157 | |
| 158 | void RemoveDetectionsAfterTimePoint(Core::InputDetector::Results* results, Clock::time_point after) |
| 159 | { |
| 160 | const auto is_after_time = [&](const Core::InputDetector::Detection& detection) { |
| 161 | return detection.release_time.value_or(after) >= after; |
| 162 | }; |
| 163 | |
| 164 | std::erase_if(*results, is_after_time); |
| 165 | } |
| 166 | |
| 167 | bool ContainsCompleteDetection(const Core::InputDetector::Results& results) |
| 168 | { |
| 169 | return std::ranges::any_of(results, [](const Core::InputDetector::Detection& detection) { |
| 170 | return detection.release_time.has_value(); |
| 171 | }); |
| 172 | } |
| 173 | |
| 174 | ReshapableInputMapper::ReshapableInputMapper(const Core::DeviceContainer& container, |
| 175 | std::span<const std::string> device_strings) |
| 176 | { |
| 177 | m_input_detector.Start(container, device_strings); |
| 178 | } |
| 179 | |
| 180 | bool ReshapableInputMapper::Update() |
| 181 | { |
| 182 | const auto prev_size = m_input_detector.GetResults().size(); |
| 183 | |
| 184 | constexpr auto wait_time = std::chrono::seconds{4}; |
| 185 | m_input_detector.Update(wait_time, wait_time, wait_time * REQUIRED_INPUT_COUNT); |
| 186 | |
| 187 | return m_input_detector.GetResults().size() != prev_size; |
| 188 | } |
| 189 | |
| 190 | float ReshapableInputMapper::GetCurrentAngle() const |
| 191 | { |
| 192 | constexpr auto quarter_circle = float(MathUtil::TAU) * 0.25f; |
| 193 | return quarter_circle - (float(m_input_detector.GetResults().size()) * quarter_circle); |
| 194 | } |
| 195 | |
| 196 | bool ReshapableInputMapper::IsComplete() const |
| 197 | { |
| 198 | return m_input_detector.GetResults().size() >= REQUIRED_INPUT_COUNT || |
| 199 | m_input_detector.IsComplete(); |
| 200 | } |
| 201 | |
| 202 | bool ReshapableInputMapper::IsCalibrationNeeded() const |
| 203 | { |
| 204 | return std::ranges::any_of(m_input_detector.GetResults() | std::views::take(REQUIRED_INPUT_COUNT), |
| 205 | &ciface::Core::InputDetector::Detection::IsAnalogPress); |
| 206 | } |
| 207 | |
| 208 | bool ReshapableInputMapper::ApplyResults(ControllerEmu::EmulatedController* controller, |
| 209 | ControllerEmu::ReshapableInput* stick) |
| 210 | { |
| 211 | auto const detections = m_input_detector.TakeResults(); |
| 212 | |
| 213 | if (detections.size() < REQUIRED_INPUT_COUNT) |
| 214 | return false; |
| 215 | |
| 216 | // Transpose URDL to UDLR. |
| 217 | const std::array results{detections[0], detections[2], detections[3], detections[1]}; |
| 218 | |
| 219 | const auto default_device = controller->GetDefaultDevice(); |
| 220 | |
| 221 | for (std::size_t i = 0; i != results.size(); ++i) |
| 222 | { |
| 223 | ciface::Core::DeviceQualifier device_qualifier; |
| 224 | device_qualifier.FromDevice(results[i].device.get()); |
| 225 | |
| 226 | stick->controls[i]->control_ref->SetExpression(ciface::MappingCommon::GetExpressionForControl( |
| 227 | results[i].input->GetName(), device_qualifier, default_device, |
| 228 | ciface::MappingCommon::Quote::On)); |
| 229 | |
| 230 | controller->UpdateSingleControlReference(g_controller_interface, |
| 231 | stick->controls[i]->control_ref.get()); |
| 232 | } |
| 233 | |
| 234 | controller->GetConfig()->GenerateControllerTextures(); |
| 235 | |
| 236 | return true; |
| 237 | } |
| 238 | |
| 239 | CalibrationBuilder::CalibrationBuilder(std::optional<Common::DVec2> center) |
| 240 | : m_calibration_data(ControllerEmu::ReshapableInput::CALIBRATION_SAMPLE_COUNT, 0.0), |
| 241 | m_center{center} |
| 242 | { |
| 243 | } |
| 244 | |
| 245 | void CalibrationBuilder::Update(Common::DVec2 point) |
| 246 | { |
| 247 | if (!m_center.has_value()) |
| 248 | m_center = point; |
| 249 | |
| 250 | const auto new_point = point - *m_center; |
| 251 | ControllerEmu::ReshapableInput::UpdateCalibrationData(m_calibration_data, m_prev_point, |
| 252 | new_point); |
| 253 | m_prev_point = new_point; |
| 254 | } |
| 255 | |
| 256 | bool CalibrationBuilder::IsCalibrationDataSensible() const |
| 257 | { |
| 258 | // Even the GC controller's small range would pass this test. |
| 259 | constexpr double REASONABLE_AVERAGE_RADIUS = 0.6; |
| 260 | |
| 261 | // Test that the average input radius is not below a threshold. |
| 262 | // This will make sure the user has actually moved their stick from neutral. |
| 263 | |
| 264 | MathUtil::RunningVariance<ControlState> stats; |
| 265 | |
| 266 | for (const auto x : m_calibration_data) |
| 267 | stats.Push(x); |
| 268 | |
| 269 | if (stats.Mean() < REASONABLE_AVERAGE_RADIUS) |
| 270 | return false; |
| 271 | |
| 272 | // Test that the standard deviation is below a threshold. |
| 273 | // This will make sure the user has not just filled in one side of their input. |
| 274 | |
| 275 | // Approx. deviation of a square input gate, anything much more than that would be unusual. |
| 276 | constexpr double REASONABLE_DEVIATION = 0.14; |
| 277 | |
| 278 | return stats.StandardDeviation() < REASONABLE_DEVIATION; |
| 279 | } |
| 280 | |
| 281 | bool CalibrationBuilder::IsComplete() const |
| 282 | { |
| 283 | if (!IsCalibrationDataSensible()) |
| 284 | return false; |
| 285 | |
| 286 | const auto half_calibration = |
| 287 | 0.5 * GetCalibrationRadiusAtAngle(std::atan2(m_prev_point.y, m_prev_point.x) + MathUtil::TAU); |
| 288 | return m_prev_point.LengthSquared() < (half_calibration * half_calibration); |
| 289 | } |
| 290 | |
| 291 | ControlState CalibrationBuilder::GetCalibrationRadiusAtAngle(double angle) const |
| 292 | { |
| 293 | return ControllerEmu::ReshapableInput::GetCalibrationDataRadiusAtAngle(m_calibration_data, angle); |
| 294 | } |
| 295 | |
| 296 | void CalibrationBuilder::ApplyResults(ControllerEmu::ReshapableInput* stick) |
| 297 | { |
| 298 | stick->SetCenter(GetCenter()); |
| 299 | stick->SetCalibrationData(std::move(m_calibration_data)); |
| 300 | } |
| 301 | |
| 302 | Common::DVec2 CalibrationBuilder::GetCenter() const |
| 303 | { |
| 304 | return m_center.value_or(Common::DVec2{}); |
| 305 | } |
| 306 | |
| 307 | } // namespace ciface::MappingCommon |