Debian Codegraph @

Source/Core/DolphinQt/Config/Mapping/MappingIndicator.cpp

raw symbols SCIP
1 // Copyright 2018 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "DolphinQt/Config/Mapping/MappingIndicator.h"
5
6 #include <array>
7 #include <cmath>
8 #include <numbers>
9
10 #include <fmt/format.h>
11
12 #include <QAction>
13 #include <QDateTime>
14 #include <QEasingCurve>
15 #include <QPainter>
16 #include <QPainterPath>
17
18 #include "Common/MathUtil.h"
19
20 #include "Core/HW/WiimoteEmu/Camera.h"
21
22 #include "InputCommon/ControllerEmu/Control/Control.h"
23 #include "InputCommon/ControllerEmu/ControlGroup/Cursor.h"
24 #include "InputCommon/ControllerEmu/ControlGroup/Force.h"
25 #include "InputCommon/ControllerEmu/ControlGroup/MixedTriggers.h"
26 #include "InputCommon/ControllerInterface/ControllerInterface.h"
27 #include "InputCommon/ControllerInterface/CoreDevice.h"
28 #include "InputCommon/ControllerInterface/MappingCommon.h"
29
30 #include "DolphinQt/Config/Mapping/MappingWidget.h"
31 #include "DolphinQt/Config/Mapping/MappingWindow.h"
32 #include "DolphinQt/Settings.h"
33
34 namespace
35 {
36 const QColor STICK_GATE_COLOR = Qt::lightGray;
37 const QColor C_STICK_GATE_COLOR = Qt::yellow;
38 const QColor CURSOR_TV_COLOR = 0xaed6f1;
39 const QColor TILT_GATE_COLOR = 0xa2d9ce;
40 const QColor SWING_GATE_COLOR = 0xcea2d9;
41
42 constexpr int INPUT_DOT_RADIUS = 2;
43
44 constexpr int NORMAL_INDICATOR_WIDTH = 100;
45 constexpr int NORMAL_INDICATOR_HEIGHT = 100;
46 constexpr int NORMAL_INDICATOR_PADDING = 2;
47
48 // Per trigger.
49 constexpr int TRIGGER_INDICATOR_HEIGHT = 32;
50
51 QPen GetCosmeticPen(QPen pen)
52 {
53 pen.setCosmetic(true);
54 return pen;
55 }
56
57 QPen GetInputDotPen(QPen pen)
58 {
59 pen.setWidth(INPUT_DOT_RADIUS * 2);
60 pen.setCapStyle(Qt::PenCapStyle::RoundCap);
61 return GetCosmeticPen(pen);
62 }
63
64 } // namespace
65
66 QPen MappingIndicator::GetBBoxPen() const
67 {
68 return QPen(palette().shadow().color(), 0);
69 }
70
71 QBrush MappingIndicator::GetBBoxBrush() const
72 {
73 return palette().base();
74 }
75
76 QColor MappingIndicator::GetRawInputColor() const
77 {
78 QColor color = palette().text().color();
79 color.setAlphaF(0.5);
80 return color;
81 }
82
83 QPen MappingIndicator::GetInputShapePen() const
84 {
85 return QPen{GetRawInputColor(), 0.0, Qt::DashLine};
86 }
87
88 QColor MappingIndicator::GetAdjustedInputColor() const
89 {
90 return Qt::red;
91 }
92
93 QColor MappingIndicator::GetCenterColor() const
94 {
95 return Qt::blue;
96 }
97
98 QColor MappingIndicator::GetDeadZoneColor() const
99 {
100 QColor color = Settings::Instance().IsThemeDark() ? Qt::white : Qt::black;
101 color.setAlphaF(0.25);
102 return color;
103 }
104
105 QPen MappingIndicator::GetDeadZonePen() const
106 {
107 return QPen(GetDeadZoneColor(), 0);
108 }
109
110 QBrush MappingIndicator::GetDeadZoneBrush(QPainter& painter) const
111 {
112 QBrush brush{GetDeadZoneColor(), Qt::FDiagPattern};
113 brush.setTransform(painter.transform().inverted());
114 return brush;
115 }
116
117 QColor MappingIndicator::GetTextColor() const
118 {
119 return palette().text().color();
120 }
121
122 // Text color that is visible atop GetAdjustedInputColor():
123 QColor MappingIndicator::GetAltTextColor() const
124 {
125 return palette().highlightedText().color();
126 }
127
128 void MappingIndicator::AdjustGateColor(QColor* color)
129 {
130 if (Settings::Instance().IsThemeDark())
131 color->setHsvF(color->hueF(), std::min(color->saturationF(), 0.5f), color->valueF() * 0.35f);
132 }
133
134 ButtonIndicator::ButtonIndicator(ControlReference* control_ref) : m_control_ref{control_ref}
135 {
136 setSizePolicy(QSizePolicy::Policy::Fixed, QSizePolicy::Policy::Fixed);
137 }
138
139 QSize ButtonIndicator::sizeHint() const
140 {
141 return QSize{INPUT_DOT_RADIUS + 2,
142 QFontMetrics(font()).boundingRect(QStringLiteral("[")).height()};
143 }
144
145 void ButtonIndicator::Draw()
146 {
147 QPainter p(this);
148 p.setBrush(GetBBoxBrush());
149 p.setPen(GetBBoxPen());
150 p.drawRect(QRect{{0, 0}, size() - QSize{1, 1}});
151
152 const auto input_value = std::clamp(m_control_ref->GetState<ControlState>(), 0.0, 1.0);
153 const bool is_pressed = std::lround(input_value) != 0;
154 QSizeF value_size = size() - QSizeF{2, 2};
155 value_size.setHeight(value_size.height() * input_value);
156
157 p.translate(0, height());
158 p.scale(1, -1);
159
160 p.setPen(Qt::NoPen);
161 p.setBrush(is_pressed ? GetAdjustedInputColor() : GetRawInputColor());
162 p.drawRect(QRectF{{1, 1}, value_size});
163 }
164
165 SquareIndicator::SquareIndicator()
166 {
167 // Additional pixel for border.
168 setFixedWidth(NORMAL_INDICATOR_WIDTH + (NORMAL_INDICATOR_PADDING + 1) * 2);
169 setFixedHeight(NORMAL_INDICATOR_HEIGHT + (NORMAL_INDICATOR_PADDING + 1) * 2);
170 }
171
172 MixedTriggersIndicator::MixedTriggersIndicator(ControllerEmu::MixedTriggers& group) : m_group(group)
173 {
174 setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Ignored);
175 setFixedHeight(TRIGGER_INDICATOR_HEIGHT * int(group.GetTriggerCount()) + 1);
176 }
177
178 namespace
179 {
180 constexpr float SPHERE_SIZE = 0.7f;
181 constexpr float SPHERE_INDICATOR_DIST = 0.85f;
182 constexpr int SPHERE_POINT_COUNT = 200;
183
184 // Constructs a polygon by querying a radius at varying angles:
185 template <typename F>
186 QPolygonF GetPolygonFromRadiusGetter(F&& radius_getter)
187 {
188 // A multiple of 8 (octagon) and enough points to be visibly pleasing:
189 constexpr int shape_point_count = 32;
190 QPolygonF shape{shape_point_count};
191
192 int p = 0;
193 for (auto& point : shape)
194 {
195 const double angle = MathUtil::TAU * p / shape.size();
196 const double radius = radius_getter(angle);
197
198 point = {std::cos(angle) * radius, std::sin(angle) * radius};
199 ++p;
200 }
201
202 return shape;
203 }
204
205 // Constructs a polygon by querying a radius at varying angles:
206 template <typename F>
207 QPolygonF GetPolygonSegmentFromRadiusGetter(F&& radius_getter, double direction,
208 double segment_size, double segment_depth)
209 {
210 constexpr int shape_point_count = 6;
211 QPolygonF shape{shape_point_count};
212
213 // We subtract from the provided direction angle so it's better
214 // to add Tau here to prevent a negative value instead of
215 // expecting the function call to be aware of this internal logic
216 const double center_angle = direction + MathUtil::TAU;
217 const double center_radius_outer = radius_getter(center_angle);
218 const double center_radius_inner = center_radius_outer - segment_depth;
219
220 const double lower_angle = center_angle - segment_size / 2;
221 const double lower_radius_outer = radius_getter(lower_angle);
222 const double lower_radius_inner = lower_radius_outer - segment_depth;
223
224 const double upper_angle = center_angle + segment_size / 2;
225 const double upper_radius_outer = radius_getter(upper_angle);
226 const double upper_radius_inner = upper_radius_outer - segment_depth;
227
228 shape[0] = {std::cos(lower_angle) * (lower_radius_inner),
229 std::sin(lower_angle) * (lower_radius_inner)};
230 shape[1] = {std::cos(center_angle) * (center_radius_inner),
231 std::sin(center_angle) * (center_radius_inner)};
232 shape[2] = {std::cos(upper_angle) * (upper_radius_inner),
233 std::sin(upper_angle) * (upper_radius_inner)};
234 shape[3] = {std::cos(upper_angle) * upper_radius_outer,
235 std::sin(upper_angle) * upper_radius_outer};
236 shape[4] = {std::cos(center_angle) * center_radius_outer,
237 std::sin(center_angle) * center_radius_outer};
238 shape[5] = {std::cos(lower_angle) * lower_radius_outer,
239 std::sin(lower_angle) * lower_radius_outer};
240
241 return shape;
242 }
243
244 // Used to test for a miscalibrated stick so the user can be informed.
245 bool IsPointOutsideCalibration(Common::DVec2 point, ControllerEmu::ReshapableInput& input)
246 {
247 const auto center = input.GetCenter();
248 const double current_radius = (point - center).Length();
249 const double input_radius = input.GetInputRadiusAtAngle(
250 std::atan2(point.y - center.y, point.x - center.x) + MathUtil::TAU);
251
252 constexpr double ALLOWED_ERROR = 1.3;
253
254 return current_radius > input_radius * ALLOWED_ERROR;
255 }
256
257 void DrawVirtualNotches(QPainter& p, ControllerEmu::ReshapableInput& stick, QColor notch_color)
258 {
259 const double segment_size = stick.GetVirtualNotchSize();
260 if (segment_size <= 0.0)
261 return;
262
263 p.setBrush(notch_color);
264 for (int i = 0; i < 8; ++i)
265 {
266 const double segment_depth = 1.0 - ControllerEmu::MINIMUM_NOTCH_DISTANCE;
267 const double segment_gap = MathUtil::TAU / 8.0;
268 const double direction = segment_gap * i;
269 p.drawPolygon(GetPolygonSegmentFromRadiusGetter(
270 [&stick](double ang) { return stick.GetGateRadiusAtAngle(ang); }, direction, segment_size,
271 segment_depth));
272 }
273 }
274
275 template <typename F>
276 void GenerateFibonacciSphere(int point_count, F&& callback)
277 {
278 const float golden_angle = MathUtil::PI * (3.f - std::sqrt(5.f));
279
280 for (int i = 0; i != point_count; ++i)
281 {
282 const float z = (1.f / point_count - 1.f) + (2.f / point_count) * i;
283 const float r = std::sqrt(1.f - z * z);
284 const float x = std::cos(golden_angle * i) * r;
285 const float y = std::sin(golden_angle * i) * r;
286
287 callback(Common::Vec3{x, y, z});
288 }
289 }
290
291 // Draws an analog stick pushed to the right by the provided amount.
292 void DrawPushedStick(QPainter& p, ReshapableInputIndicator& indicator, double value)
293 {
294 auto stick_color = indicator.GetGateBrushColor();
295 indicator.AdjustGateColor(&stick_color);
296 const auto stick_pen_color = stick_color.darker(125);
297 p.setPen(QPen{stick_pen_color, 0});
298 p.setBrush(stick_color);
299 constexpr float circle_radius = 0.65f;
300 p.drawEllipse(QPointF{value * 0.35f, 0.f}, circle_radius, circle_radius);
301
302 p.setPen(QPen{indicator.GetRawInputColor(), 0});
303 p.setBrush(Qt::NoBrush);
304 constexpr float alt_circle_radius = 0.45f;
305 p.drawEllipse(QPointF{value * 0.45f, 0.f}, alt_circle_radius, alt_circle_radius);
306 }
307
308 } // namespace
309
310 void MappingIndicator::paintEvent(QPaintEvent*)
311 {
312 constexpr float max_elapsed_seconds = 0.1f;
313
314 const auto now = Clock::now();
315 const float elapsed_seconds = std::chrono::duration_cast<DT_s>(now - m_last_update).count();
316 m_last_update = now;
317
318 const auto lock = ControllerEmu::EmulatedController::GetStateLock();
319 Update(std::min(elapsed_seconds, max_elapsed_seconds));
320 Draw();
321 }
322
323 QColor CursorIndicator::GetGateBrushColor() const
324 {
325 return CURSOR_TV_COLOR;
326 }
327
328 void CursorIndicator::Draw()
329 {
330 const auto adj_coord = m_cursor_group.GetState(true);
331
332 DrawReshapableInput(m_cursor_group,
333 adj_coord.IsVisible() ?
334 std::make_optional(Common::DVec2(adj_coord.x, adj_coord.y)) :
335 std::nullopt);
336 }
337
338 qreal SquareIndicator::GetContentsScale() const
339 {
340 return (NORMAL_INDICATOR_WIDTH - 1.0) / 2;
341 }
342
343 void SquareIndicator::DrawBoundingBox(QPainter& p)
344 {
345 p.setBrush(GetBBoxBrush());
346 p.setPen(GetBBoxPen());
347 p.drawRect(QRectF{NORMAL_INDICATOR_PADDING + 0.5, NORMAL_INDICATOR_PADDING + 0.5,
348 NORMAL_INDICATOR_WIDTH + 1.0, NORMAL_INDICATOR_HEIGHT + 1.0});
349 }
350
351 void SquareIndicator::TransformPainter(QPainter& p)
352 {
353 p.setRenderHint(QPainter::Antialiasing, true);
354 p.setRenderHint(QPainter::SmoothPixmapTransform, true);
355
356 p.translate(width() / 2.0, height() / 2.0);
357 const auto scale = GetContentsScale();
358 p.scale(scale, scale);
359 }
360
361 void ReshapableInputIndicator::DrawReshapableInput(
362 ControllerEmu::ReshapableInput& stick,
363 std::optional<ControllerEmu::ReshapableInput::ReshapeData> adj_coord)
364 {
365 QPainter p(this);
366 DrawBoundingBox(p);
367 TransformPainter(p);
368
369 // UI y-axis is opposite that of stick.
370 p.scale(1.0, -1.0);
371
372 const auto raw_coord = stick.GetReshapableState(false);
373
374 UpdateCalibrationWidget(raw_coord);
375
376 if (IsCalibrating())
377 {
378 m_calibration_widget->Draw(p, raw_coord);
379 return;
380 }
381
382 DrawUnderGate(p);
383
384 auto gate_brush_color = GetGateBrushColor();
385 auto gate_pen_color = gate_brush_color.darker(125);
386
387 AdjustGateColor(&gate_brush_color);
388 AdjustGateColor(&gate_pen_color);
389
390 // Input gate. (i.e. the octagon shape)
391 p.setPen(QPen(gate_pen_color, 0));
392 p.setBrush(gate_brush_color);
393 p.drawPolygon(
394 GetPolygonFromRadiusGetter([&stick](double ang) { return stick.GetGateRadiusAtAngle(ang); }));
395
396 DrawVirtualNotches(p, stick, gate_pen_color);
397
398 const auto center = stick.GetCenter();
399
400 p.save();
401 p.translate(center.x, center.y);
402
403 // Deadzone.
404 p.setPen(GetDeadZonePen());
405 p.setBrush(GetDeadZoneBrush(p));
406 p.drawPolygon(GetPolygonFromRadiusGetter(
407 [&stick](double ang) { return stick.GetDeadzoneRadiusAtAngle(ang); }));
408
409 // Input shape.
410 p.setPen(GetInputShapePen());
411 p.setBrush(Qt::NoBrush);
412 p.drawPolygon(GetPolygonFromRadiusGetter(
413 [&stick](double ang) { return stick.GetInputRadiusAtAngle(ang); }));
414
415 // Center.
416 if (center.x || center.y)
417 {
418 p.setPen(GetInputDotPen(GetCenterColor()));
419 p.drawPoint(QPointF{});
420 }
421
422 p.restore();
423
424 // Raw stick position.
425 p.setPen(GetInputDotPen(GetRawInputColor()));
426 p.drawPoint(QPointF{raw_coord.x, raw_coord.y});
427
428 // Adjusted stick position.
429 if (adj_coord)
430 {
431 p.setPen(GetInputDotPen(GetAdjustedInputColor()));
432 p.drawPoint(QPointF{adj_coord->x, adj_coord->y});
433 }
434 }
435
436 QColor AnalogStickIndicator::GetGateBrushColor() const
437 {
438 // Some hacks for pretty colors:
439 const bool is_c_stick = m_group.name == "C-Stick";
440
441 return is_c_stick ? C_STICK_GATE_COLOR : STICK_GATE_COLOR;
442 }
443
444 void AnalogStickIndicator::Draw()
445 {
446 const auto adj_coord = m_group.GetReshapableState(true);
447
448 DrawReshapableInput(m_group,
449 (adj_coord.x || adj_coord.y) ? std::make_optional(adj_coord) : std::nullopt);
450 }
451
452 void TiltIndicator::Update(float elapsed_seconds)
453 {
454 ReshapableInputIndicator::Update(elapsed_seconds);
455 WiimoteEmu::EmulateTilt(&m_motion_state, &m_group, elapsed_seconds);
456 }
457
458 QColor TiltIndicator::GetGateBrushColor() const
459 {
460 return TILT_GATE_COLOR;
461 }
462
463 void TiltIndicator::Draw()
464 {
465 auto adj_coord = Common::DVec2{-m_motion_state.angle.y, m_motion_state.angle.x} / MathUtil::PI;
466
467 // Angle values after dividing by pi.
468 constexpr auto norm_180_deg = 1;
469 constexpr auto norm_360_deg = 2;
470
471 // Angle may extend beyond 180 degrees when wrapping around.
472 // Apply modulo to draw within the indicator.
473 // Scale down the value a bit so +1 does not become -1.
474 adj_coord *= 0.9999f;
475 adj_coord.x = std::fmod(adj_coord.x + norm_360_deg + norm_180_deg, norm_360_deg) - norm_180_deg;
476 adj_coord.y = std::fmod(adj_coord.y + norm_360_deg + norm_180_deg, norm_360_deg) - norm_180_deg;
477
478 DrawReshapableInput(m_group,
479 (adj_coord.x || adj_coord.y) ? std::make_optional(adj_coord) : std::nullopt);
480 }
481
482 void MixedTriggersIndicator::Draw()
483 {
484 QPainter p(this);
485 p.setRenderHint(QPainter::TextAntialiasing, true);
486
487 const auto& triggers = m_group;
488 const ControlState threshold = triggers.GetThreshold();
489 const ControlState deadzone = triggers.GetDeadzone();
490
491 // MixedTriggers interface is a bit ugly:
492 constexpr int TRIGGER_COUNT = 2;
493 std::array<ControlState, TRIGGER_COUNT> raw_analog_state;
494 std::array<ControlState, TRIGGER_COUNT> adj_analog_state;
495 const std::array<u16, TRIGGER_COUNT> button_masks = {0x1, 0x2};
496 u16 button_state = 0;
497
498 triggers.GetState(&button_state, button_masks.data(), raw_analog_state.data(), false);
499 triggers.GetState(&button_state, button_masks.data(), adj_analog_state.data(), true);
500
501 // Rectangle sizes:
502 const int trigger_height = TRIGGER_INDICATOR_HEIGHT;
503 const int trigger_width = width() - 1;
504 const int trigger_button_width = trigger_height;
505 const int trigger_analog_width = trigger_width - trigger_button_width;
506
507 // Bounding box background:
508 p.setPen(Qt::NoPen);
509 p.setBrush(GetBBoxBrush());
510 p.drawRect(QRectF(0.5, 0.5, trigger_width, trigger_height * TRIGGER_COUNT));
511
512 for (int t = 0; t != TRIGGER_COUNT; ++t)
513 {
514 const double raw_analog = raw_analog_state[t];
515 const double adj_analog = adj_analog_state[t];
516 const bool trigger_button = button_state & button_masks[t];
517 auto const analog_name = QString::fromStdString(triggers.controls[TRIGGER_COUNT + t]->ui_name);
518 auto const button_name = QString::fromStdString(triggers.controls[t]->ui_name);
519
520 const QRectF trigger_rect(0.5, 0.5, trigger_width, trigger_height);
521
522 const QRectF analog_rect(0.5, 0.5, trigger_analog_width, trigger_height);
523
524 // Unactivated analog text:
525 p.setPen(GetTextColor());
526 p.drawText(analog_rect, Qt::AlignCenter, analog_name);
527
528 const QRectF adj_analog_rect(0.5, 0.5, adj_analog * trigger_analog_width, trigger_height);
529
530 // Trigger analog:
531 p.setPen(Qt::NoPen);
532 p.setBrush(GetAdjustedInputColor());
533 p.drawRect(adj_analog_rect);
534
535 p.setPen(GetInputDotPen(GetRawInputColor()));
536 p.drawPoint(QPoint(raw_analog * trigger_analog_width, trigger_height - INPUT_DOT_RADIUS));
537
538 // Deadzone:
539 p.setPen(GetDeadZonePen());
540 p.setBrush(GetDeadZoneBrush(p));
541 p.drawRect(QRectF(1.5, 1.5, trigger_analog_width * deadzone, trigger_height - 2));
542
543 // Threshold setting:
544 const int threshold_x = trigger_analog_width * threshold;
545 p.setPen(GetInputShapePen());
546 p.drawLine(threshold_x, 0, threshold_x, trigger_height);
547
548 const QRectF button_rect(trigger_analog_width + 0.5, 0.5, trigger_button_width, trigger_height);
549
550 // Trigger button:
551 p.setPen(GetBBoxPen());
552 p.setBrush(trigger_button ? GetAdjustedInputColor() : GetBBoxBrush());
553 p.drawRect(button_rect);
554
555 // Bounding box outline:
556 p.setPen(GetBBoxPen());
557 p.setBrush(Qt::NoBrush);
558 p.drawRect(trigger_rect);
559
560 // Button text:
561 p.setPen(GetTextColor());
562 p.setPen(trigger_button ? GetAltTextColor() : GetTextColor());
563 p.drawText(button_rect, Qt::AlignCenter, button_name);
564
565 // Activated analog text:
566 p.setPen(GetAltTextColor());
567 p.setClipping(true);
568 p.setClipRect(adj_analog_rect);
569 p.drawText(analog_rect, Qt::AlignCenter, analog_name);
570 p.setClipping(false);
571
572 // Move down for next trigger:
573 p.translate(0.0, trigger_height);
574 }
575 }
576
577 void SwingIndicator::DrawUnderGate(QPainter& p)
578 {
579 auto& force = m_swing_group;
580
581 // Deadzone for Z (forward/backward):
582 const double deadzone = force.GetDeadzonePercentage();
583 if (deadzone > 0.0)
584 {
585 p.setPen(GetDeadZonePen());
586 p.setBrush(GetDeadZoneBrush(p));
587 p.drawRect(QRectF(-1, -deadzone, 2, deadzone * 2));
588 }
589
590 // Raw Z:
591 const auto raw_coord = force.GetState(false);
592 p.setPen(GetCosmeticPen(QPen(GetRawInputColor(), INPUT_DOT_RADIUS)));
593 p.drawLine(QLineF(-1, raw_coord.z, 1, raw_coord.z));
594
595 // Adjusted Z:
596 const auto& adj_coord = m_motion_state.position;
597 const auto curve_point =
598 std::max(std::abs(m_motion_state.angle.x), std::abs(m_motion_state.angle.z)) / MathUtil::TAU;
599 if (adj_coord.y || curve_point)
600 {
601 // Show off the angle somewhat with a curved line.
602 QPainterPath path;
603 path.moveTo(-1.0, (adj_coord.y + curve_point) * -1);
604 path.quadTo({0, (adj_coord.y - curve_point) * -1}, {1, (adj_coord.y + curve_point) * -1});
605
606 p.setBrush(Qt::NoBrush);
607 p.setPen(GetCosmeticPen(QPen(GetAdjustedInputColor(), INPUT_DOT_RADIUS)));
608 p.drawPath(path);
609 }
610 }
611
612 void SwingIndicator::Update(float elapsed_seconds)
613 {
614 ReshapableInputIndicator::Update(elapsed_seconds);
615 WiimoteEmu::EmulateSwing(&m_motion_state, &m_swing_group, elapsed_seconds);
616 }
617
618 QColor SwingIndicator::GetGateBrushColor() const
619 {
620 return SWING_GATE_COLOR;
621 }
622
623 void SwingIndicator::Draw()
624 {
625 DrawReshapableInput(m_swing_group,
626 Common::DVec2{-m_motion_state.position.x, m_motion_state.position.z});
627 }
628
629 void ShakeMappingIndicator::Update(float elapsed_seconds)
630 {
631 WiimoteEmu::EmulateShake(&m_motion_state, &m_shake_group, elapsed_seconds);
632
633 for (auto& sample : m_position_samples)
634 sample.age += elapsed_seconds;
635
636 m_position_samples.erase(
637 std::ranges::find_if(m_position_samples,
638 [](const ShakeSample& sample) { return sample.age > 1.f; }),
639 m_position_samples.end());
640
641 constexpr float MAX_DISTANCE = 0.5f;
642
643 m_position_samples.push_front(ShakeSample{m_motion_state.position / MAX_DISTANCE});
644
645 const bool any_non_zero_samples = std::ranges::any_of(
646 m_position_samples, [](const ShakeSample& s) { return s.state.LengthSquared() != 0.0; });
647
648 // Only start moving the line if there's non-zero data.
649 if (m_grid_line_position || any_non_zero_samples)
650 {
651 m_grid_line_position += elapsed_seconds;
652
653 if (m_grid_line_position > 1.f)
654 {
655 if (any_non_zero_samples)
656 m_grid_line_position = std::fmod(m_grid_line_position, 1.f);
657 else
658 m_grid_line_position = 0;
659 }
660 }
661 }
662
663 void ShakeMappingIndicator::Draw()
664 {
665 QPainter p(this);
666 DrawBoundingBox(p);
667 TransformPainter(p);
668
669 // UI y-axis is opposite that of acceleration Z.
670 p.scale(1.0, -1.0);
671
672 // Deadzone.
673 const double deadzone = m_shake_group.GetDeadzone();
674 if (deadzone > 0.0)
675 {
676 p.setPen(GetDeadZonePen());
677 p.setBrush(GetDeadZoneBrush(p));
678 p.drawRect(QRectF(-1, 0, 2, deadzone));
679 }
680
681 // Raw input.
682 const auto raw_coord = m_shake_group.GetState(false);
683 p.setPen(GetInputDotPen(GetRawInputColor()));
684 for (std::size_t c = 0; c != raw_coord.data.size(); ++c)
685 {
686 p.drawPoint(QPointF{-0.5 + c * 0.5, raw_coord.data[c]});
687 }
688
689 const double grid_line_x = 1.0 - m_grid_line_position * 2.0;
690 p.setPen(QPen(GetRawInputColor(), 0));
691 p.drawLine(QPointF{grid_line_x, -1.0}, QPointF{grid_line_x, 1.0});
692
693 // Position history.
694 const QColor component_colors[] = {Qt::blue, Qt::green, Qt::red};
695 p.setBrush(Qt::NoBrush);
696 for (std::size_t c = 0; c != raw_coord.data.size(); ++c)
697 {
698 QPolygonF polyline;
699
700 for (auto& sample : m_position_samples)
701 polyline.append(QPointF{1.0 - sample.age * 2.0, sample.state.data[c]});
702
703 p.setPen(QPen(component_colors[c], 0));
704 p.drawPolyline(polyline);
705 }
706 }
707
708 void AccelerometerMappingIndicator::Draw()
709 {
710 const auto accel_state = m_accel_group.GetState();
711 const auto state = accel_state.value_or(Common::Vec3{});
712
713 QPainter p(this);
714 p.setRenderHint(QPainter::TextAntialiasing, true);
715 DrawBoundingBox(p);
716 TransformPainter(p);
717
718 // UI axes are opposite that of Wii remote accelerometer.
719 p.scale(-1.0, -1.0);
720
721 const auto rotation = WiimoteEmu::GetRotationFromAcceleration(state);
722
723 // Draw sphere.
724 p.setPen(GetCosmeticPen(QPen(GetRawInputColor(), 0.5)));
725
726 GenerateFibonacciSphere(SPHERE_POINT_COUNT, [&](const Common::Vec3& point) {
727 const auto pt = rotation * point;
728
729 if (pt.y > 0)
730 p.drawPoint(QPointF(pt.x, pt.z) * SPHERE_SIZE);
731 });
732
733 // Sphere outline.
734 p.setPen(QPen(GetRawInputColor(), 0));
735 p.setBrush(Qt::NoBrush);
736 p.drawEllipse(QPointF{}, SPHERE_SIZE, SPHERE_SIZE);
737
738 p.setPen(Qt::NoPen);
739
740 // Red dot.
741 const auto point = rotation * Common::Vec3{0, 0, SPHERE_INDICATOR_DIST};
742 if (point.y > 0 || Common::Vec2(point.x, point.z).Length() > SPHERE_SIZE)
743 {
744 p.setPen(GetInputDotPen(GetAdjustedInputColor()));
745 p.drawPoint(QPointF(point.x, point.z));
746 }
747
748 // Blue dot.
749 const auto point2 = -point;
750 if (point2.y > 0 || Common::Vec2(point2.x, point2.z).Length() > SPHERE_SIZE)
751 {
752 p.setPen(GetInputDotPen(GetCenterColor()));
753 p.drawPoint(QPointF(point2.x, point2.z));
754 }
755
756 p.setBrush(Qt::NoBrush);
757
758 p.resetTransform();
759 p.translate(width() / 2.0, height() / 2.0);
760
761 // Red dot upright target.
762 p.setPen(GetAdjustedInputColor());
763 p.drawEllipse(QPointF{0, -SPHERE_INDICATOR_DIST} * GetContentsScale(), INPUT_DOT_RADIUS,
764 INPUT_DOT_RADIUS);
765
766 // Blue dot target.
767 p.setPen(GetCenterColor());
768 p.drawEllipse(QPointF{0, SPHERE_INDICATOR_DIST} * GetContentsScale(), INPUT_DOT_RADIUS,
769 INPUT_DOT_RADIUS);
770
771 // Only draw g-force text if acceleration data is present.
772 if (!accel_state.has_value())
773 return;
774
775 // G-force text:
776 p.setPen(GetTextColor());
777 p.drawText(QRect(0, 0, NORMAL_INDICATOR_WIDTH / 2 - 2, NORMAL_INDICATOR_HEIGHT / 2 - 1),
778 Qt::AlignBottom | Qt::AlignRight,
779 QString::fromStdString(
780 // i18n: "g" is the symbol for "gravitational force equivalent" (g-force).
781 fmt::format("{:.2f} g", state.Length() / WiimoteEmu::GRAVITY_ACCELERATION)));
782 }
783
784 void GyroMappingIndicator::Update(float elapsed_seconds)
785 {
786 const auto gyro_state = m_gyro_group.GetState();
787 const auto angular_velocity = gyro_state.value_or(Common::Vec3{});
788 m_state *= WiimoteEmu::GetRotationFromGyroscope(angular_velocity * Common::Vec3(-1, +1, -1) *
789 elapsed_seconds);
790 m_state = m_state.Normalized();
791
792 // Reset orientation when stable for a bit:
793 constexpr float STABLE_RESET_SECONDS = 1.f;
794 // Consider device stable when data (with deadzone applied) is zero.
795 const bool is_stable = !angular_velocity.LengthSquared();
796
797 if (!is_stable)
798 m_stable_time = 0;
799 else if (m_stable_time < STABLE_RESET_SECONDS)
800 m_stable_time += elapsed_seconds;
801
802 if (m_stable_time >= STABLE_RESET_SECONDS)
803 m_state = Common::Quaternion::Identity();
804 }
805
806 void GyroMappingIndicator::Draw()
807 {
808 const auto gyro_state = m_gyro_group.GetState();
809 const auto raw_gyro_state = m_gyro_group.GetRawState();
810 const auto angular_velocity = gyro_state.value_or(Common::Vec3{});
811 const auto jitter = raw_gyro_state - m_previous_velocity;
812 m_previous_velocity = raw_gyro_state;
813
814 // Consider device stable when data (with deadzone applied) is zero.
815 const bool is_stable = !angular_velocity.LengthSquared();
816
817 // Use an empty rotation matrix if gyroscope data is not present.
818 const auto rotation =
819 (gyro_state.has_value() ? Common::Matrix33::FromQuaternion(m_state) : Common::Matrix33{});
820
821 QPainter p(this);
822 DrawBoundingBox(p);
823 TransformPainter(p);
824
825 // Deadzone.
826 if (const auto deadzone_value = m_gyro_group.GetDeadzone(); deadzone_value)
827 {
828 static constexpr auto DEADZONE_DRAW_SIZE = 1 - SPHERE_SIZE;
829 static constexpr auto DEADZONE_DRAW_BOTTOM = 1;
830
831 p.setPen(GetDeadZonePen());
832 p.setBrush(GetDeadZoneBrush(p));
833 p.drawRect(QRectF{-1, DEADZONE_DRAW_BOTTOM, 2, -DEADZONE_DRAW_SIZE});
834
835 if (gyro_state.has_value())
836 {
837 const auto max_jitter =
838 std::max({std::abs(jitter.x), std::abs(jitter.y), std::abs(jitter.z)});
839 const auto jitter_line_y =
840 std::min(max_jitter / deadzone_value * DEADZONE_DRAW_SIZE - DEADZONE_DRAW_BOTTOM, 1.0);
841 p.setPen(GetCosmeticPen(QPen(GetRawInputColor(), INPUT_DOT_RADIUS)));
842 p.drawLine(QLineF(-1.0, jitter_line_y * -1.0, 1.0, jitter_line_y * -1.0));
843
844 // Sphere background.
845 p.setPen(Qt::NoPen);
846 p.setBrush(GetBBoxBrush());
847 p.drawEllipse(QPointF{}, SPHERE_SIZE, SPHERE_SIZE);
848 }
849 }
850
851 // Sphere dots.
852 p.setPen(GetCosmeticPen(QPen(GetRawInputColor(), 0.5)));
853
854 GenerateFibonacciSphere(SPHERE_POINT_COUNT, [&](const Common::Vec3& point) {
855 const auto pt = rotation * point;
856
857 if (pt.y > 0)
858 p.drawPoint(QPointF(pt.x, pt.z) * SPHERE_SIZE);
859 });
860
861 // Sphere outline.
862 const auto outline_color =
863 is_stable ? (m_gyro_group.IsCalibrating() ? GetCenterColor() : GetRawInputColor()) :
864 GetAdjustedInputColor();
865 p.setPen(QPen(outline_color, 0));
866 p.setBrush(Qt::NoBrush);
867 p.drawEllipse(QPointF{}, SPHERE_SIZE, SPHERE_SIZE);
868
869 p.setPen(Qt::NoPen);
870
871 // Red dot.
872 const auto point = rotation * Common::Vec3{0, 0, -SPHERE_INDICATOR_DIST};
873 if (point.y > 0 || Common::Vec2(point.x, point.z).Length() > SPHERE_SIZE)
874 {
875 p.setPen(GetInputDotPen(GetAdjustedInputColor()));
876 p.drawPoint(QPointF(point.x, point.z));
877 }
878 // Blue dot.
879 const auto point2 = rotation * Common::Vec3{0, SPHERE_INDICATOR_DIST, 0};
880 if (point2.y > 0 || Common::Vec2(point2.x, point2.z).Length() > SPHERE_SIZE)
881 {
882 p.setPen(GetInputDotPen(GetCenterColor()));
883 p.drawPoint(QPointF(point2.x, point2.z));
884 }
885
886 p.setBrush(Qt::NoBrush);
887
888 p.resetTransform();
889 p.translate(width() / 2.0, height() / 2.0);
890
891 // Red dot upright target.
892 p.setPen(GetAdjustedInputColor());
893 p.drawEllipse(QPointF{0, -SPHERE_INDICATOR_DIST} * GetContentsScale(), INPUT_DOT_RADIUS,
894 INPUT_DOT_RADIUS);
895
896 // Blue dot target.
897 p.setPen(GetCenterColor());
898 p.drawEllipse(QPointF{}, INPUT_DOT_RADIUS, INPUT_DOT_RADIUS);
899 }
900
901 void IRPassthroughMappingIndicator::Draw()
902 {
903 QPainter p(this);
904 DrawBoundingBox(p);
905 TransformPainter(p);
906
907 p.scale(1.0, -1.0);
908
909 auto pen =
910 GetInputDotPen(m_ir_group.enabled.GetValue() ? GetAdjustedInputColor() : GetRawInputColor());
911
912 for (std::size_t i = 0; i != WiimoteEmu::CameraLogic::NUM_POINTS; ++i)
913 {
914 const auto size = m_ir_group.GetObjectSize(i);
915
916 const bool is_visible = size > 0;
917 if (!is_visible)
918 continue;
919
920 const auto point =
921 (QPointF{m_ir_group.GetObjectPositionX(i), m_ir_group.GetObjectPositionY(i)} -
922 QPointF{0.5, 0.5}) *
923 2.0;
924
925 pen.setWidth(size * NORMAL_INDICATOR_WIDTH / 2);
926 p.setPen(pen);
927 p.drawPoint(point);
928 }
929 }
930
931 void CalibrationWidget::Draw(QPainter& p, Common::DVec2 point)
932 {
933 DrawInProgressMapping(p);
934 DrawInProgressCalibration(p, point);
935 }
936
937 double CalibrationWidget::GetAnimationElapsedSeconds() const
938 {
939 return DT_s{Clock::now() - m_animation_start_time}.count();
940 }
941
942 void CalibrationWidget::RestartAnimation()
943 {
944 m_animation_start_time = Clock::now();
945 }
946
947 void CalibrationWidget::DrawInProgressMapping(QPainter& p)
948 {
949 if (!IsMapping())
950 return;
951
952 p.rotate(qRadiansToDegrees(m_mapper->GetCurrentAngle()));
953
954 const auto ping_pong = 1 - std::abs(1 - (2 * std::fmod(GetAnimationElapsedSeconds(), 1)));
955
956 // Stick.
957 DrawPushedStick(p, m_indicator,
958 QEasingCurve(QEasingCurve::OutBounce).valueForProgress(ping_pong));
959
960 // Arrow.
961 p.save();
962 const auto triangle_x =
963 (QEasingCurve(QEasingCurve::InOutQuart).valueForProgress(ping_pong) * 0.3) + 0.1;
964 p.translate(triangle_x, 0.0);
965
966 // An equilateral triangle.
967 constexpr auto triangle_h = 0.2f;
968 constexpr auto triangle_w_2 = triangle_h / std::numbers::sqrt3_v<float>;
969
970 p.setPen(Qt::NoPen);
971 p.setBrush(m_indicator.GetRawInputColor());
972 p.drawPolygon(QPolygonF{{triangle_h, 0.f}, {0.f, -triangle_w_2}, {0.f, +triangle_w_2}});
973
974 p.restore();
975 }
976
977 void CalibrationWidget::DrawInProgressCalibration(QPainter& p, Common::DVec2 point)
978 {
979 if (!IsCalibrating())
980 return;
981
982 const auto elapsed_seconds = GetAnimationElapsedSeconds();
983
984 const auto stop_spinning_amount =
985 std::max(DT_s{m_stop_spinning_time - Clock::now()} / STOP_SPINNING_DURATION, 0.0);
986
987 const auto stick_pushed_amount =
988 QEasingCurve(QEasingCurve::OutCirc).valueForProgress(std::min(elapsed_seconds * 2, 1.0)) *
989 stop_spinning_amount;
990
991 // Clockwise spinning stick starting from center.
992 p.save();
993 p.rotate(elapsed_seconds * -360.0);
994 DrawPushedStick(p, m_indicator, -stick_pushed_amount);
995 p.restore();
996
997 const auto center = m_calibrator->GetCenter();
998 p.save();
999 p.translate(center.x, center.y);
1000
1001 // Input shape.
1002 p.setPen(m_indicator.GetInputShapePen());
1003 p.setBrush(Qt::NoBrush);
1004 p.drawPolygon(GetPolygonFromRadiusGetter(
1005 [this](double angle) { return m_calibrator->GetCalibrationRadiusAtAngle(angle); }));
1006
1007 // Calibrated center.
1008 if (center.x || center.y)
1009 {
1010 p.setPen(GetInputDotPen(m_indicator.GetCenterColor()));
1011 p.drawPoint(QPointF{});
1012 }
1013 p.restore();
1014
1015 // Show the red dot only if the input is at least halfway pressed.
1016 // The cool spinning stick is otherwise uglified by the red dot always being shown.
1017 if (Common::DVec2{point.x, point.y}.LengthSquared() > (0.5 * 0.5))
1018 {
1019 p.setPen(GetInputDotPen(m_indicator.GetAdjustedInputColor()));
1020 p.drawPoint(QPointF{point.x, point.y});
1021 }
1022 }
1023
1024 void ReshapableInputIndicator::UpdateCalibrationWidget(Common::DVec2 point)
1025 {
1026 if (m_calibration_widget != nullptr)
1027 m_calibration_widget->Update(point);
1028 }
1029
1030 bool ReshapableInputIndicator::IsCalibrating() const
1031 {
1032 return m_calibration_widget != nullptr && m_calibration_widget->IsActive();
1033 }
1034
1035 void ReshapableInputIndicator::SetCalibrationWidget(CalibrationWidget* widget)
1036 {
1037 m_calibration_widget = widget;
1038 }
1039
1040 CalibrationWidget::CalibrationWidget(MappingWidget& mapping_widget,
1041 ControllerEmu::ReshapableInput& input,
1042 ReshapableInputIndicator& indicator)
1043 : m_mapping_widget(mapping_widget), m_input(input), m_indicator(indicator)
1044 {
1045 connect(mapping_widget.GetParent(), &MappingWindow::CancelMapping, this,
1046 &CalibrationWidget::ResetActions);
1047 connect(mapping_widget.GetParent(), &MappingWindow::ConfigChanged, this,
1048 &CalibrationWidget::ResetActions);
1049
1050 m_indicator.SetCalibrationWidget(this);
1051
1052 // Make it more apparent that this is a menu with more options.
1053 setPopupMode(ToolButtonPopupMode::MenuButtonPopup);
1054
1055 setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
1056
1057 ResetActions();
1058 }
1059
1060 void CalibrationWidget::DeleteAllActions()
1061 {
1062 for (auto* action : actions())
1063 delete action;
1064 }
1065
1066 void CalibrationWidget::ResetActions()
1067 {
1068 m_calibrator.reset();
1069 m_mapper.reset();
1070
1071 // i18n: A button to start the process of game controller analog stick mapping and calibration.
1072 auto* const map_and_calibrate_action = new QAction(tr("Map and Calibrate"), this);
1073
1074 // i18n: A button to start the process of game controller analog stick calibration.
1075 auto* const calibrate_action = new QAction(tr("Calibrate"), this);
1076
1077 // i18n: A button to calibrate the center and extremities of a game controller analog stick.
1078 auto* const center_action = new QAction(tr("Center and Calibrate"), this);
1079
1080 // i18n: A button to reset game controller analog stick calibration.
1081 auto* const reset_action = new QAction(tr("Reset Calibration"), this);
1082
1083 connect(map_and_calibrate_action, &QAction::triggered, this,
1084 &CalibrationWidget::StartMappingAndCalibration);
1085 connect(calibrate_action, &QAction::triggered, this, [this]() { StartCalibration(); });
1086 connect(center_action, &QAction::triggered, this, [this]() { StartCalibration(std::nullopt); });
1087 connect(reset_action, &QAction::triggered, this, [this]() {
1088 const auto lock = m_mapping_widget.GetController()->GetStateLock();
1089 m_input.SetCalibrationToDefault();
1090 m_input.SetCenter({});
1091 });
1092
1093 DeleteAllActions();
1094
1095 addAction(map_and_calibrate_action);
1096 addAction(calibrate_action);
1097 addAction(center_action);
1098 addAction(reset_action);
1099
1100 setDefaultAction(map_and_calibrate_action);
1101 }
1102
1103 void CalibrationWidget::StartMappingAndCalibration()
1104 {
1105 RestartAnimation();
1106
1107 // i18n: A button to stop a game controller button mapping process.
1108 auto* const cancel_action = new QAction(tr("Cancel Mapping"), this);
1109 connect(cancel_action, &QAction::triggered, this, &CalibrationWidget::ResetActions);
1110
1111 DeleteAllActions();
1112
1113 addAction(cancel_action);
1114 setDefaultAction(cancel_action);
1115
1116 auto* const window = m_mapping_widget.GetParent();
1117 const auto& default_device = window->GetController()->GetDefaultDevice();
1118
1119 std::vector device_strings{default_device.ToString()};
1120 if (window->IsCreateOtherDeviceMappingsEnabled())
1121 device_strings = g_controller_interface.GetAllDeviceStrings();
1122
1123 const auto lock = window->GetController()->GetStateLock();
1124 m_mapper = std::make_unique<ciface::MappingCommon::ReshapableInputMapper>(g_controller_interface,
1125 device_strings);
1126 }
1127
1128 void CalibrationWidget::StartCalibration(std::optional<Common::DVec2> center)
1129 {
1130 RestartAnimation();
1131 m_calibrator = std::make_unique<ciface::MappingCommon::CalibrationBuilder>(center);
1132
1133 // i18n: A button to abort a game controller calibration process.
1134 auto* const cancel_action = new QAction(tr("Cancel Calibration"), this);
1135 connect(cancel_action, &QAction::triggered, this, &CalibrationWidget::ResetActions);
1136
1137 // i18n: A button to finalize a game controller calibration process.
1138 auto* const finish_action = new QAction(tr("Finish Calibration"), this);
1139 connect(finish_action, &QAction::triggered, this, &CalibrationWidget::FinishCalibration);
1140
1141 DeleteAllActions();
1142
1143 addAction(finish_action);
1144 addAction(cancel_action);
1145 setDefaultAction(cancel_action);
1146 }
1147
1148 void CalibrationWidget::FinishCalibration()
1149 {
1150 const auto lock = m_mapping_widget.GetController()->GetStateLock();
1151 m_calibrator->ApplyResults(&m_input);
1152 ResetActions();
1153 }
1154
1155 void CalibrationWidget::Update(Common::DVec2 point)
1156 {
1157 // FYI: The "StateLock" is always held when this is called.
1158
1159 QFont f = parentWidget()->font();
1160 QPalette p = parentWidget()->palette();
1161
1162 if (IsMapping())
1163 {
1164 if (m_mapper->Update())
1165 {
1166 // Restart the animation for the next direction when progress is made.
1167 RestartAnimation();
1168 }
1169
1170 if (m_mapper->IsComplete())
1171 {
1172 const bool needs_calibration = m_mapper->IsCalibrationNeeded();
1173
1174 if (m_mapper->ApplyResults(m_mapping_widget.GetController(), &m_input))
1175 {
1176 emit m_mapping_widget.ConfigChanged();
1177
1178 if (needs_calibration)
1179 {
1180 StartCalibration();
1181 }
1182 else
1183 {
1184 // Load square calibration for digital inputs.
1185 m_input.SetCalibrationFromGate(ControllerEmu::SquareStickGate{1});
1186 m_input.SetCenter({});
1187
1188 ResetActions();
1189 }
1190 }
1191 else
1192 {
1193 ResetActions();
1194 }
1195
1196 m_mapper.reset();
1197 }
1198 }
1199 else if (IsCalibrating())
1200 {
1201 m_calibrator->Update(point);
1202
1203 if (!m_calibrator->IsCalibrationDataSensible())
1204 {
1205 m_stop_spinning_time = Clock::now() + STOP_SPINNING_DURATION;
1206 }
1207 else if (m_calibrator->IsComplete())
1208 {
1209 FinishCalibration();
1210 }
1211 }
1212 else if (IsPointOutsideCalibration(point, m_input))
1213 {
1214 // Bold and red on miscalibration.
1215 f.setBold(true);
1216 p.setColor(QPalette::ButtonText, Qt::red);
1217 }
1218
1219 setFont(f);
1220 setPalette(p);
1221 }
1222
1223 bool CalibrationWidget::IsActive() const
1224 {
1225 return IsMapping() || IsCalibrating();
1226 }
1227
1228 bool CalibrationWidget::IsMapping() const
1229 {
1230 return m_mapper != nullptr;
1231 }
1232
1233 bool CalibrationWidget::IsCalibrating() const
1234 {
1235 return m_calibrator != nullptr;
1236 }