Debian Codegraph @

Source/Core/InputCommon/ControllerEmu/StickGate.cpp

raw symbols SCIP
1 // Copyright 2018 Dolphin Emulator Project
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "InputCommon/ControllerEmu/StickGate.h"
5
6 #include <algorithm>
7 #include <cmath>
8 #include <ranges>
9
10 #include <fmt/format.h>
11 #include <fmt/ranges.h>
12
13 #include "Common/MathUtil.h"
14 #include "Common/Matrix.h"
15 #include "Common/StringUtil.h"
16 #include "InputCommon/ControllerEmu/Control/Control.h"
17 #include "InputCommon/ControllerEmu/Setting/NumericSetting.h"
18
19 namespace
20 {
21 constexpr auto CALIBRATION_CONFIG_NAME = "Calibration";
22 constexpr auto CALIBRATION_DEFAULT_VALUE = 1.0;
23 constexpr auto CALIBRATION_CONFIG_SCALE = 100;
24
25 constexpr auto CENTER_CONFIG_NAME = "Center";
26 constexpr auto CENTER_CONFIG_SCALE = 100;
27
28 // Calculate distance to intersection of a ray with a line segment defined by two points.
29 std::optional<double> GetRayLineIntersection(Common::DVec2 ray, Common::DVec2 point1,
30 Common::DVec2 point2)
31 {
32 const auto diff = point2 - point1;
33
34 const auto dot = diff.Dot({-ray.y, ray.x});
35 if (std::abs(dot) < 0.00001)
36 {
37 // Both points are on top of each other.
38 return std::nullopt;
39 }
40
41 const auto segment_position = point1.Dot({ray.y, -ray.x}) / dot;
42 if (segment_position < -0.00001 || segment_position > 1.00001)
43 {
44 // Ray does not pass through segment.
45 return std::nullopt;
46 }
47
48 return diff.Cross(-point1) / dot;
49 }
50
51 double GetNearestNotch(double angle, double virtual_notch_angle)
52 {
53 constexpr auto sides = 8;
54 constexpr auto rounding = MathUtil::TAU / sides;
55 const auto closest_notch = std::round(angle / rounding) * rounding;
56 const auto angle_diff =
57 std::fmod(angle - closest_notch + MathUtil::PI, MathUtil::TAU) - MathUtil::PI;
58 return std::abs(angle_diff) < virtual_notch_angle / 2 ? closest_notch : angle;
59 }
60
61 Common::DVec2 GetPointFromAngleAndLength(double angle, double length)
62 {
63 return Common::DVec2{std::cos(angle), std::sin(angle)} * length;
64 }
65 } // namespace
66
67 namespace ControllerEmu
68 {
69 constexpr int ReshapableInput::CALIBRATION_SAMPLE_COUNT;
70
71 std::optional<u32> StickGate::GetIdealCalibrationSampleCount() const
72 {
73 return std::nullopt;
74 }
75
76 OctagonStickGate::OctagonStickGate(ControlState radius) : m_radius(radius)
77 {
78 }
79
80 ControlState OctagonStickGate::GetRadiusAtAngle(double angle) const
81 {
82 constexpr int sides = 8;
83 constexpr double sum_int_angles = (sides - 2) * MathUtil::PI;
84 constexpr double half_int_angle = sum_int_angles / sides / 2;
85
86 angle = std::fmod(angle, MathUtil::TAU / sides);
87 // Solve ASA triangle using The Law of Sines:
88 return m_radius / std::sin(MathUtil::PI - angle - half_int_angle) * std::sin(half_int_angle);
89 }
90
91 std::optional<u32> OctagonStickGate::GetIdealCalibrationSampleCount() const
92 {
93 return 8;
94 }
95
96 RoundStickGate::RoundStickGate(ControlState radius) : m_radius(radius)
97 {
98 }
99
100 ControlState RoundStickGate::GetRadiusAtAngle(double) const
101 {
102 return m_radius;
103 }
104
105 std::optional<u32> RoundStickGate::GetIdealCalibrationSampleCount() const
106 {
107 // The "radius" is the same at every angle so a single sample is enough.
108 return 1;
109 }
110
111 SquareStickGate::SquareStickGate(ControlState half_width) : m_half_width(half_width)
112 {
113 }
114
115 ControlState SquareStickGate::GetRadiusAtAngle(double angle) const
116 {
117 constexpr double section_angle = MathUtil::TAU / 4;
118 return m_half_width /
119 std::cos(std::fmod(angle + section_angle / 2, section_angle) - section_angle / 2);
120 }
121
122 std::optional<u32> SquareStickGate::GetIdealCalibrationSampleCount() const
123 {
124 // Because angle:0 points to the right we must use 8 samples for our square.
125 return 8;
126 }
127
128 ReshapableInput::ReshapableInput(std::string name_, std::string ui_name_, GroupType type_)
129 : ControlGroup(std::move(name_), std::move(ui_name_), type_)
130 {
131 // 50 is not always enough but users can set it to more with an expression
132 AddDeadzoneSetting(&m_deadzone_setting, 50);
133 }
134
135 ControlState ReshapableInput::GetDeadzoneRadiusAtAngle(double angle) const
136 {
137 // FYI: deadzone is scaled by input radius which allows the shape to match.
138 return GetInputRadiusAtAngle(angle) * GetDeadzonePercentage();
139 }
140
141 ControlState ReshapableInput::GetInputRadiusAtAngle(double angle) const
142 {
143 // Handle the "default" state.
144 if (m_calibration.empty())
145 {
146 return GetDefaultInputRadiusAtAngle(angle);
147 }
148
149 return GetCalibrationDataRadiusAtAngle(m_calibration, angle);
150 }
151
152 ControlState ReshapableInput::GetDeadzonePercentage() const
153 {
154 return m_deadzone_setting.GetValue() / 100;
155 }
156
157 ControlState ReshapableInput::GetCalibrationDataRadiusAtAngle(const CalibrationData& data,
158 double angle)
159 {
160 const auto sample_pos = angle / MathUtil::TAU * data.size();
161 // Interpolate the radius between 2 calibration samples.
162 const u32 sample1_index = u32(sample_pos) % data.size();
163 const u32 sample2_index = (sample1_index + 1) % data.size();
164 const double sample1_angle = sample1_index * MathUtil::TAU / data.size();
165 const double sample2_angle = sample2_index * MathUtil::TAU / data.size();
166
167 const auto intersection =
168 GetRayLineIntersection(GetPointFromAngleAndLength(angle, 1.0),
169 GetPointFromAngleAndLength(sample1_angle, data[sample1_index]),
170 GetPointFromAngleAndLength(sample2_angle, data[sample2_index]));
171
172 // Intersection has no value when points are on top of each other.
173 return intersection.value_or(data[sample1_index]);
174 }
175
176 ControlState ReshapableInput::GetDefaultInputRadiusAtAngle(double angle) const
177 {
178 // This will normally be the same as the gate radius.
179 // Unless a sub-class is doing weird things with the gate radius (e.g. Tilt)
180 return GetGateRadiusAtAngle(angle);
181 }
182
183 void ReshapableInput::SetCalibrationToDefault()
184 {
185 m_calibration.clear();
186 }
187
188 void ReshapableInput::SetCalibrationFromGate(const StickGate& gate)
189 {
190 m_calibration.resize(gate.GetIdealCalibrationSampleCount().value_or(CALIBRATION_SAMPLE_COUNT));
191
192 u32 i = 0;
193 for (auto& val : m_calibration)
194 val = gate.GetRadiusAtAngle(MathUtil::TAU * i++ / m_calibration.size());
195 }
196
197 void ReshapableInput::UpdateCalibrationData(CalibrationData& data, Common::DVec2 point1,
198 Common::DVec2 point2)
199 {
200 for (u32 i = 0; i != data.size(); ++i)
201 {
202 const auto angle = i * MathUtil::TAU / data.size();
203 const auto intersection =
204 GetRayLineIntersection(GetPointFromAngleAndLength(angle, 1.0), point1, point2);
205
206 data[i] = std::max(data[i], intersection.value_or(data[i]));
207 }
208 }
209
210 const ReshapableInput::CalibrationData& ReshapableInput::GetCalibrationData() const
211 {
212 return m_calibration;
213 }
214
215 void ReshapableInput::SetCalibrationData(CalibrationData data)
216 {
217 m_calibration = std::move(data);
218 }
219
220 const ReshapableInput::ReshapeData& ReshapableInput::GetCenter() const
221 {
222 return m_center;
223 }
224
225 void ReshapableInput::SetCenter(ReshapableInput::ReshapeData center)
226 {
227 m_center = center;
228 }
229
230 void ReshapableInput::LoadConfig(Common::IniFile::Section* section, const std::string& base_name)
231 {
232 ControlGroup::LoadConfig(section, base_name);
233
234 const std::string group(base_name + name + '/');
235
236 // Special handling for "Modifier" button "Range" settings which default to 50% instead of 100%.
237 if (const auto* modifier_input = GetModifierInput())
238 {
239 section->Get(group + modifier_input->name + "/Range", &modifier_input->control_ref->range,
240 50.0);
241 modifier_input->control_ref->range /= 100;
242 }
243
244 std::string load_str;
245 section->Get(group + CALIBRATION_CONFIG_NAME, &load_str, "");
246 const auto load_data = SplitString(load_str, ' ');
247
248 m_calibration.assign(load_data.size(), CALIBRATION_DEFAULT_VALUE);
249
250 auto it = load_data.begin();
251 for (auto& sample : m_calibration)
252 {
253 if (TryParse(*(it++), &sample))
254 sample /= CALIBRATION_CONFIG_SCALE;
255 }
256
257 section->Get(group + CENTER_CONFIG_NAME, &load_str, "");
258 const auto center_data = SplitString(load_str, ' ');
259
260 m_center = Common::DVec2();
261
262 if (center_data.size() == 2)
263 {
264 if (TryParse(center_data[0], &m_center.x))
265 m_center.x /= CENTER_CONFIG_SCALE;
266
267 if (TryParse(center_data[1], &m_center.y))
268 m_center.y /= CENTER_CONFIG_SCALE;
269 }
270 }
271
272 void ReshapableInput::SaveConfig(Common::IniFile::Section* section, const std::string& base_name)
273 {
274 ControlGroup::SaveConfig(section, base_name);
275
276 const std::string group(base_name + name + '/');
277
278 // Special handling for "Modifier" button "Range" settings which default to 50% instead of 100%.
279 if (const auto* modifier_input = GetModifierInput())
280 {
281 section->Set(group + modifier_input->name + "/Range", modifier_input->control_ref->range * 100,
282 50.0);
283 }
284
285 const std::ranges::transform_view scaled_calibration(
286 m_calibration, [](ControlState val) { return val * CALIBRATION_CONFIG_SCALE; });
287 section->Set(group + CALIBRATION_CONFIG_NAME,
288 fmt::format("{:.2f}", fmt::join(scaled_calibration, " ")), "");
289
290 // Save center value.
291 static constexpr char center_format[] = "{:.2f} {:.2f}";
292 const auto center_data = fmt::format(center_format, m_center.x * CENTER_CONFIG_SCALE,
293 m_center.y * CENTER_CONFIG_SCALE);
294 section->Set(group + CENTER_CONFIG_NAME, center_data, fmt::format(center_format, 0.0, 0.0));
295 }
296
297 ReshapableInput::ReshapeData ReshapableInput::Reshape(ControlState x, ControlState y,
298 ControlState modifier,
299 ControlState clamp) const
300 {
301 x -= m_center.x;
302 y -= m_center.y;
303
304 // We run this even if both x and y will be zero.
305 // In that case, std::atan2(0, 0) returns a valid non-NaN value, but the exact value
306 // (which depends on the signs of x and y) does not matter here as dist is zero
307
308 // TODO: make the AtAngle functions work with negative angles:
309 ControlState angle = std::atan2(y, x) + MathUtil::TAU;
310
311 const ControlState input_max_dist = GetInputRadiusAtAngle(angle);
312 ControlState gate_max_dist = GetGateRadiusAtAngle(angle);
313
314 // If input radius (from calibration) is zero apply no scaling to prevent division by zero.
315 const ControlState max_dist = input_max_dist ? input_max_dist : gate_max_dist;
316
317 ControlState dist = Common::DVec2{x, y}.Length() / max_dist;
318
319 const double virtual_notch_size = GetVirtualNotchSize();
320
321 if (virtual_notch_size > 0.0 && dist >= MINIMUM_NOTCH_DISTANCE)
322 {
323 angle = GetNearestNotch(angle, virtual_notch_size);
324 gate_max_dist = GetGateRadiusAtAngle(angle);
325 }
326
327 // If the modifier is pressed, scale the distance by the modifier's value.
328 // This is affected by the modifier's "range" setting which defaults to 50%.
329 if (modifier)
330 {
331 dist *= modifier;
332 }
333
334 // Apply deadzone as a percentage of the user-defined calibration shape/size:
335 dist = ApplyDeadzone(dist, GetDeadzonePercentage());
336
337 // Scale to the gate shape/radius:
338 dist *= gate_max_dist;
339
340 return {std::clamp(std::cos(angle) * dist, -clamp, clamp),
341 std::clamp(std::sin(angle) * dist, -clamp, clamp)};
342 }
343
344 Control* ReshapableInput::GetModifierInput() const
345 {
346 return nullptr;
347 }
348
349 } // namespace ControllerEmu