| 1 | // Copyright 2020 Dolphin Emulator Project |
| 2 | // SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | |
| 4 | #include "InputCommon/ControllerInterface/Wiimote/WiimoteController.h" |
| 5 | |
| 6 | #include "Common/BitUtils.h" |
| 7 | #include "Common/Logging/Log.h" |
| 8 | #include "Common/MathUtil.h" |
| 9 | #include "Core/Config/SYSCONFSettings.h" |
| 10 | #include "Core/HW/WiimoteEmu/ExtensionPort.h" |
| 11 | #include "Core/HW/WiimoteEmu/WiimoteEmu.h" |
| 12 | #include "InputCommon/ControllerEmu/ControllerEmu.h" |
| 13 | #include "InputCommon/ControllerInterface/ControllerInterface.h" |
| 14 | |
| 15 | namespace ciface::WiimoteController |
| 16 | { |
| 17 | static constexpr char SOURCE_NAME[] = "Bluetooth"; |
| 18 | |
| 19 | static constexpr size_t IR_SENSITIVITY_LEVEL_COUNT = 5; |
| 20 | |
| 21 | template <typename T> |
| 22 | class Button final : public Core::Device::Input |
| 23 | { |
| 24 | public: |
| 25 | Button(const T* value, std::common_type_t<T> mask, std::string name) |
| 26 | : m_value(*value), m_mask(mask), m_name(std::move(name)) |
| 27 | { |
| 28 | } |
| 29 | |
| 30 | std::string GetName() const override { return m_name; } |
| 31 | |
| 32 | ControlState GetState() const override { return (m_value & m_mask) != 0; } |
| 33 | |
| 34 | private: |
| 35 | const T& m_value; |
| 36 | const T m_mask; |
| 37 | const std::string m_name; |
| 38 | }; |
| 39 | |
| 40 | // GetState returns value divided by supplied "extent". |
| 41 | template <typename T, bool Detectable> |
| 42 | class GenericInput : public Core::Device::Input |
| 43 | { |
| 44 | public: |
| 45 | GenericInput(const T* value, std::string name, ControlState extent) |
| 46 | : m_value(*value), m_name(std::move(name)), m_extent(extent) |
| 47 | { |
| 48 | } |
| 49 | |
| 50 | bool IsDetectable() const override { return Detectable; } |
| 51 | |
| 52 | std::string GetName() const override { return m_name; } |
| 53 | |
| 54 | ControlState GetState() const final { return ControlState(m_value) / m_extent; } |
| 55 | |
| 56 | protected: |
| 57 | const T& m_value; |
| 58 | const std::string m_name; |
| 59 | const ControlState m_extent; |
| 60 | }; |
| 61 | |
| 62 | template <typename T> |
| 63 | using AnalogInput = GenericInput<T, true>; |
| 64 | |
| 65 | template <typename T> |
| 66 | using UndetectableAnalogInput = GenericInput<T, false>; |
| 67 | |
| 68 | // GetName() is appended with '-' or '+' based on sign of "extent" value. |
| 69 | template <bool Detectable> |
| 70 | class SignedInput final : public GenericInput<float, Detectable> |
| 71 | { |
| 72 | public: |
| 73 | using GenericInput<float, Detectable>::GenericInput; |
| 74 | |
| 75 | std::string GetName() const override { return this->m_name + (this->m_extent < 0 ? '-' : '+'); } |
| 76 | }; |
| 77 | |
| 78 | using SignedAnalogInput = SignedInput<true>; |
| 79 | using UndetectableSignedAnalogInput = SignedInput<false>; |
| 80 | |
| 81 | class Motor final : public Core::Device::Output |
| 82 | { |
| 83 | public: |
| 84 | Motor(std::atomic<ControlState>* value) : m_value(*value) {} |
| 85 | |
| 86 | std::string GetName() const override { return "Motor"; } |
| 87 | |
| 88 | void SetState(ControlState state) override { m_value = state; } |
| 89 | |
| 90 | private: |
| 91 | std::atomic<ControlState>& m_value; |
| 92 | }; |
| 93 | |
| 94 | template <typename T> |
| 95 | void Device::QueueReport(T&& report, std::function<void(ErrorCode)> ack_callback) |
| 96 | { |
| 97 | // Maintain proper rumble state. |
| 98 | report.rumble = m_rumble; |
| 99 | |
| 100 | m_wiimote->QueueReport(report.REPORT_ID, &report, sizeof(report)); |
| 101 | |
| 102 | if (ack_callback) |
| 103 | AddReportHandler(MakeAckHandler(report.REPORT_ID, std::move(ack_callback))); |
| 104 | } |
| 105 | |
| 106 | void AddDevice(std::unique_ptr<WiimoteReal::Wiimote> wiimote) |
| 107 | { |
| 108 | // Our real wiimote class requires an index. |
| 109 | // Within the pool it's only going to be used for logging purposes. |
| 110 | static constexpr int CIFACE_WIIMOTE_INDEX = 55; |
| 111 | |
| 112 | if (!wiimote->Connect(CIFACE_WIIMOTE_INDEX)) |
| 113 | { |
| 114 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Failed to connect."); |
| 115 | return; |
| 116 | } |
| 117 | |
| 118 | wiimote->Prepare(); |
| 119 | wiimote->EventLinked(); |
| 120 | |
| 121 | g_controller_interface.AddDevice(std::make_shared<Device>(std::move(wiimote))); |
| 122 | } |
| 123 | |
| 124 | void ReleaseDevices(std::optional<u32> count) |
| 125 | { |
| 126 | u32 removed_devices = 0; |
| 127 | |
| 128 | // Remove up to "count" remotes (or all of them if nullopt). |
| 129 | // Real wiimotes will be added to the pool. |
| 130 | // Make sure to force the device removal immediately (as they are shared ptrs and |
| 131 | // they could be kept alive, preventing us from re-creating the device) |
| 132 | g_controller_interface.RemoveDevice( |
| 133 | [&](const Core::Device* device) { |
| 134 | if (device->GetSource() != SOURCE_NAME || count == removed_devices) |
| 135 | return false; |
| 136 | |
| 137 | ++removed_devices; |
| 138 | return true; |
| 139 | }, |
| 140 | true); |
| 141 | } |
| 142 | |
| 143 | Device::Device(std::unique_ptr<WiimoteReal::Wiimote> wiimote) : m_wiimote(std::move(wiimote)) |
| 144 | { |
| 145 | using EmuWiimote = WiimoteEmu::Wiimote; |
| 146 | |
| 147 | // Buttons. |
| 148 | static constexpr std::pair<u16, const char*> button_masks[] = { |
| 149 | {EmuWiimote::BUTTON_A, "A"}, {EmuWiimote::BUTTON_B, "B"}, |
| 150 | {EmuWiimote::BUTTON_ONE, "1"}, {EmuWiimote::BUTTON_TWO, "2"}, |
| 151 | {EmuWiimote::BUTTON_MINUS, "-"}, {EmuWiimote::BUTTON_PLUS, "+"}, |
| 152 | {EmuWiimote::BUTTON_HOME, "HOME"}, |
| 153 | }; |
| 154 | |
| 155 | for (auto& button : button_masks) |
| 156 | AddInput(new Button<u16>(&m_core_data.hex, button.first, button.second)); |
| 157 | |
| 158 | static constexpr u16 dpad_masks[] = { |
| 159 | EmuWiimote::PAD_UP, |
| 160 | EmuWiimote::PAD_DOWN, |
| 161 | EmuWiimote::PAD_LEFT, |
| 162 | EmuWiimote::PAD_RIGHT, |
| 163 | }; |
| 164 | |
| 165 | // Friendly orientation inputs. |
| 166 | static constexpr const char* const rotation_names[] = {"Pitch", "Roll", "Yaw"}; |
| 167 | for (std::size_t i = 0; i != std::size(rotation_names); ++i) |
| 168 | { |
| 169 | AddInput( |
| 170 | new UndetectableSignedAnalogInput(&m_rotation_inputs.data[i], rotation_names[i], -1.f)); |
| 171 | AddInput(new UndetectableSignedAnalogInput(&m_rotation_inputs.data[i], rotation_names[i], 1.f)); |
| 172 | } |
| 173 | |
| 174 | // Raw accelerometer. |
| 175 | for (std::size_t i = 0; i != std::size(dpad_masks); ++i) |
| 176 | AddInput(new Button<u16>(&m_core_data.hex, dpad_masks[i], named_directions[i])); |
| 177 | |
| 178 | static constexpr std::array<std::array<const char*, 2>, 3> accel_names = {{ |
| 179 | {"Accel Left", "Accel Right"}, |
| 180 | {"Accel Backward", "Accel Forward"}, |
| 181 | {"Accel Up", "Accel Down"}, |
| 182 | }}; |
| 183 | |
| 184 | for (std::size_t i = 0; i != m_accel_data.data.size(); ++i) |
| 185 | { |
| 186 | AddInput(new UndetectableAnalogInput<float>(&m_accel_data.data[i], accel_names[i][0], 1)); |
| 187 | AddInput(new UndetectableAnalogInput<float>(&m_accel_data.data[i], accel_names[i][1], -1)); |
| 188 | } |
| 189 | |
| 190 | // IR data. |
| 191 | static constexpr const char* const ir_names[] = {"IR Center X", "IR Center Y"}; |
| 192 | for (std::size_t i = 0; i != std::size(ir_names); ++i) |
| 193 | { |
| 194 | AddInput( |
| 195 | new UndetectableSignedAnalogInput(&m_ir_state.center_position.data[i], ir_names[i], -1.f)); |
| 196 | AddInput( |
| 197 | new UndetectableSignedAnalogInput(&m_ir_state.center_position.data[i], ir_names[i], 1.f)); |
| 198 | } |
| 199 | |
| 200 | AddInput(new UndetectableAnalogInput<bool>(&m_ir_state.is_hidden, "IR Hidden", 1)); |
| 201 | |
| 202 | AddInput(new UndetectableAnalogInput<float>(&m_ir_state.distance, "IR Distance", 1)); |
| 203 | |
| 204 | // Raw IR Objects. |
| 205 | for (std::size_t i = 0; i < 4; ++i) |
| 206 | { |
| 207 | AddInput(new UndetectableAnalogInput<float>(&m_ir_state.raw_ir_object_position[i].x, |
| 208 | fmt::format("IR Object {} X", i + 1), 1)); |
| 209 | AddInput(new UndetectableAnalogInput<float>(&m_ir_state.raw_ir_object_position[i].y, |
| 210 | fmt::format("IR Object {} Y", i + 1), 1)); |
| 211 | AddInput(new UndetectableAnalogInput<float>(&m_ir_state.raw_ir_object_size[i], |
| 212 | fmt::format("IR Object {} Size", i + 1), 1)); |
| 213 | } |
| 214 | |
| 215 | // Raw gyroscope. |
| 216 | static constexpr std::array<std::array<const char*, 2>, 3> gyro_names = {{ |
| 217 | {"Gyro Pitch Down", "Gyro Pitch Up"}, |
| 218 | {"Gyro Roll Left", "Gyro Roll Right"}, |
| 219 | {"Gyro Yaw Left", "Gyro Yaw Right"}, |
| 220 | }}; |
| 221 | |
| 222 | for (std::size_t i = 0; i != m_accel_data.data.size(); ++i) |
| 223 | { |
| 224 | AddInput( |
| 225 | new UndetectableAnalogInput<float>(&m_mplus_state.gyro_data.data[i], gyro_names[i][0], 1)); |
| 226 | AddInput( |
| 227 | new UndetectableAnalogInput<float>(&m_mplus_state.gyro_data.data[i], gyro_names[i][1], -1)); |
| 228 | } |
| 229 | |
| 230 | using WiimoteEmu::Nunchuk; |
| 231 | const std::string nunchuk_prefix = "Nunchuk "; |
| 232 | |
| 233 | // Buttons. |
| 234 | AddInput(new Button<u8>(&m_nunchuk_state.buttons, Nunchuk::BUTTON_C, nunchuk_prefix + "C")); |
| 235 | AddInput(new Button<u8>(&m_nunchuk_state.buttons, Nunchuk::BUTTON_Z, nunchuk_prefix + "Z")); |
| 236 | |
| 237 | // Stick. |
| 238 | static constexpr const char* const nunchuk_stick_names[] = {"X", "Y"}; |
| 239 | for (std::size_t i = 0; i != std::size(nunchuk_stick_names); ++i) |
| 240 | { |
| 241 | AddInput(new SignedAnalogInput(&m_nunchuk_state.stick.data[i], |
| 242 | nunchuk_prefix + nunchuk_stick_names[i], -1.f)); |
| 243 | AddInput(new SignedAnalogInput(&m_nunchuk_state.stick.data[i], |
| 244 | nunchuk_prefix + nunchuk_stick_names[i], 1.f)); |
| 245 | } |
| 246 | |
| 247 | // Raw accelerometer. |
| 248 | for (std::size_t i = 0; i != m_accel_data.data.size(); ++i) |
| 249 | { |
| 250 | AddInput(new UndetectableAnalogInput<float>(&m_nunchuk_state.accel.data[i], |
| 251 | nunchuk_prefix + accel_names[i][0], 1)); |
| 252 | AddInput(new UndetectableAnalogInput<float>(&m_nunchuk_state.accel.data[i], |
| 253 | nunchuk_prefix + accel_names[i][1], -1)); |
| 254 | } |
| 255 | |
| 256 | using WiimoteEmu::Classic; |
| 257 | const std::string classic_prefix = "Classic "; |
| 258 | |
| 259 | // Buttons. |
| 260 | static constexpr u16 classic_dpad_masks[] = { |
| 261 | Classic::PAD_UP, |
| 262 | Classic::PAD_DOWN, |
| 263 | Classic::PAD_LEFT, |
| 264 | Classic::PAD_RIGHT, |
| 265 | }; |
| 266 | |
| 267 | for (std::size_t i = 0; i != std::size(classic_dpad_masks); ++i) |
| 268 | AddInput(new Button<u16>(&m_classic_state.buttons, classic_dpad_masks[i], |
| 269 | classic_prefix + named_directions[i])); |
| 270 | |
| 271 | static constexpr u16 classic_button_masks[] = { |
| 272 | Classic::BUTTON_A, Classic::BUTTON_B, Classic::BUTTON_X, Classic::BUTTON_Y, |
| 273 | Classic::TRIGGER_L, Classic::TRIGGER_R, Classic::BUTTON_ZL, Classic::BUTTON_ZR, |
| 274 | Classic::BUTTON_MINUS, Classic::BUTTON_PLUS, Classic::BUTTON_HOME, |
| 275 | }; |
| 276 | |
| 277 | static constexpr const char* const classic_button_names[] = { |
| 278 | "A", "B", "X", "Y", "L", "R", "ZL", "ZR", "-", "+", "HOME", |
| 279 | }; |
| 280 | |
| 281 | for (std::size_t i = 0; i != std::size(classic_button_masks); ++i) |
| 282 | AddInput(new Button<u16>(&m_classic_state.buttons, classic_button_masks[i], |
| 283 | classic_prefix + classic_button_names[i])); |
| 284 | |
| 285 | // Sticks. |
| 286 | static constexpr const char* const classic_stick_names[][2] = {{"Left X", "Left Y"}, |
| 287 | {"Right X", "Right Y"}}; |
| 288 | |
| 289 | for (std::size_t s = 0; s != std::size(m_classic_state.sticks); ++s) |
| 290 | { |
| 291 | for (std::size_t i = 0; i != std::size(m_classic_state.sticks[0].data); ++i) |
| 292 | { |
| 293 | AddInput(new SignedAnalogInput(&m_classic_state.sticks[s].data[i], |
| 294 | classic_prefix + classic_stick_names[s][i], -1.f)); |
| 295 | AddInput(new SignedAnalogInput(&m_classic_state.sticks[s].data[i], |
| 296 | classic_prefix + classic_stick_names[s][i], 1.f)); |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | // Triggers. |
| 301 | AddInput(new AnalogInput<float>(&m_classic_state.triggers[0], classic_prefix + "L-Analog", 1.f)); |
| 302 | AddInput(new AnalogInput<float>(&m_classic_state.triggers[1], classic_prefix + "R-Analog", 1.f)); |
| 303 | |
| 304 | // Specialty inputs: |
| 305 | AddInput(new UndetectableAnalogInput<float>(&m_battery, "Battery", 1.f)); |
| 306 | AddInput(new UndetectableAnalogInput<WiimoteEmu::ExtensionNumber>( |
| 307 | &m_extension_number_input, "Attached Extension", WiimoteEmu::ExtensionNumber(1))); |
| 308 | AddInput(new UndetectableAnalogInput<bool>(&m_mplus_attached_input, "Attached MotionPlus", 1)); |
| 309 | |
| 310 | AddOutput(new Motor(&m_rumble_level)); |
| 311 | } |
| 312 | |
| 313 | Device::~Device() |
| 314 | { |
| 315 | if (!m_wiimote->IsConnected()) |
| 316 | return; |
| 317 | |
| 318 | m_wiimote->EmuStop(); |
| 319 | |
| 320 | INFO_LOG_FMT(WIIMOTE, "WiiRemote: Returning remote to pool."); |
| 321 | WiimoteReal::AddWiimoteToPool(std::move(m_wiimote)); |
| 322 | } |
| 323 | |
| 324 | std::string Device::GetName() const |
| 325 | { |
| 326 | return "Wii Remote"; |
| 327 | } |
| 328 | |
| 329 | std::string Device::GetSource() const |
| 330 | { |
| 331 | return SOURCE_NAME; |
| 332 | } |
| 333 | |
| 334 | // Always add these at the end, given their hotplug nature |
| 335 | int Device::GetSortPriority() const |
| 336 | { |
| 337 | return -4; |
| 338 | } |
| 339 | |
| 340 | void Device::RunTasks() |
| 341 | { |
| 342 | if (IsPerformingTask()) |
| 343 | return; |
| 344 | |
| 345 | // Request status. |
| 346 | if (Clock::now() >= m_status_outdated_time) |
| 347 | { |
| 348 | QueueReport(OutputReportRequestStatus()); |
| 349 | |
| 350 | AddReportHandler(std::function<void(const InputReportStatus& status)>( |
| 351 | [this](const InputReportStatus& status) { |
| 352 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Received requested status."); |
| 353 | ProcessStatusReport(status); |
| 354 | })); |
| 355 | |
| 356 | return; |
| 357 | } |
| 358 | |
| 359 | // Set LEDs. |
| 360 | const auto desired_leds = GetDesiredLEDValue(); |
| 361 | if (m_leds != desired_leds) |
| 362 | { |
| 363 | OutputReportLeds rpt = {}; |
| 364 | rpt.ack = 1; |
| 365 | rpt.leds = desired_leds; |
| 366 | QueueReport(rpt, [this, desired_leds](ErrorCode result) { |
| 367 | if (result != ErrorCode::Success) |
| 368 | { |
| 369 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Failed to set LEDs."); |
| 370 | return; |
| 371 | } |
| 372 | |
| 373 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Set LEDs."); |
| 374 | |
| 375 | m_leds = desired_leds; |
| 376 | }); |
| 377 | |
| 378 | return; |
| 379 | } |
| 380 | |
| 381 | // Set reporting mode to one that supports every component. |
| 382 | static constexpr auto desired_reporting_mode = InputReportID::ReportCoreAccelIR10Ext6; |
| 383 | if (m_reporting_mode != desired_reporting_mode) |
| 384 | { |
| 385 | OutputReportMode mode = {}; |
| 386 | mode.ack = 1; |
| 387 | mode.mode = desired_reporting_mode; |
| 388 | QueueReport(mode, [this](ErrorCode error) { |
| 389 | if (error != ErrorCode::Success) |
| 390 | { |
| 391 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Failed to set reporting mode."); |
| 392 | return; |
| 393 | } |
| 394 | |
| 395 | m_reporting_mode = desired_reporting_mode; |
| 396 | |
| 397 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Set reporting mode."); |
| 398 | }); |
| 399 | |
| 400 | return; |
| 401 | } |
| 402 | |
| 403 | // Read accelerometer calibration. |
| 404 | if (!m_accel_calibration.has_value()) |
| 405 | { |
| 406 | static constexpr u16 ACCEL_CALIBRATION_ADDR = 0x16; |
| 407 | |
| 408 | ReadData(AddressSpace::EEPROM, 0, ACCEL_CALIBRATION_ADDR, sizeof(AccelCalibrationData), |
| 409 | [this](ReadResponse response) { |
| 410 | if (!response) |
| 411 | { |
| 412 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Failed to read accelerometer calibration."); |
| 413 | return; |
| 414 | } |
| 415 | |
| 416 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Read accelerometer calibration."); |
| 417 | |
| 418 | auto& calibration_data = *response; |
| 419 | |
| 420 | const AccelCalibrationData accel_calibration = |
| 421 | Common::BitCastPtr<AccelCalibrationData>(calibration_data.data()); |
| 422 | m_accel_calibration = accel_calibration.GetCalibration(); |
| 423 | |
| 424 | WiimoteEmu::UpdateCalibrationDataChecksum(calibration_data, 1); |
| 425 | |
| 426 | // We could potentially try the second block at 0x26 if the checksum is bad. |
| 427 | if (accel_calibration.checksum != calibration_data.back()) |
| 428 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Bad accelerometer calibration checksum."); |
| 429 | }); |
| 430 | |
| 431 | return; |
| 432 | } |
| 433 | |
| 434 | if (!m_ir_state.IsFullyConfigured()) |
| 435 | { |
| 436 | ConfigureIRCamera(); |
| 437 | |
| 438 | return; |
| 439 | } |
| 440 | |
| 441 | if (!m_speaker_configured) |
| 442 | { |
| 443 | ConfigureSpeaker(); |
| 444 | |
| 445 | return; |
| 446 | } |
| 447 | |
| 448 | // Perform the following tasks only after M+ is settled. |
| 449 | if (IsWaitingForMotionPlus()) |
| 450 | return; |
| 451 | |
| 452 | // Read the "active" extension ID. (This also gives us the current M+ mode) |
| 453 | // This will fail on an un-intialized other extension. |
| 454 | // But extension initialization is the same as M+ de-activation so we must try this first. |
| 455 | if (m_extension_port == true && |
| 456 | (!IsMotionPlusStateKnown() || (!IsMotionPlusActive() && !m_extension_id.has_value()))) |
| 457 | { |
| 458 | static constexpr u16 ENCRYPTION_ADDR = 0xfb; |
| 459 | static constexpr u8 ENCRYPTION_VALUE = 0x00; |
| 460 | |
| 461 | // First disable encryption. Note this is a no-op when performed on the M+. |
| 462 | WriteData(AddressSpace::I2CBus, WiimoteEmu::ExtensionPort::REPORT_I2C_SLAVE, ENCRYPTION_ADDR, |
| 463 | {ENCRYPTION_VALUE}, [this](ErrorCode error) { |
| 464 | if (error != ErrorCode::Success) |
| 465 | return; |
| 466 | |
| 467 | ReadActiveExtensionID(); |
| 468 | }); |
| 469 | |
| 470 | return; |
| 471 | } |
| 472 | |
| 473 | static constexpr u16 INIT_ADDR = 0xf0; |
| 474 | static constexpr u8 INIT_VALUE = 0x55; |
| 475 | |
| 476 | // Initialize "active" extension if ID was not recognized. |
| 477 | // Note this is done before M+ setup to determine the required passthrough mode. |
| 478 | if (m_extension_id == ExtensionID::Unsupported) |
| 479 | { |
| 480 | // Note that this signal also DE-activates a M+. |
| 481 | WriteData(AddressSpace::I2CBus, WiimoteEmu::ExtensionPort::REPORT_I2C_SLAVE, INIT_ADDR, |
| 482 | {INIT_VALUE}, [this](ErrorCode result) { |
| 483 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Initialized extension: {}.", int(result)); |
| 484 | m_extension_id = std::nullopt; |
| 485 | }); |
| 486 | |
| 487 | return; |
| 488 | } |
| 489 | |
| 490 | // The following tasks require a known M+ state. |
| 491 | if (!IsMotionPlusStateKnown()) |
| 492 | return; |
| 493 | |
| 494 | // We now know the status of the M+. |
| 495 | // Updating it too frequently results off/on flashes on mode change. |
| 496 | m_mplus_attached_input = IsMotionPlusActive(); |
| 497 | |
| 498 | // Extension removal status is known here. Attachment status is updated after the ID is read. |
| 499 | if (m_extension_port != true) |
| 500 | m_extension_number_input = WiimoteEmu::ExtensionNumber::NONE; |
| 501 | |
| 502 | // Periodically try to initialize and activate an inactive M+. |
| 503 | if (!IsMotionPlusActive() && m_mplus_desired_mode.has_value() && |
| 504 | m_mplus_state.current_mode != m_mplus_desired_mode) |
| 505 | { |
| 506 | static constexpr u16 MPLUS_POLL_ADDR = WiimoteEmu::MotionPlus::PASSTHROUGH_MODE_OFFSET; |
| 507 | ReadData(AddressSpace::I2CBus, WiimoteEmu::MotionPlus::INACTIVE_DEVICE_ADDR, MPLUS_POLL_ADDR, 1, |
| 508 | [this](const ReadResponse& response) { |
| 509 | if (!response) |
| 510 | { |
| 511 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: M+ poll failed."); |
| 512 | HandleMotionPlusNonResponse(); |
| 513 | return; |
| 514 | } |
| 515 | |
| 516 | WriteData(AddressSpace::I2CBus, WiimoteEmu::MotionPlus::INACTIVE_DEVICE_ADDR, |
| 517 | INIT_ADDR, {INIT_VALUE}, [this](ErrorCode result) { |
| 518 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: M+ initialization: {}.", int(result)); |
| 519 | if (result != ErrorCode::Success) |
| 520 | { |
| 521 | HandleMotionPlusNonResponse(); |
| 522 | return; |
| 523 | } |
| 524 | |
| 525 | TriggerMotionPlusModeChange(); |
| 526 | }); |
| 527 | }); |
| 528 | |
| 529 | return; |
| 530 | } |
| 531 | |
| 532 | // Change active M+ passthrough mode. |
| 533 | if (IsMotionPlusActive() && m_mplus_desired_mode.has_value() && |
| 534 | m_mplus_state.current_mode != m_mplus_desired_mode) |
| 535 | { |
| 536 | TriggerMotionPlusModeChange(); |
| 537 | |
| 538 | return; |
| 539 | } |
| 540 | |
| 541 | // Read passthrough extension ID. |
| 542 | // This will also give us a desired M+ passthrough mode. |
| 543 | if (IsMotionPlusActive() && m_mplus_state.passthrough_port == true && !m_extension_id.has_value()) |
| 544 | { |
| 545 | // The M+ reads the passthrough ext ID and stores it at 0xf6,f8,f9. |
| 546 | static constexpr u16 PASSTHROUGH_EXT_ID_ADDR = 0xf6; |
| 547 | |
| 548 | ReadData(AddressSpace::I2CBus, WiimoteEmu::MotionPlus::ACTIVE_DEVICE_ADDR, |
| 549 | PASSTHROUGH_EXT_ID_ADDR, 4, [this](ReadResponse response) { |
| 550 | if (!response) |
| 551 | return; |
| 552 | |
| 553 | // Port status may have changed since the read was sent. |
| 554 | // In which case this data read would succeed but be useless. |
| 555 | if (m_mplus_state.passthrough_port != true) |
| 556 | return; |
| 557 | |
| 558 | auto& identifier = *response; |
| 559 | |
| 560 | ProcessExtensionID(identifier[2], identifier[0], identifier[3]); |
| 561 | }); |
| 562 | |
| 563 | return; |
| 564 | } |
| 565 | |
| 566 | // The following tasks require M+ configuration to be done. |
| 567 | if (!IsMotionPlusInDesiredMode()) |
| 568 | return; |
| 569 | |
| 570 | // Now that M+ config has settled we can update the extension number. |
| 571 | // Updating it too frequently results off/on flashes on M+ mode change. |
| 572 | UpdateExtensionNumberInput(); |
| 573 | |
| 574 | static constexpr u16 NORMAL_CALIBRATION_ADDR = 0x20; |
| 575 | |
| 576 | // Read M+ calibration. |
| 577 | if (IsMotionPlusActive() && !m_mplus_state.calibration.has_value()) |
| 578 | { |
| 579 | ReadData(AddressSpace::I2CBus, WiimoteEmu::MotionPlus::ACTIVE_DEVICE_ADDR, |
| 580 | NORMAL_CALIBRATION_ADDR, sizeof(WiimoteEmu::MotionPlus::CalibrationData), |
| 581 | [this](ReadResponse response) { |
| 582 | if (!response) |
| 583 | return; |
| 584 | |
| 585 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Read M+ calibration."); |
| 586 | |
| 587 | WiimoteEmu::MotionPlus::CalibrationData calibration = |
| 588 | Common::BitCastPtr<WiimoteEmu::MotionPlus::CalibrationData>(response->data()); |
| 589 | |
| 590 | const auto read_checksum = std::pair(calibration.crc32_lsb, calibration.crc32_msb); |
| 591 | |
| 592 | calibration.UpdateChecksum(); |
| 593 | |
| 594 | m_mplus_state.SetCalibrationData(calibration); |
| 595 | |
| 596 | if (read_checksum != std::pair(calibration.crc32_lsb, calibration.crc32_msb)) |
| 597 | { |
| 598 | // We could potentially try another read or call the M+ unusable. |
| 599 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Bad M+ calibration checksum."); |
| 600 | } |
| 601 | }); |
| 602 | |
| 603 | return; |
| 604 | } |
| 605 | |
| 606 | // Read normal extension calibration. |
| 607 | if ((m_extension_id == ExtensionID::Nunchuk && !m_nunchuk_state.calibration) || |
| 608 | (m_extension_id == ExtensionID::Classic && !m_classic_state.calibration)) |
| 609 | { |
| 610 | // Extension calibration is normally at 0x20 but M+ reads and stores it at 0x40. |
| 611 | static constexpr u16 PASSTHROUGH_CALIBRATION_ADDR = 0x40; |
| 612 | |
| 613 | const u16 calibration_addr = |
| 614 | IsMotionPlusActive() ? PASSTHROUGH_CALIBRATION_ADDR : NORMAL_CALIBRATION_ADDR; |
| 615 | static constexpr u16 CALIBRATION_SIZE = 0x10; |
| 616 | |
| 617 | ReadData( |
| 618 | AddressSpace::I2CBus, WiimoteEmu::ExtensionPort::REPORT_I2C_SLAVE, calibration_addr, |
| 619 | CALIBRATION_SIZE, [this](ReadResponse response) { |
| 620 | if (!response) |
| 621 | return; |
| 622 | |
| 623 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Read extension calibration."); |
| 624 | |
| 625 | auto& calibration_data = *response; |
| 626 | |
| 627 | const auto read_checksum = std::pair(calibration_data[CALIBRATION_SIZE - 2], |
| 628 | calibration_data[CALIBRATION_SIZE - 1]); |
| 629 | |
| 630 | WiimoteEmu::UpdateCalibrationDataChecksum(calibration_data, 2); |
| 631 | |
| 632 | Checksum checksum = Checksum::Good; |
| 633 | |
| 634 | if (read_checksum != std::pair(calibration_data[CALIBRATION_SIZE - 2], |
| 635 | calibration_data[CALIBRATION_SIZE - 1])) |
| 636 | { |
| 637 | // We could potentially try another block or call the extension unusable. |
| 638 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Bad extension calibration checksum."); |
| 639 | checksum = Checksum::Bad; |
| 640 | } |
| 641 | |
| 642 | if (m_extension_id == ExtensionID::Nunchuk) |
| 643 | { |
| 644 | m_nunchuk_state.SetCalibrationData( |
| 645 | Common::BitCastPtr<WiimoteEmu::Nunchuk::CalibrationData>(calibration_data.data()), |
| 646 | checksum); |
| 647 | } |
| 648 | else if (m_extension_id == ExtensionID::Classic) |
| 649 | { |
| 650 | m_classic_state.SetCalibrationData( |
| 651 | Common::BitCastPtr<WiimoteEmu::Classic::CalibrationData>(calibration_data.data()), |
| 652 | checksum); |
| 653 | } |
| 654 | }); |
| 655 | |
| 656 | return; |
| 657 | } |
| 658 | } |
| 659 | |
| 660 | void Device::HandleMotionPlusNonResponse() |
| 661 | { |
| 662 | // No need for additional checks if an extension is attached. |
| 663 | // (not possible for M+ to become attached) |
| 664 | if (m_extension_port == true) |
| 665 | m_mplus_desired_mode = MotionPlusState::PassthroughMode{}; |
| 666 | else |
| 667 | WaitForMotionPlus(); |
| 668 | } |
| 669 | |
| 670 | // Produce LED bitmask for remotes. |
| 671 | // Remotes 1-4 are normal. Additional remotes LED labels will add up to their assigned ID. |
| 672 | u8 Device::GetDesiredLEDValue() const |
| 673 | { |
| 674 | const auto index = GetId(); |
| 675 | |
| 676 | // Normal LED behavior for remotes 1-4. |
| 677 | if (index < 4) |
| 678 | return 1 << index; |
| 679 | |
| 680 | // Light LED 4 and LEDs 1 through 3 for remotes 5-7. (Add up the numbers on the remote) |
| 681 | if (index < 7) |
| 682 | return 1 << (index - 4) | 8; |
| 683 | |
| 684 | // Light LED 4+3 and LEDs 1 or 2 for remotes 8 or 9. (Add up the numbers on the remote) |
| 685 | if (index < 9) |
| 686 | return 1 << (index - 7) | 8 | 4; |
| 687 | |
| 688 | // For remotes 10 and up just light all LEDs. |
| 689 | return 0xf; |
| 690 | } |
| 691 | |
| 692 | void Device::UpdateExtensionNumberInput() |
| 693 | { |
| 694 | switch (m_extension_id.value_or(ExtensionID::Unsupported)) |
| 695 | { |
| 696 | case ExtensionID::Nunchuk: |
| 697 | m_extension_number_input = WiimoteEmu::ExtensionNumber::NUNCHUK; |
| 698 | break; |
| 699 | case ExtensionID::Classic: |
| 700 | m_extension_number_input = WiimoteEmu::ExtensionNumber::CLASSIC; |
| 701 | break; |
| 702 | case ExtensionID::Unsupported: |
| 703 | default: |
| 704 | m_extension_number_input = WiimoteEmu::ExtensionNumber::NONE; |
| 705 | break; |
| 706 | } |
| 707 | } |
| 708 | |
| 709 | void Device::ProcessExtensionEvent(bool connected) |
| 710 | { |
| 711 | // Reset extension state. |
| 712 | m_nunchuk_state = {}; |
| 713 | m_classic_state = {}; |
| 714 | |
| 715 | m_extension_id = std::nullopt; |
| 716 | |
| 717 | // We won't know the desired mode until we get the extension ID. |
| 718 | if (connected) |
| 719 | m_mplus_desired_mode = std::nullopt; |
| 720 | } |
| 721 | |
| 722 | void Device::ProcessExtensionID(u8 id_0, u8 id_4, u8 id_5) |
| 723 | { |
| 724 | if (id_4 == 0x00 && id_5 == 0x00) |
| 725 | { |
| 726 | INFO_LOG_FMT(WIIMOTE, "WiiRemote: Nunchuk is attached."); |
| 727 | m_extension_id = ExtensionID::Nunchuk; |
| 728 | |
| 729 | m_mplus_desired_mode = MotionPlusState::PassthroughMode::Nunchuk; |
| 730 | } |
| 731 | else if (id_4 == 0x01 && id_5 == 0x01) |
| 732 | { |
| 733 | INFO_LOG_FMT(WIIMOTE, "WiiRemote: Classic Controller is attached."); |
| 734 | m_extension_id = ExtensionID::Classic; |
| 735 | |
| 736 | m_mplus_desired_mode = MotionPlusState::PassthroughMode::Classic; |
| 737 | } |
| 738 | else |
| 739 | { |
| 740 | // This is a normal occurrence before extension initialization. |
| 741 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Unknown extension: {} {} {}.", id_0, id_4, id_5); |
| 742 | m_extension_id = ExtensionID::Unsupported; |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | void Device::MotionPlusState::SetCalibrationData( |
| 747 | const WiimoteEmu::MotionPlus::CalibrationData& data) |
| 748 | { |
| 749 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Set M+ calibration."); |
| 750 | |
| 751 | calibration.emplace(); |
| 752 | |
| 753 | calibration->fast = data.fast; |
| 754 | calibration->slow = data.slow; |
| 755 | } |
| 756 | |
| 757 | Device::NunchukState::Calibration::Calibration() : accel{}, stick{} |
| 758 | { |
| 759 | accel.zero.data.fill(1 << (accel.BITS_OF_PRECISION - 1)); |
| 760 | // Approximate 1G value per WiiBrew: |
| 761 | accel.max.data.fill(740); |
| 762 | |
| 763 | stick.zero.data.fill(1 << (stick.BITS_OF_PRECISION - 1)); |
| 764 | stick.max.data.fill((1 << stick.BITS_OF_PRECISION) - 1); |
| 765 | } |
| 766 | |
| 767 | void Device::NunchukState::SetCalibrationData(const WiimoteEmu::Nunchuk::CalibrationData& data, |
| 768 | Checksum checksum) |
| 769 | { |
| 770 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Set Nunchuk calibration."); |
| 771 | |
| 772 | calibration.emplace(); |
| 773 | |
| 774 | if (checksum == Checksum::Bad) |
| 775 | return; |
| 776 | |
| 777 | // Genuine Nunchuks have been observed with "min" and "max" values of zero. |
| 778 | // We catch that here and fall back to "full range" calibration. |
| 779 | const auto stick_calibration = data.GetStick(); |
| 780 | if (stick_calibration.IsSane()) |
| 781 | { |
| 782 | calibration->stick = stick_calibration; |
| 783 | } |
| 784 | else |
| 785 | { |
| 786 | WARN_LOG_FMT(WIIMOTE, |
| 787 | "WiiRemote: Nunchuk stick calibration is not sane. Using fallback values."); |
| 788 | } |
| 789 | |
| 790 | // No known reports of bad accelerometer calibration but we'll handle it just in case. |
| 791 | const auto accel_calibration = data.GetAccel(); |
| 792 | if (accel_calibration.IsSane()) |
| 793 | { |
| 794 | calibration->accel = accel_calibration; |
| 795 | } |
| 796 | else |
| 797 | { |
| 798 | WARN_LOG_FMT(WIIMOTE, |
| 799 | "WiiRemote: Nunchuk accel calibration is not sane. Using fallback values."); |
| 800 | } |
| 801 | } |
| 802 | |
| 803 | Device::ClassicState::Calibration::Calibration() |
| 804 | : left_stick{}, right_stick{}, left_trigger{}, right_trigger{} |
| 805 | { |
| 806 | left_stick.zero.data.fill(1 << (left_stick.BITS_OF_PRECISION - 1)); |
| 807 | left_stick.max.data.fill((1 << left_stick.BITS_OF_PRECISION) - 1); |
| 808 | |
| 809 | right_stick.zero.data.fill(1 << (right_stick.BITS_OF_PRECISION - 1)); |
| 810 | right_stick.max.data.fill((1 << right_stick.BITS_OF_PRECISION) - 1); |
| 811 | |
| 812 | left_trigger.max = (1 << left_trigger.BITS_OF_PRECISION) - 1; |
| 813 | right_trigger.max = (1 << right_trigger.BITS_OF_PRECISION) - 1; |
| 814 | } |
| 815 | |
| 816 | void Device::ClassicState::SetCalibrationData(const WiimoteEmu::Classic::CalibrationData& data, |
| 817 | Checksum checksum) |
| 818 | { |
| 819 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Set Classic Controller calibration."); |
| 820 | |
| 821 | calibration.emplace(); |
| 822 | |
| 823 | if (checksum == Checksum::Bad) |
| 824 | return; |
| 825 | |
| 826 | const auto left_stick_calibration = data.GetLeftStick(); |
| 827 | if (left_stick_calibration.IsSane()) |
| 828 | { |
| 829 | calibration->left_stick = left_stick_calibration; |
| 830 | } |
| 831 | else |
| 832 | { |
| 833 | WARN_LOG_FMT(WIIMOTE, |
| 834 | "WiiRemote: CC left stick calibration is not sane. Using fallback values."); |
| 835 | } |
| 836 | |
| 837 | const auto right_stick_calibration = data.GetRightStick(); |
| 838 | if (right_stick_calibration.IsSane()) |
| 839 | { |
| 840 | calibration->right_stick = right_stick_calibration; |
| 841 | } |
| 842 | else |
| 843 | { |
| 844 | WARN_LOG_FMT(WIIMOTE, |
| 845 | "WiiRemote: CC right stick calibration is not sane. Using fallback values."); |
| 846 | } |
| 847 | calibration->left_trigger = data.GetLeftTrigger(); |
| 848 | calibration->right_trigger = data.GetRightTrigger(); |
| 849 | } |
| 850 | |
| 851 | void Device::ReadActiveExtensionID() |
| 852 | { |
| 853 | static constexpr u16 EXT_ID_ADDR = 0xfa; |
| 854 | static constexpr u16 EXT_ID_SIZE = 6; |
| 855 | |
| 856 | ReadData(AddressSpace::I2CBus, WiimoteEmu::ExtensionPort::REPORT_I2C_SLAVE, EXT_ID_ADDR, |
| 857 | EXT_ID_SIZE, [this](ReadResponse response) { |
| 858 | if (!response) |
| 859 | return; |
| 860 | |
| 861 | auto& identifier = *response; |
| 862 | |
| 863 | // Check for M+ ID. |
| 864 | if (identifier[5] == 0x05) |
| 865 | { |
| 866 | const auto passthrough_mode = MotionPlusState::PassthroughMode(identifier[4]); |
| 867 | |
| 868 | m_mplus_state.current_mode = passthrough_mode; |
| 869 | |
| 870 | INFO_LOG_FMT(WIIMOTE, "WiiRemote: M+ is active in mode: {}.", int(passthrough_mode)); |
| 871 | } |
| 872 | else |
| 873 | { |
| 874 | m_mplus_state.current_mode = MotionPlusState::PassthroughMode{}; |
| 875 | |
| 876 | ProcessExtensionID(identifier[0], identifier[4], identifier[5]); |
| 877 | } |
| 878 | }); |
| 879 | } |
| 880 | |
| 881 | bool Device::IRState::IsFullyConfigured() const |
| 882 | { |
| 883 | return enabled && mode_set && current_sensitivity == GetDesiredIRSensitivity(); |
| 884 | } |
| 885 | |
| 886 | u32 Device::IRState::GetDesiredIRSensitivity() |
| 887 | { |
| 888 | // Wii stores values from 1 to 5. (subtract 1) |
| 889 | const u32 configured_level = Config::Get(Config::SYSCONF_SENSOR_BAR_SENSITIVITY) - 1; |
| 890 | |
| 891 | if (configured_level < IR_SENSITIVITY_LEVEL_COUNT) |
| 892 | return configured_level; |
| 893 | |
| 894 | // Default to middle level on bad value. |
| 895 | return 2; |
| 896 | } |
| 897 | |
| 898 | void Device::SetIRSensitivity(u32 level) |
| 899 | { |
| 900 | struct IRSensitivityConfig |
| 901 | { |
| 902 | std::array<u8, 9> block1; |
| 903 | std::array<u8, 2> block2; |
| 904 | }; |
| 905 | |
| 906 | // Data for Wii levels 1 to 5. |
| 907 | static constexpr std::array<IRSensitivityConfig, IR_SENSITIVITY_LEVEL_COUNT> sensitivity_configs = |
| 908 | {{ |
| 909 | {{0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0x64, 0x00, 0xfe}, {0xfd, 0x05}}, |
| 910 | {{0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0x96, 0x00, 0xb4}, {0xb3, 0x04}}, |
| 911 | {{0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xaa, 0x00, 0x64}, {0x63, 0x03}}, |
| 912 | {{0x02, 0x00, 0x00, 0x71, 0x01, 0x00, 0xc8, 0x00, 0x36}, {0x35, 0x03}}, |
| 913 | {{0x07, 0x00, 0x00, 0x71, 0x01, 0x00, 0x72, 0x00, 0x20}, {0x1f, 0x03}}, |
| 914 | }}; |
| 915 | |
| 916 | static constexpr u16 BLOCK1_ADDR = 0x00; |
| 917 | static constexpr u16 BLOCK2_ADDR = 0x1a; |
| 918 | |
| 919 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Setting IR sensitivity: {}.", level + 1); |
| 920 | |
| 921 | const auto& sensitivity_config = sensitivity_configs[level]; |
| 922 | |
| 923 | WriteData(AddressSpace::I2CBus, WiimoteEmu::CameraLogic::I2C_ADDR, BLOCK1_ADDR, |
| 924 | sensitivity_config.block1, [&sensitivity_config, level, this](ErrorCode block_result) { |
| 925 | if (block_result != ErrorCode::Success) |
| 926 | { |
| 927 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Failed to write IR block 1."); |
| 928 | return; |
| 929 | } |
| 930 | |
| 931 | WriteData(AddressSpace::I2CBus, WiimoteEmu::CameraLogic::I2C_ADDR, BLOCK2_ADDR, |
| 932 | sensitivity_config.block2, [&, level, this](ErrorCode block2_result) { |
| 933 | if (block2_result != ErrorCode::Success) |
| 934 | { |
| 935 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Failed to write IR block 2."); |
| 936 | return; |
| 937 | } |
| 938 | |
| 939 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: IR sensitivity set."); |
| 940 | |
| 941 | m_ir_state.current_sensitivity = level; |
| 942 | }); |
| 943 | }); |
| 944 | } |
| 945 | |
| 946 | void Device::ConfigureIRCamera() |
| 947 | { |
| 948 | if (!m_ir_state.enabled) |
| 949 | { |
| 950 | OutputReportIRLogicEnable2 ir_logic2 = {}; |
| 951 | ir_logic2.ack = 1; |
| 952 | ir_logic2.enable = 1; |
| 953 | QueueReport(ir_logic2, [this](ErrorCode result) { |
| 954 | if (result != ErrorCode::Success) |
| 955 | { |
| 956 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Failed to enable IR."); |
| 957 | return; |
| 958 | } |
| 959 | |
| 960 | OutputReportIRLogicEnable ir_logic = {}; |
| 961 | ir_logic.ack = 1; |
| 962 | ir_logic.enable = 1; |
| 963 | QueueReport(ir_logic, [this](ErrorCode ir_result) { |
| 964 | if (ir_result != ErrorCode::Success) |
| 965 | { |
| 966 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Failed to enable IR."); |
| 967 | return; |
| 968 | } |
| 969 | |
| 970 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: IR enabled."); |
| 971 | |
| 972 | m_ir_state.enabled = true; |
| 973 | }); |
| 974 | }); |
| 975 | |
| 976 | return; |
| 977 | } |
| 978 | |
| 979 | if (const u32 desired_level = IRState::GetDesiredIRSensitivity(); |
| 980 | desired_level != m_ir_state.current_sensitivity) |
| 981 | { |
| 982 | SetIRSensitivity(desired_level); |
| 983 | |
| 984 | return; |
| 985 | } |
| 986 | |
| 987 | if (!m_ir_state.mode_set) |
| 988 | { |
| 989 | static constexpr u16 MODE_ADDR = 0x33; |
| 990 | |
| 991 | // We only support "Basic" mode (it's all that fits in ReportCoreAccelIR10Ext6). |
| 992 | WriteData(AddressSpace::I2CBus, WiimoteEmu::CameraLogic::I2C_ADDR, MODE_ADDR, |
| 993 | {WiimoteEmu::CameraLogic::IR_MODE_BASIC}, [this](ErrorCode mode_result) { |
| 994 | if (mode_result != ErrorCode::Success) |
| 995 | { |
| 996 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Failed to set IR mode."); |
| 997 | return; |
| 998 | } |
| 999 | |
| 1000 | // This seems to enable object tracking. |
| 1001 | static constexpr u16 ENABLE_ADDR = 0x30; |
| 1002 | static constexpr u8 ENABLE_VALUE = 0x08; |
| 1003 | |
| 1004 | WriteData(AddressSpace::I2CBus, WiimoteEmu::CameraLogic::I2C_ADDR, ENABLE_ADDR, |
| 1005 | {ENABLE_VALUE}, [this](ErrorCode result) { |
| 1006 | if (result != ErrorCode::Success) |
| 1007 | { |
| 1008 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Failed to enable object tracking."); |
| 1009 | return; |
| 1010 | } |
| 1011 | |
| 1012 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: IR mode set."); |
| 1013 | |
| 1014 | m_ir_state.mode_set = true; |
| 1015 | }); |
| 1016 | }); |
| 1017 | } |
| 1018 | } |
| 1019 | |
| 1020 | void Device::ConfigureSpeaker() |
| 1021 | { |
| 1022 | OutputReportSpeakerMute mute = {}; |
| 1023 | mute.enable = 1; |
| 1024 | mute.ack = 1; |
| 1025 | QueueReport(mute, [this](ErrorCode mute_result) { |
| 1026 | if (mute_result != ErrorCode::Success) |
| 1027 | { |
| 1028 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Failed to mute speaker."); |
| 1029 | return; |
| 1030 | } |
| 1031 | |
| 1032 | OutputReportSpeakerEnable spkr = {}; |
| 1033 | spkr.enable = 0; |
| 1034 | spkr.ack = 1; |
| 1035 | QueueReport(spkr, [this](ErrorCode enable_result) { |
| 1036 | if (enable_result != ErrorCode::Success) |
| 1037 | { |
| 1038 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Failed to disable speaker."); |
| 1039 | return; |
| 1040 | } |
| 1041 | |
| 1042 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Speaker muted and disabled."); |
| 1043 | |
| 1044 | m_speaker_configured = true; |
| 1045 | }); |
| 1046 | }); |
| 1047 | } |
| 1048 | |
| 1049 | void Device::TriggerMotionPlusModeChange() |
| 1050 | { |
| 1051 | if (!m_mplus_desired_mode.has_value()) |
| 1052 | return; |
| 1053 | |
| 1054 | const u8 passthrough_mode = u8(*m_mplus_desired_mode); |
| 1055 | |
| 1056 | const u8 device_addr = IsMotionPlusActive() ? WiimoteEmu::MotionPlus::ACTIVE_DEVICE_ADDR : |
| 1057 | WiimoteEmu::MotionPlus::INACTIVE_DEVICE_ADDR; |
| 1058 | |
| 1059 | WriteData(AddressSpace::I2CBus, device_addr, WiimoteEmu::MotionPlus::PASSTHROUGH_MODE_OFFSET, |
| 1060 | {passthrough_mode}, [this](ErrorCode activation_result) { |
| 1061 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: M+ activation: {}.", int(activation_result)); |
| 1062 | |
| 1063 | WaitForMotionPlus(); |
| 1064 | |
| 1065 | // Normally M+ will be seen performing a reset here. (extension port events) |
| 1066 | // But sometimes (rarely) M+ activation does not cause an extension port event. |
| 1067 | // We'll consider the mode unknown. It will be read back after some time. |
| 1068 | m_mplus_state.current_mode = std::nullopt; |
| 1069 | }); |
| 1070 | } |
| 1071 | |
| 1072 | void Device::TriggerMotionPlusCalibration() |
| 1073 | { |
| 1074 | static constexpr u16 CALIBRATION_TRIGGER_ADDR = 0xf2; |
| 1075 | static constexpr u8 CALIBRATION_TRIGGER_VALUE = 0x00; |
| 1076 | |
| 1077 | // This triggers a hardware "zero" calibration. |
| 1078 | // The effect is notiecable but output still strays from calibration data. |
| 1079 | // It seems we're better off just manually determining "zero". |
| 1080 | WriteData(AddressSpace::I2CBus, WiimoteEmu::MotionPlus::ACTIVE_DEVICE_ADDR, |
| 1081 | CALIBRATION_TRIGGER_ADDR, {CALIBRATION_TRIGGER_VALUE}, [](ErrorCode result) { |
| 1082 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: M+ calibration trigger done: {}.", int(result)); |
| 1083 | }); |
| 1084 | } |
| 1085 | |
| 1086 | bool Device::IsMotionPlusStateKnown() const |
| 1087 | { |
| 1088 | return m_mplus_state.current_mode.has_value(); |
| 1089 | } |
| 1090 | |
| 1091 | bool Device::IsMotionPlusActive() const |
| 1092 | { |
| 1093 | return m_mplus_state.current_mode != MotionPlusState::PassthroughMode{}; |
| 1094 | } |
| 1095 | |
| 1096 | bool Device::IsMotionPlusInDesiredMode() const |
| 1097 | { |
| 1098 | return m_mplus_state.current_mode.has_value() && |
| 1099 | (m_mplus_state.current_mode == m_mplus_desired_mode); |
| 1100 | } |
| 1101 | |
| 1102 | void Device::ProcessInputReport(WiimoteReal::Report& report) |
| 1103 | { |
| 1104 | if (report.size() < WiimoteReal::REPORT_HID_HEADER_SIZE) |
| 1105 | { |
| 1106 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Bad report size."); |
| 1107 | return; |
| 1108 | } |
| 1109 | |
| 1110 | auto report_id = InputReportID(report[WiimoteReal::REPORT_HID_HEADER_SIZE]); |
| 1111 | |
| 1112 | for (auto it = m_report_handlers.begin(); true;) |
| 1113 | { |
| 1114 | if (it == m_report_handlers.end()) |
| 1115 | { |
| 1116 | if (report_id == InputReportID::Status) |
| 1117 | { |
| 1118 | if (report.size() - WiimoteReal::REPORT_HID_HEADER_SIZE < |
| 1119 | sizeof(TypedInputData<InputReportStatus>)) |
| 1120 | { |
| 1121 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Bad report size."); |
| 1122 | } |
| 1123 | else |
| 1124 | { |
| 1125 | ProcessStatusReport(Common::BitCastPtr<InputReportStatus>(report.data() + 2)); |
| 1126 | } |
| 1127 | } |
| 1128 | else if (report_id < InputReportID::ReportCore) |
| 1129 | { |
| 1130 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Unhandled input report: {}.", |
| 1131 | ArrayToString(report.data(), u32(report.size()))); |
| 1132 | } |
| 1133 | |
| 1134 | break; |
| 1135 | } |
| 1136 | |
| 1137 | if (it->IsExpired()) |
| 1138 | { |
| 1139 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Removing expired handler."); |
| 1140 | it = m_report_handlers.erase(it); |
| 1141 | continue; |
| 1142 | } |
| 1143 | |
| 1144 | if (const auto result = it->TryToHandleReport(report); |
| 1145 | result == ReportHandler::HandlerResult::Handled) |
| 1146 | { |
| 1147 | it = m_report_handlers.erase(it); |
| 1148 | break; |
| 1149 | } |
| 1150 | |
| 1151 | ++it; |
| 1152 | } |
| 1153 | |
| 1154 | if (report_id < InputReportID::ReportCore) |
| 1155 | { |
| 1156 | // Normal input reports can be processed as "ReportCore". |
| 1157 | report_id = InputReportID::ReportCore; |
| 1158 | } |
| 1159 | else |
| 1160 | { |
| 1161 | // We can assume the last received input report is the current reporting mode. |
| 1162 | // FYI: This logic fails to properly handle the (never used) "interleaved" reports. |
| 1163 | m_reporting_mode = InputReportID(report_id); |
| 1164 | } |
| 1165 | |
| 1166 | auto manipulator = MakeDataReportManipulator( |
| 1167 | report_id, report.data() + WiimoteReal::REPORT_HID_HEADER_SIZE + sizeof(InputReportID)); |
| 1168 | |
| 1169 | if (manipulator->GetDataSize() + WiimoteReal::REPORT_HID_HEADER_SIZE > report.size()) |
| 1170 | { |
| 1171 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Bad report size."); |
| 1172 | return; |
| 1173 | } |
| 1174 | |
| 1175 | // Read buttons. |
| 1176 | manipulator->GetCoreData(&m_core_data); |
| 1177 | |
| 1178 | // Process accel data. |
| 1179 | if (manipulator->HasAccel() && m_accel_calibration.has_value()) |
| 1180 | { |
| 1181 | // FYI: This logic fails to properly handle the (never used) "interleaved" reports. |
| 1182 | AccelData accel_data = {}; |
| 1183 | manipulator->GetAccelData(&accel_data); |
| 1184 | |
| 1185 | m_accel_data = |
| 1186 | accel_data.GetNormalizedValue(*m_accel_calibration) * float(MathUtil::GRAVITY_ACCELERATION); |
| 1187 | } |
| 1188 | |
| 1189 | // Process IR data. |
| 1190 | if (manipulator->HasIR() && m_ir_state.IsFullyConfigured()) |
| 1191 | { |
| 1192 | m_ir_state.ProcessData(*manipulator); |
| 1193 | } |
| 1194 | |
| 1195 | // Process extension data. |
| 1196 | if (IsMotionPlusStateKnown()) |
| 1197 | { |
| 1198 | const auto ext_data = manipulator->GetExtDataPtr(); |
| 1199 | const auto ext_size = manipulator->GetExtDataSize(); |
| 1200 | |
| 1201 | if (IsMotionPlusActive()) |
| 1202 | ProcessMotionPlusExtensionData(ext_data, ext_size); |
| 1203 | else |
| 1204 | ProcessNormalExtensionData(ext_data, ext_size); |
| 1205 | } |
| 1206 | |
| 1207 | UpdateOrientation(); |
| 1208 | } |
| 1209 | |
| 1210 | void Device::UpdateOrientation() |
| 1211 | { |
| 1212 | const auto current_report_time = Clock::now(); |
| 1213 | const auto elapsed_time = std::chrono::duration_cast<std::chrono::duration<float>>( |
| 1214 | current_report_time - m_last_report_time); |
| 1215 | m_last_report_time = current_report_time; |
| 1216 | |
| 1217 | // Apply M+ gyro data to our orientation. |
| 1218 | m_orientation = |
| 1219 | WiimoteEmu::GetRotationFromGyroscope(m_mplus_state.gyro_data * -1 * elapsed_time.count()) * |
| 1220 | m_orientation; |
| 1221 | |
| 1222 | // When M+ data is not available give accel/ir data more weight. |
| 1223 | // ComplementaryFilter will then just smooth out our data a bit. |
| 1224 | const bool is_mplus_active = IsMotionPlusStateKnown() && IsMotionPlusActive(); |
| 1225 | |
| 1226 | // With non-zero acceleration data we can perform pitch and roll correction. |
| 1227 | if (m_accel_data.LengthSquared()) |
| 1228 | { |
| 1229 | const auto accel_weight = is_mplus_active ? 0.04 : 0.5f; |
| 1230 | |
| 1231 | m_orientation = WiimoteEmu::ComplementaryFilter(m_orientation, m_accel_data, accel_weight); |
| 1232 | } |
| 1233 | |
| 1234 | // If IR objects are visible we can perform yaw and pitch correction. |
| 1235 | if (!m_ir_state.is_hidden) |
| 1236 | { |
| 1237 | // FYI: We could do some roll correction from multiple IR objects. |
| 1238 | |
| 1239 | const auto ir_rotation = |
| 1240 | Common::Vec3(m_ir_state.center_position.y * WiimoteEmu::CameraLogic::CAMERA_FOV_Y, 0, |
| 1241 | m_ir_state.center_position.x * WiimoteEmu::CameraLogic::CAMERA_FOV_X) / |
| 1242 | 2; |
| 1243 | const auto ir_normal = Common::Vec3(0, 1, 0); |
| 1244 | const auto ir_vector = WiimoteEmu::GetRotationFromGyroscope(-ir_rotation) * ir_normal; |
| 1245 | |
| 1246 | // Pitch correction will be slightly wrong based on sensorbar height. |
| 1247 | // Keep weight below accelerometer weight for that reason. |
| 1248 | // Correction will only happen near pitch zero when the sensorbar is actually in view. |
| 1249 | const auto ir_weight = is_mplus_active ? 0.035 : 0.45f; |
| 1250 | |
| 1251 | m_orientation = WiimoteEmu::ComplementaryFilter(m_orientation, ir_vector, ir_weight, ir_normal); |
| 1252 | } |
| 1253 | |
| 1254 | // Normalize for floating point inaccuracies. |
| 1255 | m_orientation = m_orientation.Normalized(); |
| 1256 | |
| 1257 | // Update our (pitch, roll, yaw) inputs now that orientation has been adjusted. |
| 1258 | m_rotation_inputs = |
| 1259 | Common::Vec3{WiimoteEmu::GetPitch(m_orientation), WiimoteEmu::GetRoll(m_orientation), |
| 1260 | WiimoteEmu::GetYaw(m_orientation)} / |
| 1261 | float(MathUtil::PI); |
| 1262 | } |
| 1263 | |
| 1264 | void Device::IRState::ProcessData(const DataReportManipulator& manipulator) |
| 1265 | { |
| 1266 | // A better implementation might extrapolate points when they fall out of camera view. |
| 1267 | // But just averaging visible points actually seems to work very well. |
| 1268 | |
| 1269 | using IRObject = WiimoteEmu::IRObject; |
| 1270 | |
| 1271 | MathUtil::RunningVariance<Common::Vec2> points; |
| 1272 | |
| 1273 | const auto camera_max = IRObject(WiimoteEmu::CameraLogic::CAMERA_RES_X - 1, |
| 1274 | WiimoteEmu::CameraLogic::CAMERA_RES_Y - 1); |
| 1275 | |
| 1276 | const auto add_point = [&](IRObject point, u8 size, size_t idx) { |
| 1277 | // Non-visible points are 0xFF-filled. |
| 1278 | if (point.y > camera_max.y) |
| 1279 | { |
| 1280 | raw_ir_object_position[idx].x = 0.0f; |
| 1281 | raw_ir_object_position[idx].y = 0.0f; |
| 1282 | raw_ir_object_size[idx] = 0.0f; |
| 1283 | return; |
| 1284 | } |
| 1285 | |
| 1286 | raw_ir_object_position[idx].x = static_cast<float>(point.x) / camera_max.x; |
| 1287 | raw_ir_object_position[idx].y = static_cast<float>(point.y) / camera_max.y; |
| 1288 | raw_ir_object_size[idx] = static_cast<float>(size) / 15.0f; |
| 1289 | |
| 1290 | points.Push(Common::Vec2(point)); |
| 1291 | }; |
| 1292 | |
| 1293 | size_t object_index = 0; |
| 1294 | switch (manipulator.GetIRReportFormat()) |
| 1295 | { |
| 1296 | case IRReportFormat::Basic: |
| 1297 | { |
| 1298 | const std::array<WiimoteEmu::IRBasic, 2> data = |
| 1299 | Common::BitCastPtr<std::array<WiimoteEmu::IRBasic, 2>>(manipulator.GetIRDataPtr()); |
| 1300 | for (const auto& block : data) |
| 1301 | { |
| 1302 | // size is not reported by IRBasic, just assume a typical size |
| 1303 | add_point(block.GetObject1(), 2, object_index); |
| 1304 | ++object_index; |
| 1305 | add_point(block.GetObject2(), 2, object_index); |
| 1306 | ++object_index; |
| 1307 | } |
| 1308 | break; |
| 1309 | } |
| 1310 | case IRReportFormat::Extended: |
| 1311 | { |
| 1312 | const std::array<WiimoteEmu::IRExtended, 4> data = |
| 1313 | Common::BitCastPtr<std::array<WiimoteEmu::IRExtended, 4>>(manipulator.GetIRDataPtr()); |
| 1314 | for (const auto& object : data) |
| 1315 | { |
| 1316 | add_point(object.GetPosition(), object.size, object_index); |
| 1317 | ++object_index; |
| 1318 | } |
| 1319 | break; |
| 1320 | } |
| 1321 | default: |
| 1322 | // unsupported format |
| 1323 | return; |
| 1324 | } |
| 1325 | |
| 1326 | is_hidden = !points.Count(); |
| 1327 | |
| 1328 | if (points.Count() >= 2) |
| 1329 | { |
| 1330 | const auto variance = points.PopulationVariance(); |
| 1331 | // Adjusts Y coordinate to match horizontal FOV. |
| 1332 | const auto separation = |
| 1333 | Common::Vec2(std::sqrt(variance.x), std::sqrt(variance.y)) / |
| 1334 | Common::Vec2(WiimoteEmu::CameraLogic::CAMERA_RES_X, |
| 1335 | WiimoteEmu::CameraLogic::CAMERA_RES_Y * WiimoteEmu::CameraLogic::CAMERA_AR) * |
| 1336 | 2; |
| 1337 | |
| 1338 | distance = WiimoteEmu::CameraLogic::SENSOR_BAR_LED_SEPARATION / separation.Length() / 2 / |
| 1339 | std::tan(WiimoteEmu::CameraLogic::CAMERA_FOV_X / 2); |
| 1340 | } |
| 1341 | |
| 1342 | if (points.Count()) |
| 1343 | { |
| 1344 | center_position = points.Mean() / Common::Vec2(camera_max) * 2.f - Common::Vec2(1, 1); |
| 1345 | } |
| 1346 | else |
| 1347 | { |
| 1348 | center_position = {}; |
| 1349 | } |
| 1350 | } |
| 1351 | |
| 1352 | void Device::ProcessMotionPlusExtensionData(const u8* ext_data, u32 ext_size) |
| 1353 | { |
| 1354 | if (ext_size < sizeof(WiimoteEmu::MotionPlus::DataFormat)) |
| 1355 | return; |
| 1356 | |
| 1357 | const WiimoteEmu::MotionPlus::DataFormat mplus_data = |
| 1358 | Common::BitCastPtr<WiimoteEmu::MotionPlus::DataFormat>(ext_data); |
| 1359 | |
| 1360 | const bool is_ext_connected = mplus_data.extension_connected; |
| 1361 | |
| 1362 | // Handle passthrough extension change. |
| 1363 | if (is_ext_connected != m_mplus_state.passthrough_port) |
| 1364 | { |
| 1365 | m_mplus_state.passthrough_port = is_ext_connected; |
| 1366 | |
| 1367 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: M+ passthrough port event: {}.", is_ext_connected); |
| 1368 | |
| 1369 | // With no passthrough extension we'll be happy with the current mode. |
| 1370 | if (!is_ext_connected) |
| 1371 | m_mplus_desired_mode = m_mplus_state.current_mode; |
| 1372 | |
| 1373 | ProcessExtensionEvent(is_ext_connected); |
| 1374 | } |
| 1375 | |
| 1376 | if (mplus_data.is_mp_data) |
| 1377 | { |
| 1378 | m_mplus_state.ProcessData(mplus_data); |
| 1379 | return; |
| 1380 | } |
| 1381 | |
| 1382 | if (!IsMotionPlusInDesiredMode()) |
| 1383 | { |
| 1384 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Ignoring unwanted passthrough data."); |
| 1385 | return; |
| 1386 | } |
| 1387 | |
| 1388 | std::array<u8, sizeof(WiimoteEmu::Nunchuk::DataFormat)> data; |
| 1389 | std::copy_n(ext_data, ext_size, data.begin()); |
| 1390 | |
| 1391 | // Undo bit-hacks of M+ passthrough. |
| 1392 | WiimoteEmu::MotionPlus::ReversePassthroughModifications(*m_mplus_state.current_mode, data.data()); |
| 1393 | |
| 1394 | ProcessNormalExtensionData(data.data(), u32(data.size())); |
| 1395 | } |
| 1396 | |
| 1397 | void Device::ProcessNormalExtensionData(const u8* ext_data, u32 ext_size) |
| 1398 | { |
| 1399 | if (m_extension_id == ExtensionID::Nunchuk) |
| 1400 | { |
| 1401 | if (ext_size < sizeof(WiimoteEmu::MotionPlus::DataFormat)) |
| 1402 | return; |
| 1403 | |
| 1404 | const WiimoteEmu::Nunchuk::DataFormat nunchuk_data = |
| 1405 | Common::BitCastPtr<WiimoteEmu::Nunchuk::DataFormat>(ext_data); |
| 1406 | |
| 1407 | m_nunchuk_state.ProcessData(nunchuk_data); |
| 1408 | } |
| 1409 | else if (m_extension_id == ExtensionID::Classic) |
| 1410 | { |
| 1411 | if (ext_size < sizeof(WiimoteEmu::Classic::DataFormat)) |
| 1412 | return; |
| 1413 | |
| 1414 | const WiimoteEmu::Classic::DataFormat cc_data = |
| 1415 | Common::BitCastPtr<WiimoteEmu::Classic::DataFormat>(ext_data); |
| 1416 | |
| 1417 | m_classic_state.ProcessData(cc_data); |
| 1418 | } |
| 1419 | } |
| 1420 | |
| 1421 | void Device::UpdateRumble() |
| 1422 | { |
| 1423 | static constexpr auto rumble_period = std::chrono::milliseconds(100); |
| 1424 | |
| 1425 | const auto on_time = |
| 1426 | std::chrono::duration_cast<Clock::duration>(rumble_period * m_rumble_level.load()); |
| 1427 | const auto off_time = rumble_period - on_time; |
| 1428 | |
| 1429 | const auto now = Clock::now(); |
| 1430 | |
| 1431 | if (m_rumble && (now < m_last_rumble_change + on_time || !off_time.count())) |
| 1432 | return; |
| 1433 | |
| 1434 | if (!m_rumble && (now < m_last_rumble_change + off_time || !on_time.count())) |
| 1435 | return; |
| 1436 | |
| 1437 | m_last_rumble_change = now; |
| 1438 | m_rumble ^= true; |
| 1439 | |
| 1440 | // Rumble flag will be set within QueueReport. |
| 1441 | QueueReport(OutputReportRumble{}); |
| 1442 | } |
| 1443 | |
| 1444 | Core::DeviceRemoval Device::UpdateInput() |
| 1445 | { |
| 1446 | if (!m_wiimote->IsConnected()) |
| 1447 | return Core::DeviceRemoval::Remove; |
| 1448 | |
| 1449 | UpdateRumble(); |
| 1450 | RunTasks(); |
| 1451 | |
| 1452 | WiimoteReal::Report report; |
| 1453 | while (m_wiimote->GetNextReport(&report)) |
| 1454 | { |
| 1455 | ProcessInputReport(report); |
| 1456 | RunTasks(); |
| 1457 | } |
| 1458 | |
| 1459 | return Core::DeviceRemoval::Keep; |
| 1460 | } |
| 1461 | |
| 1462 | void Device::MotionPlusState::ProcessData(const WiimoteEmu::MotionPlus::DataFormat& data) |
| 1463 | { |
| 1464 | // We need the calibration block read to know the sensor orientations. |
| 1465 | if (!calibration.has_value()) |
| 1466 | return; |
| 1467 | |
| 1468 | gyro_data = data.GetData().GetAngularVelocity(*calibration); |
| 1469 | } |
| 1470 | |
| 1471 | bool Device::IsWaitingForMotionPlus() const |
| 1472 | { |
| 1473 | return Clock::now() < m_mplus_wait_time; |
| 1474 | } |
| 1475 | |
| 1476 | void Device::WaitForMotionPlus() |
| 1477 | { |
| 1478 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Wait for M+."); |
| 1479 | m_mplus_wait_time = Clock::now() + std::chrono::seconds{2}; |
| 1480 | } |
| 1481 | |
| 1482 | void Device::NunchukState::ProcessData(const WiimoteEmu::Nunchuk::DataFormat& data) |
| 1483 | { |
| 1484 | buttons = data.GetButtons(); |
| 1485 | |
| 1486 | // Stick/accel require calibration data. |
| 1487 | if (!calibration.has_value()) |
| 1488 | return; |
| 1489 | |
| 1490 | stick = data.GetStick().GetNormalizedValue(calibration->stick); |
| 1491 | accel = data.GetAccel().GetNormalizedValue(calibration->accel) * |
| 1492 | float(MathUtil::GRAVITY_ACCELERATION); |
| 1493 | } |
| 1494 | |
| 1495 | void Device::ClassicState::ProcessData(const WiimoteEmu::Classic::DataFormat& data) |
| 1496 | { |
| 1497 | buttons = data.GetButtons(); |
| 1498 | |
| 1499 | // Sticks/triggers require calibration data. |
| 1500 | if (!calibration.has_value()) |
| 1501 | return; |
| 1502 | |
| 1503 | sticks[0] = data.GetLeftStick().GetNormalizedValue(calibration->left_stick); |
| 1504 | sticks[1] = data.GetRightStick().GetNormalizedValue(calibration->right_stick); |
| 1505 | triggers[0] = data.GetLeftTrigger().GetNormalizedValue(calibration->left_trigger); |
| 1506 | triggers[1] = data.GetRightTrigger().GetNormalizedValue(calibration->right_trigger); |
| 1507 | } |
| 1508 | |
| 1509 | void Device::ReadData(AddressSpace space, u8 slave, u16 address, u16 size, |
| 1510 | std::function<void(ReadResponse)> callback) |
| 1511 | { |
| 1512 | OutputReportReadData read_data{}; |
| 1513 | read_data.space = u8(space); |
| 1514 | read_data.slave_address = slave; |
| 1515 | read_data.address[0] = u8(address >> 8); |
| 1516 | read_data.address[1] = u8(address); |
| 1517 | read_data.size[0] = u8(size >> 8); |
| 1518 | read_data.size[1] = u8(size); |
| 1519 | QueueReport(read_data); |
| 1520 | |
| 1521 | AddReadDataReplyHandler(space, slave, address, size, {}, std::move(callback)); |
| 1522 | } |
| 1523 | |
| 1524 | void Device::AddReadDataReplyHandler(AddressSpace space, u8 slave, u16 address, u16 size, |
| 1525 | std::vector<u8> starting_data, |
| 1526 | std::function<void(ReadResponse)> callback) |
| 1527 | { |
| 1528 | // Data read may return a busy ack. |
| 1529 | auto ack_handler = MakeAckHandler(OutputReportID::ReadData, [callback](ErrorCode result) { |
| 1530 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Read ack error: {}.", int(result)); |
| 1531 | callback(ReadResponse{}); |
| 1532 | }); |
| 1533 | |
| 1534 | // Or more normally a "ReadDataReply". |
| 1535 | auto read_handler = [this, space, slave, address, size, data = std::move(starting_data), |
| 1536 | callback = |
| 1537 | std::move(callback)](const InputReportReadDataReply& reply) mutable { |
| 1538 | if (Common::swap16(reply.address) != address) |
| 1539 | return ReportHandler::HandlerResult::NotHandled; |
| 1540 | |
| 1541 | if (reply.error != u8(ErrorCode::Success)) |
| 1542 | { |
| 1543 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Read reply error: {}.", int(reply.error)); |
| 1544 | callback(ReadResponse{}); |
| 1545 | |
| 1546 | return ReportHandler::HandlerResult::Handled; |
| 1547 | } |
| 1548 | |
| 1549 | const auto read_count = reply.size_minus_one + 1; |
| 1550 | |
| 1551 | data.insert(data.end(), reply.data, reply.data + read_count); |
| 1552 | |
| 1553 | if (read_count < size) |
| 1554 | { |
| 1555 | // We have more data to acquire. |
| 1556 | AddReadDataReplyHandler(space, slave, address + read_count, size - read_count, |
| 1557 | std::move(data), std::move(callback)); |
| 1558 | } |
| 1559 | else |
| 1560 | { |
| 1561 | // We have all the data. |
| 1562 | callback(std::move(data)); |
| 1563 | } |
| 1564 | |
| 1565 | return ReportHandler::HandlerResult::Handled; |
| 1566 | }; |
| 1567 | |
| 1568 | AddReportHandler( |
| 1569 | std::function<ReportHandler::HandlerResult(const InputReportReadDataReply& reply)>( |
| 1570 | std::move(read_handler)), |
| 1571 | std::move(ack_handler)); |
| 1572 | } |
| 1573 | |
| 1574 | template <typename T, typename C> |
| 1575 | void Device::WriteData(AddressSpace space, u8 slave, u16 address, T&& data, C&& callback) |
| 1576 | { |
| 1577 | OutputReportWriteData write_data = {}; |
| 1578 | write_data.space = u8(space); |
| 1579 | write_data.slave_address = slave; |
| 1580 | write_data.address[0] = u8(address >> 8); |
| 1581 | write_data.address[1] = u8(address); |
| 1582 | |
| 1583 | static constexpr auto MAX_DATA_SIZE = std::size(write_data.data); |
| 1584 | write_data.size = u8(std::min(std::size(data), MAX_DATA_SIZE)); |
| 1585 | |
| 1586 | std::copy_n(std::begin(data), write_data.size, write_data.data); |
| 1587 | |
| 1588 | // Writes of more than 16 bytes must be split into multiple reports. |
| 1589 | if (std::size(data) > MAX_DATA_SIZE) |
| 1590 | { |
| 1591 | auto next_write = [this, space, slave, address, |
| 1592 | additional_data = |
| 1593 | std::vector<u8>(std::begin(data) + MAX_DATA_SIZE, std::end(data)), |
| 1594 | callback = std::forward<C>(callback)](ErrorCode result) mutable { |
| 1595 | if (result != ErrorCode::Success) |
| 1596 | callback(result); |
| 1597 | else |
| 1598 | WriteData(space, slave, address + MAX_DATA_SIZE, additional_data, std::move(callback)); |
| 1599 | }; |
| 1600 | |
| 1601 | QueueReport(write_data, std::move(next_write)); |
| 1602 | } |
| 1603 | else |
| 1604 | { |
| 1605 | QueueReport(write_data, std::forward<C>(callback)); |
| 1606 | } |
| 1607 | } |
| 1608 | |
| 1609 | Device::ReportHandler::ReportHandler(Clock::time_point expired_time) : m_expired_time(expired_time) |
| 1610 | { |
| 1611 | } |
| 1612 | |
| 1613 | template <typename... T> |
| 1614 | void Device::AddReportHandler(T&&... callbacks) |
| 1615 | { |
| 1616 | auto& handler = m_report_handlers.emplace_back(Clock::now() + std::chrono::seconds{5}); |
| 1617 | (handler.AddHandler(std::forward<T>(callbacks)), ...); |
| 1618 | } |
| 1619 | |
| 1620 | template <typename R, typename T> |
| 1621 | void Device::ReportHandler::AddHandler(std::function<R(const T&)> handler) |
| 1622 | { |
| 1623 | m_callbacks.emplace_back([handler = std::move(handler)](const WiimoteReal::Report& report) { |
| 1624 | if (report[WiimoteReal::REPORT_HID_HEADER_SIZE] != u8(T::REPORT_ID)) |
| 1625 | return ReportHandler::HandlerResult::NotHandled; |
| 1626 | |
| 1627 | T data; |
| 1628 | |
| 1629 | if (report.size() < sizeof(T) + WiimoteReal::REPORT_HID_HEADER_SIZE + 1) |
| 1630 | { |
| 1631 | // Off-brand "NEW 2in1" Wii Remote likes to shorten read data replies. |
| 1632 | WARN_LOG_FMT(WIIMOTE, "WiiRemote: Bad report size ({}) for report {:#x}. Zero-filling.", |
| 1633 | report.size(), int(T::REPORT_ID)); |
| 1634 | |
| 1635 | data = {}; |
| 1636 | std::memcpy(&data, report.data() + WiimoteReal::REPORT_HID_HEADER_SIZE + 1, |
| 1637 | report.size() - WiimoteReal::REPORT_HID_HEADER_SIZE + 1); |
| 1638 | } |
| 1639 | else |
| 1640 | { |
| 1641 | data = Common::BitCastPtr<T>(report.data() + WiimoteReal::REPORT_HID_HEADER_SIZE + 1); |
| 1642 | } |
| 1643 | |
| 1644 | if constexpr (std::is_same_v<decltype(handler(data)), void>) |
| 1645 | { |
| 1646 | handler(data); |
| 1647 | return ReportHandler::HandlerResult::Handled; |
| 1648 | } |
| 1649 | else |
| 1650 | { |
| 1651 | return handler(data); |
| 1652 | } |
| 1653 | }); |
| 1654 | } |
| 1655 | |
| 1656 | auto Device::ReportHandler::TryToHandleReport(const WiimoteReal::Report& report) -> HandlerResult |
| 1657 | { |
| 1658 | for (auto& callback : m_callbacks) |
| 1659 | { |
| 1660 | if (const auto result = callback(report); result != HandlerResult::NotHandled) |
| 1661 | return result; |
| 1662 | } |
| 1663 | |
| 1664 | return HandlerResult::NotHandled; |
| 1665 | } |
| 1666 | |
| 1667 | bool Device::ReportHandler::IsExpired() const |
| 1668 | { |
| 1669 | return Clock::now() >= m_expired_time; |
| 1670 | } |
| 1671 | |
| 1672 | auto Device::MakeAckHandler(OutputReportID report_id, |
| 1673 | std::function<void(WiimoteCommon::ErrorCode)> callback) |
| 1674 | -> AckReportHandler |
| 1675 | { |
| 1676 | return [report_id, callback = std::move(callback)](const InputReportAck& reply) { |
| 1677 | if (reply.rpt_id != report_id) |
| 1678 | return ReportHandler::HandlerResult::NotHandled; |
| 1679 | |
| 1680 | callback(reply.error_code); |
| 1681 | return ReportHandler::HandlerResult::Handled; |
| 1682 | }; |
| 1683 | } |
| 1684 | |
| 1685 | bool Device::IsPerformingTask() const |
| 1686 | { |
| 1687 | return !m_report_handlers.empty(); |
| 1688 | } |
| 1689 | |
| 1690 | void Device::ProcessStatusReport(const InputReportStatus& status) |
| 1691 | { |
| 1692 | // Update status periodically to keep battery level value up to date. |
| 1693 | m_status_outdated_time = Clock::now() + std::chrono::seconds(10); |
| 1694 | |
| 1695 | m_battery = status.GetEstimatedCharge() * BATTERY_INPUT_MAX_VALUE; |
| 1696 | m_leds = status.leds; |
| 1697 | |
| 1698 | if (!status.ir) |
| 1699 | m_ir_state = {}; |
| 1700 | |
| 1701 | const bool is_ext_connected = status.extension; |
| 1702 | |
| 1703 | // Handle extension port state change. |
| 1704 | if (is_ext_connected != m_extension_port) |
| 1705 | { |
| 1706 | DEBUG_LOG_FMT(WIIMOTE, "WiiRemote: Extension port event: {}.", is_ext_connected); |
| 1707 | |
| 1708 | m_extension_port = is_ext_connected; |
| 1709 | |
| 1710 | // Data reporting stops on an extension port event. |
| 1711 | m_reporting_mode = InputReportID::ReportDisabled; |
| 1712 | |
| 1713 | ProcessExtensionEvent(is_ext_connected); |
| 1714 | |
| 1715 | // The M+ is now in an unknown state. |
| 1716 | m_mplus_state = {}; |
| 1717 | |
| 1718 | if (is_ext_connected) |
| 1719 | { |
| 1720 | // We can assume the M+ is settled on an attachment event. |
| 1721 | m_mplus_wait_time = Clock::now(); |
| 1722 | } |
| 1723 | else |
| 1724 | { |
| 1725 | // "Nunchuk" will be the most used mode and also works with no passthrough extension. |
| 1726 | m_mplus_desired_mode = MotionPlusState::PassthroughMode::Nunchuk; |
| 1727 | |
| 1728 | // If an extension is not connected the M+ is either disabled or resetting. |
| 1729 | m_mplus_state.current_mode = MotionPlusState::PassthroughMode{}; |
| 1730 | } |
| 1731 | } |
| 1732 | } |
| 1733 | |
| 1734 | } // namespace ciface::WiimoteController |