1#include "touch_controls.h"
2
3#include <base/color.h>
4#include <base/log.h>
5#include <base/system.h>
6
7#include <engine/client.h>
8#include <engine/external/json-parser/json.h>
9#include <engine/shared/config.h>
10#include <engine/shared/jsonwriter.h>
11#include <engine/shared/localization.h>
12
13#include <game/client/components/camera.h>
14#include <game/client/components/chat.h>
15#include <game/client/components/console.h>
16#include <game/client/components/controls.h>
17#include <game/client/components/emoticon.h>
18#include <game/client/components/menus.h>
19#include <game/client/components/spectator.h>
20#include <game/client/components/voting.h>
21#include <game/client/gameclient.h>
22#include <game/localization.h>
23
24#include <algorithm>
25#include <cstdlib>
26#include <functional>
27#include <iterator>
28#include <queue>
29
30using namespace std::chrono_literals;
31
32// TODO: Add combined weapon picker button that shows all currently available weapons
33// TODO: Add "joystick-aim-relative", a virtual joystick that moves the mouse pointer relatively. And add "aim-relative" ingame direct touch input.
34// TODO: Add "choice" predefined behavior which shows a selection popup for 2 or more other behaviors?
35// TODO: Support changing labels of menu buttons (or support overriding label for all predefined button behaviors)?
36
37static constexpr const char *const ACTION_NAMES[] = {Localizable(pStr: "Aim"), Localizable(pStr: "Fire"), Localizable(pStr: "Hook")};
38static constexpr const char *const ACTION_SWAP_NAMES[] = {/* unused */ "", Localizable(pStr: "Active: Fire"), Localizable(pStr: "Active: Hook")};
39static constexpr const char *const ACTION_COMMANDS[] = {/* unused */ "", "+fire", "+hook"};
40
41static constexpr std::chrono::milliseconds LONG_TOUCH_DURATION = 500ms;
42static constexpr std::chrono::milliseconds BIND_REPEAT_INITIAL_DELAY = 250ms;
43static constexpr std::chrono::nanoseconds BIND_REPEAT_RATE = std::chrono::nanoseconds(1s) / 15;
44
45static constexpr const char *const CONFIGURATION_FILENAME = "touch_controls.json";
46
47/* This is required for the localization script to find the labels of the default bind buttons specified in the configuration file:
48Localizable("Move left") Localizable("Move right") Localizable("Jump") Localizable("Prev. weapon") Localizable("Next weapon")
49Localizable("Zoom out") Localizable("Default zoom") Localizable("Zoom in") Localizable("Scoreboard") Localizable("Chat") Localizable("Team chat")
50Localizable("Vote yes") Localizable("Vote no") Localizable("Toggle dummy")
51*/
52
53CTouchControls::CTouchButton::CTouchButton(CTouchControls *pTouchControls) :
54 m_pTouchControls(pTouchControls),
55 m_UnitRect({.m_X: 0, .m_Y: 0, .m_W: BUTTON_SIZE_MINIMUM, .m_H: BUTTON_SIZE_MINIMUM}),
56 m_Shape(EButtonShape::RECT),
57 m_pBehavior(nullptr),
58 m_VisibilityCached(false)
59{
60}
61
62CTouchControls::CTouchButton::CTouchButton(CTouchButton &&Other) noexcept :
63 m_pTouchControls(Other.m_pTouchControls),
64 m_UnitRect(Other.m_UnitRect),
65 m_Shape(Other.m_Shape),
66 m_vVisibilities(Other.m_vVisibilities),
67 m_pBehavior(std::move(Other.m_pBehavior)),
68 m_VisibilityCached(false)
69{
70 Other.m_pTouchControls = nullptr;
71 UpdatePointers();
72 UpdateScreenFromUnitRect();
73}
74
75CTouchControls::CTouchButton &CTouchControls::CTouchButton::operator=(CTouchButton &&Other) noexcept
76{
77 if(this == &Other)
78 {
79 return *this;
80 }
81 m_pTouchControls = Other.m_pTouchControls;
82 Other.m_pTouchControls = nullptr;
83 m_UnitRect = Other.m_UnitRect;
84 m_Shape = Other.m_Shape;
85 m_vVisibilities = Other.m_vVisibilities;
86 m_pBehavior = std::move(Other.m_pBehavior);
87 m_VisibilityCached = false;
88 UpdatePointers();
89 UpdateScreenFromUnitRect();
90 return *this;
91}
92
93void CTouchControls::CTouchButton::UpdatePointers()
94{
95 m_pBehavior->Init(pTouchButton: this);
96}
97
98void CTouchControls::CTouchButton::UpdateScreenFromUnitRect()
99{
100 m_ScreenRect = m_pTouchControls->CalculateScreenFromUnitRect(Unit: m_UnitRect, Shape: m_Shape);
101}
102
103CUIRect CTouchControls::CalculateScreenFromUnitRect(CUnitRect Unit, EButtonShape Shape) const
104{
105 Unit = CalculateHitbox(Rect: Unit, Shape);
106 const vec2 ScreenSize = CalculateScreenSize();
107 CUIRect ScreenRect;
108 ScreenRect.x = Unit.m_X * ScreenSize.x / BUTTON_SIZE_SCALE;
109 ScreenRect.y = Unit.m_Y * ScreenSize.y / BUTTON_SIZE_SCALE;
110 ScreenRect.w = Unit.m_W * ScreenSize.x / BUTTON_SIZE_SCALE;
111 ScreenRect.h = Unit.m_H * ScreenSize.y / BUTTON_SIZE_SCALE;
112 return ScreenRect;
113}
114
115CTouchControls::CUnitRect CTouchControls::CalculateHitbox(const CUnitRect &Rect, EButtonShape Shape) const
116{
117 switch(Shape)
118 {
119 case EButtonShape::RECT: return Rect;
120 case EButtonShape::CIRCLE:
121 {
122 const vec2 ScreenSize = CalculateScreenSize();
123 CUnitRect Hitbox = Rect;
124 if(ScreenSize.x * Rect.m_W < ScreenSize.y * Rect.m_H)
125 {
126 Hitbox.m_Y += (ScreenSize.y * Rect.m_H - ScreenSize.x * Rect.m_W) / 2 / ScreenSize.y;
127 Hitbox.m_H = ScreenSize.x * Rect.m_W / ScreenSize.y;
128 }
129 else if(ScreenSize.x * Rect.m_W > ScreenSize.y * Rect.m_H)
130 {
131 Hitbox.m_X += (ScreenSize.x * Rect.m_W - ScreenSize.y * Rect.m_H) / 2 / ScreenSize.x;
132 Hitbox.m_W = ScreenSize.y * Rect.m_H / ScreenSize.x;
133 }
134 return Hitbox;
135 }
136 default: dbg_assert_failed("Unhandled shape");
137 }
138}
139
140void CTouchControls::CTouchButton::UpdateBackgroundCorners()
141{
142 if(m_Shape != EButtonShape::RECT)
143 {
144 m_BackgroundCorners = IGraphics::CORNER_NONE;
145 return;
146 }
147
148 // Determine rounded corners based on button layout
149 m_BackgroundCorners = IGraphics::CORNER_ALL;
150
151 if(m_UnitRect.m_X == 0)
152 {
153 m_BackgroundCorners &= ~IGraphics::CORNER_L;
154 }
155 if(m_UnitRect.m_X + m_UnitRect.m_W == BUTTON_SIZE_SCALE)
156 {
157 m_BackgroundCorners &= ~IGraphics::CORNER_R;
158 }
159 if(m_UnitRect.m_Y == 0)
160 {
161 m_BackgroundCorners &= ~IGraphics::CORNER_T;
162 }
163 if(m_UnitRect.m_Y + m_UnitRect.m_H == BUTTON_SIZE_SCALE)
164 {
165 m_BackgroundCorners &= ~IGraphics::CORNER_B;
166 }
167
168 const auto &&PointInOrOnRect = [](ivec2 Point, CUnitRect Rect) {
169 return Point.x >= Rect.m_X && Point.x <= Rect.m_X + Rect.m_W && Point.y >= Rect.m_Y && Point.y <= Rect.m_Y + Rect.m_H;
170 };
171 for(const CTouchButton &OtherButton : m_pTouchControls->m_vTouchButtons)
172 {
173 if(&OtherButton == this || OtherButton.m_Shape != EButtonShape::RECT || !OtherButton.IsVisible())
174 continue;
175
176 if((m_BackgroundCorners & IGraphics::CORNER_TL) && PointInOrOnRect(ivec2(m_UnitRect.m_X, m_UnitRect.m_Y), OtherButton.m_UnitRect))
177 {
178 m_BackgroundCorners &= ~IGraphics::CORNER_TL;
179 }
180 if((m_BackgroundCorners & IGraphics::CORNER_TR) && PointInOrOnRect(ivec2(m_UnitRect.m_X + m_UnitRect.m_W, m_UnitRect.m_Y), OtherButton.m_UnitRect))
181 {
182 m_BackgroundCorners &= ~IGraphics::CORNER_TR;
183 }
184 if((m_BackgroundCorners & IGraphics::CORNER_BL) && PointInOrOnRect(ivec2(m_UnitRect.m_X, m_UnitRect.m_Y + m_UnitRect.m_H), OtherButton.m_UnitRect))
185 {
186 m_BackgroundCorners &= ~IGraphics::CORNER_BL;
187 }
188 if((m_BackgroundCorners & IGraphics::CORNER_BR) && PointInOrOnRect(ivec2(m_UnitRect.m_X + m_UnitRect.m_W, m_UnitRect.m_Y + m_UnitRect.m_H), OtherButton.m_UnitRect))
189 {
190 m_BackgroundCorners &= ~IGraphics::CORNER_BR;
191 }
192 if(m_BackgroundCorners == IGraphics::CORNER_NONE)
193 {
194 break;
195 }
196 }
197}
198
199vec2 CTouchControls::CTouchButton::ClampTouchPosition(vec2 TouchPosition) const
200{
201 switch(m_Shape)
202 {
203 case EButtonShape::RECT:
204 {
205 TouchPosition.x = std::clamp(val: TouchPosition.x, lo: m_ScreenRect.x, hi: m_ScreenRect.x + m_ScreenRect.w);
206 TouchPosition.y = std::clamp(val: TouchPosition.y, lo: m_ScreenRect.y, hi: m_ScreenRect.y + m_ScreenRect.h);
207 break;
208 }
209 case EButtonShape::CIRCLE:
210 {
211 const vec2 Center = m_ScreenRect.Center();
212 const float MaxLength = minimum(a: m_ScreenRect.w, b: m_ScreenRect.h) / 2.0f;
213 const vec2 TouchDirection = TouchPosition - Center;
214 const float Length = length(a: TouchDirection);
215 if(Length > MaxLength)
216 {
217 TouchPosition = normalize_pre_length(v: TouchDirection, len: Length) * MaxLength + Center;
218 }
219 break;
220 }
221 default:
222 dbg_assert_failed("Unhandled shape");
223 }
224 return TouchPosition;
225}
226
227bool CTouchControls::CTouchButton::IsInside(vec2 TouchPosition) const
228{
229 switch(m_Shape)
230 {
231 case EButtonShape::RECT:
232 return m_ScreenRect.Inside(Point: TouchPosition);
233 case EButtonShape::CIRCLE:
234 return distance(a: TouchPosition, b: m_ScreenRect.Center()) <= minimum(a: m_ScreenRect.w, b: m_ScreenRect.h) / 2.0f;
235 default:
236 dbg_assert_failed("Unhandled shape");
237 return false;
238 }
239}
240
241void CTouchControls::CTouchButton::UpdateVisibilityGame()
242{
243 const bool PrevVisibility = m_VisibilityCached;
244 m_VisibilityCached = std::all_of(first: m_vVisibilities.begin(), last: m_vVisibilities.end(), pred: [&](CButtonVisibility Visibility) {
245 return m_pTouchControls->m_aVisibilityFunctions[(int)Visibility.m_Type].m_Function() == Visibility.m_Parity;
246 });
247 if(m_VisibilityCached && !PrevVisibility)
248 {
249 m_VisibilityStartTime = time_get_nanoseconds();
250 }
251}
252
253void CTouchControls::CTouchButton::UpdateVisibilityEditor()
254{
255 const bool PrevVisibility = m_VisibilityCached;
256 m_VisibilityCached = std::all_of(first: m_vVisibilities.begin(), last: m_vVisibilities.end(), pred: [&](CButtonVisibility Visibility) {
257 return m_pTouchControls->m_aVirtualVisibilities[(int)Visibility.m_Type] == Visibility.m_Parity;
258 });
259 if(m_VisibilityCached && !PrevVisibility)
260 {
261 m_VisibilityStartTime = time_get_nanoseconds();
262 }
263}
264
265bool CTouchControls::CTouchButton::IsVisible() const
266{
267 return m_VisibilityCached;
268}
269
270// TODO: Optimization: Use text and quad containers for rendering
271void CTouchControls::CTouchButton::Render(std::optional<bool> Selected, std::optional<CUnitRect> Rect) const
272{
273 dbg_assert(m_pBehavior != nullptr, "Touch button behavior is nullptr");
274 CUIRect ScreenRect;
275 if(Rect.has_value())
276 ScreenRect = m_pTouchControls->CalculateScreenFromUnitRect(Unit: *Rect, Shape: m_Shape);
277 else
278 ScreenRect = m_ScreenRect;
279
280 ColorRGBA ButtonColor;
281 // "Selected" can decide which color to use, while not disturbing the original color check.
282 ButtonColor = m_pBehavior->IsActive() || Selected.value_or(u: false) ? m_pTouchControls->m_BackgroundColorActive : m_pTouchControls->m_BackgroundColorInactive;
283 if(!Selected.value_or(u: true))
284 ButtonColor = m_pTouchControls->m_BackgroundColorInactive;
285 switch(m_Shape)
286 {
287 case EButtonShape::RECT:
288 {
289 ScreenRect.Draw(Color: ButtonColor, Corners: m_pTouchControls->m_EditingActive ? IGraphics::CORNER_NONE : m_BackgroundCorners, Rounding: 10.0f);
290 break;
291 }
292 case EButtonShape::CIRCLE:
293 {
294 const vec2 Center = ScreenRect.Center();
295 const float Radius = minimum(a: ScreenRect.w, b: ScreenRect.h) / 2.0f;
296 m_pTouchControls->Graphics()->TextureClear();
297 m_pTouchControls->Graphics()->QuadsBegin();
298 m_pTouchControls->Graphics()->SetColor(ButtonColor);
299 m_pTouchControls->Graphics()->DrawCircle(CenterX: Center.x, CenterY: Center.y, Radius, Segments: maximum(a: round_truncate(f: Radius / 4.0f) & ~1, b: 32));
300 m_pTouchControls->Graphics()->QuadsEnd();
301 break;
302 }
303 default:
304 dbg_assert_failed("Unhandled shape");
305 }
306
307 const float FontSize = 22.0f;
308 CButtonLabel LabelData = m_pBehavior->GetLabel();
309 CUIRect LabelRect;
310 ScreenRect.Margin(Cut: 10.0f, pOtherRect: &LabelRect);
311 SLabelProperties LabelProps;
312 LabelProps.m_MaxWidth = LabelRect.w;
313 if(LabelData.m_Type == CButtonLabel::EType::ICON)
314 {
315 m_pTouchControls->TextRender()->SetFontPreset(EFontPreset::ICON_FONT);
316 m_pTouchControls->TextRender()->SetRenderFlags(ETextRenderFlags::TEXT_RENDER_FLAG_ONLY_ADVANCE_WIDTH | ETextRenderFlags::TEXT_RENDER_FLAG_NO_X_BEARING | ETextRenderFlags::TEXT_RENDER_FLAG_NO_Y_BEARING);
317 m_pTouchControls->Ui()->DoLabel(pRect: &LabelRect, pText: LabelData.m_pLabel, Size: FontSize, Align: TEXTALIGN_MC, LabelProps);
318 m_pTouchControls->TextRender()->SetRenderFlags(0);
319 m_pTouchControls->TextRender()->SetFontPreset(EFontPreset::DEFAULT_FONT);
320 }
321 else
322 {
323 const char *pLabel = LabelData.m_Type == CButtonLabel::EType::LOCALIZED ? Localize(pStr: LabelData.m_pLabel) : LabelData.m_pLabel;
324 m_pTouchControls->Ui()->DoLabel(pRect: &LabelRect, pText: pLabel, Size: FontSize, Align: TEXTALIGN_MC, LabelProps);
325 }
326}
327
328void CTouchControls::CTouchButton::WriteToConfiguration(CJsonWriter *pWriter)
329{
330 char aBuf[256];
331
332 pWriter->BeginObject();
333
334 pWriter->WriteAttribute(pName: "x");
335 pWriter->WriteIntValue(Value: m_UnitRect.m_X);
336 pWriter->WriteAttribute(pName: "y");
337 pWriter->WriteIntValue(Value: m_UnitRect.m_Y);
338 pWriter->WriteAttribute(pName: "w");
339 pWriter->WriteIntValue(Value: m_UnitRect.m_W);
340 pWriter->WriteAttribute(pName: "h");
341 pWriter->WriteIntValue(Value: m_UnitRect.m_H);
342
343 pWriter->WriteAttribute(pName: "shape");
344 pWriter->WriteStrValue(pValue: SHAPE_NAMES[(int)m_Shape]);
345
346 pWriter->WriteAttribute(pName: "visibilities");
347 pWriter->BeginArray();
348 for(CButtonVisibility Visibility : m_vVisibilities)
349 {
350 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s%s", Visibility.m_Parity ? "" : "-", m_pTouchControls->m_aVisibilityFunctions[(int)Visibility.m_Type].m_pId);
351 pWriter->WriteStrValue(pValue: aBuf);
352 }
353 pWriter->EndArray();
354
355 pWriter->WriteAttribute(pName: "behavior");
356 pWriter->BeginObject();
357 m_pBehavior->WriteToConfiguration(pWriter);
358 pWriter->EndObject();
359
360 pWriter->EndObject();
361}
362
363void CTouchControls::CTouchButtonBehavior::Init(CTouchButton *pTouchButton)
364{
365 m_pTouchButton = pTouchButton;
366 m_pTouchControls = pTouchButton->m_pTouchControls;
367}
368
369void CTouchControls::CTouchButtonBehavior::Reset()
370{
371 m_Active = false;
372}
373
374void CTouchControls::CTouchButtonBehavior::SetActive(const IInput::CTouchFingerState &FingerState)
375{
376 const vec2 ScreenSize = m_pTouchControls->CalculateScreenSize();
377 const CUIRect ButtonScreenRect = m_pTouchButton->m_ScreenRect;
378 const vec2 Position = (m_pTouchButton->ClampTouchPosition(TouchPosition: FingerState.m_Position * ScreenSize) - ButtonScreenRect.TopLeft()) / ButtonScreenRect.Size();
379 const vec2 Delta = FingerState.m_Delta * ScreenSize / ButtonScreenRect.Size();
380 if(!m_Active)
381 {
382 m_Active = true;
383 m_ActivePosition = Position;
384 m_AccumulatedDelta = Delta;
385 m_ActivationStartTime = time_get_nanoseconds();
386 m_Finger = FingerState.m_Finger;
387 OnActivate();
388 }
389 else if(m_Finger == FingerState.m_Finger)
390 {
391 m_ActivePosition = Position;
392 m_AccumulatedDelta += Delta;
393 OnUpdate();
394 }
395 else
396 {
397 dbg_assert_failed("Touch button must be inactive or use same finger");
398 }
399}
400
401void CTouchControls::CTouchButtonBehavior::SetInactive(bool ByFinger)
402{
403 if(m_Active)
404 {
405 m_Active = false;
406 OnDeactivate(ByFinger);
407 }
408}
409
410bool CTouchControls::CTouchButtonBehavior::IsActive() const
411{
412 return m_Active;
413}
414
415bool CTouchControls::CTouchButtonBehavior::IsActive(const IInput::CTouchFinger &Finger) const
416{
417 return m_Active && m_Finger == Finger;
418}
419
420void CTouchControls::CPredefinedTouchButtonBehavior::WriteToConfiguration(CJsonWriter *pWriter)
421{
422 pWriter->WriteAttribute(pName: "type");
423 pWriter->WriteStrValue(pValue: BEHAVIOR_TYPE);
424
425 pWriter->WriteAttribute(pName: "id");
426 pWriter->WriteStrValue(pValue: m_pId);
427}
428
429// Ingame menu button: always opens ingame menu.
430CTouchControls::CButtonLabel CTouchControls::CIngameMenuTouchButtonBehavior::GetLabel() const
431{
432 return {.m_Type: CButtonLabel::EType::ICON, .m_pLabel: "\xEF\x85\x8E"};
433}
434
435void CTouchControls::CIngameMenuTouchButtonBehavior::OnDeactivate(bool ByFinger)
436{
437 if(!ByFinger)
438 return;
439 m_pTouchControls->GameClient()->m_Menus.SetActive(true);
440}
441
442// Extra menu button:
443// - Short press: show/hide additional buttons (toggle extra-menu visibilities)
444// - Long press: open ingame menu
445CTouchControls::CExtraMenuTouchButtonBehavior::CExtraMenuTouchButtonBehavior(int Number) :
446 CPredefinedTouchButtonBehavior(BEHAVIOR_ID),
447 m_Number(Number)
448{
449 if(m_Number == 0)
450 {
451 str_copy(dst&: m_aLabel, src: "\xEF\x83\x89");
452 }
453 else
454 {
455 str_format(buffer: m_aLabel, buffer_size: sizeof(m_aLabel), format: "\xEF\x83\x89%d", m_Number + 1);
456 }
457}
458
459CTouchControls::CButtonLabel CTouchControls::CExtraMenuTouchButtonBehavior::GetLabel() const
460{
461 if(m_Active && time_get_nanoseconds() - m_ActivationStartTime >= LONG_TOUCH_DURATION)
462 {
463 return {.m_Type: CButtonLabel::EType::ICON, .m_pLabel: "\xEF\x95\x90"};
464 }
465 else
466 {
467 return {.m_Type: CButtonLabel::EType::ICON, .m_pLabel: m_aLabel};
468 }
469}
470
471void CTouchControls::CExtraMenuTouchButtonBehavior::OnDeactivate(bool ByFinger)
472{
473 if(!ByFinger)
474 return;
475 if(time_get_nanoseconds() - m_ActivationStartTime >= LONG_TOUCH_DURATION)
476 {
477 m_pTouchControls->GameClient()->m_Menus.SetActive(true);
478 }
479 else
480 {
481 m_pTouchControls->m_aExtraMenuActive[m_Number] = !m_pTouchControls->m_aExtraMenuActive[m_Number];
482 }
483}
484
485void CTouchControls::CExtraMenuTouchButtonBehavior::WriteToConfiguration(CJsonWriter *pWriter)
486{
487 CPredefinedTouchButtonBehavior::WriteToConfiguration(pWriter);
488
489 pWriter->WriteAttribute(pName: "number");
490 pWriter->WriteIntValue(Value: m_Number + 1);
491}
492
493// Emoticon button: keeps the emoticon HUD open, next touch in emoticon HUD will close it again.
494CTouchControls::CButtonLabel CTouchControls::CEmoticonTouchButtonBehavior::GetLabel() const
495{
496 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: Localizable(pStr: "Emoticon")};
497}
498
499void CTouchControls::CEmoticonTouchButtonBehavior::OnDeactivate(bool ByFinger)
500{
501 if(!ByFinger)
502 return;
503 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: "+emote");
504}
505
506// Spectate button: keeps the spectate menu open, next touch in spectate menu will close it again.
507CTouchControls::CButtonLabel CTouchControls::CSpectateTouchButtonBehavior::GetLabel() const
508{
509 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: Localizable(pStr: "Spectator mode")};
510}
511
512void CTouchControls::CSpectateTouchButtonBehavior::OnDeactivate(bool ByFinger)
513{
514 if(!ByFinger)
515 return;
516 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: "+spectate");
517}
518
519// Swap action button:
520// - If joystick is currently active with one action: activate the other action.
521// - Else: swap active action.
522CTouchControls::CButtonLabel CTouchControls::CSwapActionTouchButtonBehavior::GetLabel() const
523{
524 if(m_ActiveAction != NUM_ACTIONS)
525 {
526 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_ActiveAction]};
527 }
528 else if(m_pTouchControls->m_JoystickPressCount != 0)
529 {
530 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_pTouchControls->NextActiveAction(Action: m_pTouchControls->m_ActionSelected)]};
531 }
532 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_SWAP_NAMES[m_pTouchControls->m_ActionSelected]};
533}
534
535void CTouchControls::CSwapActionTouchButtonBehavior::OnActivate()
536{
537 if(m_pTouchControls->m_JoystickPressCount != 0)
538 {
539 m_ActiveAction = m_pTouchControls->NextActiveAction(Action: m_pTouchControls->m_ActionSelected);
540 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: ACTION_COMMANDS[m_ActiveAction]);
541 }
542 else
543 {
544 m_pTouchControls->m_ActionSelected = m_pTouchControls->NextActiveAction(Action: m_pTouchControls->m_ActionSelected);
545 }
546}
547
548void CTouchControls::CSwapActionTouchButtonBehavior::OnDeactivate(bool ByFinger)
549{
550 if(m_ActiveAction != NUM_ACTIONS)
551 {
552 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 0, pStr: ACTION_COMMANDS[m_ActiveAction]);
553 m_ActiveAction = NUM_ACTIONS;
554 }
555}
556
557// Use action button: always uses the active action.
558CTouchControls::CButtonLabel CTouchControls::CUseActionTouchButtonBehavior::GetLabel() const
559{
560 if(m_ActiveAction != NUM_ACTIONS)
561 {
562 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_ActiveAction]};
563 }
564 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_pTouchControls->m_ActionSelected]};
565}
566
567void CTouchControls::CUseActionTouchButtonBehavior::OnActivate()
568{
569 m_ActiveAction = m_pTouchControls->m_ActionSelected;
570 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: ACTION_COMMANDS[m_ActiveAction]);
571}
572
573void CTouchControls::CUseActionTouchButtonBehavior::OnDeactivate(bool ByFinger)
574{
575 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 0, pStr: ACTION_COMMANDS[m_ActiveAction]);
576 m_ActiveAction = NUM_ACTIONS;
577}
578
579// Generic joystick button behavior: aim with virtual joystick and use action (defined by subclass).
580CTouchControls::CButtonLabel CTouchControls::CJoystickTouchButtonBehavior::GetLabel() const
581{
582 if(m_ActiveAction != NUM_ACTIONS)
583 {
584 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[m_ActiveAction]};
585 }
586 return {.m_Type: CButtonLabel::EType::LOCALIZED, .m_pLabel: ACTION_NAMES[SelectedAction()]};
587}
588
589void CTouchControls::CJoystickTouchButtonBehavior::OnActivate()
590{
591 m_ActiveAction = SelectedAction();
592 OnUpdate();
593 if(m_ActiveAction != ACTION_AIM)
594 {
595 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: ACTION_COMMANDS[m_ActiveAction]);
596 }
597 m_pTouchControls->m_JoystickPressCount++;
598}
599
600void CTouchControls::CJoystickTouchButtonBehavior::OnDeactivate(bool ByFinger)
601{
602 if(m_ActiveAction != ACTION_AIM)
603 {
604 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 0, pStr: ACTION_COMMANDS[m_ActiveAction]);
605 }
606 m_ActiveAction = NUM_ACTIONS;
607 m_pTouchControls->m_JoystickPressCount--;
608}
609
610void CTouchControls::CJoystickTouchButtonBehavior::OnUpdate()
611{
612 CControls &Controls = m_pTouchControls->GameClient()->m_Controls;
613 if(m_pTouchControls->GameClient()->m_Snap.m_SpecInfo.m_Active)
614 {
615 vec2 WorldScreenSize;
616 m_pTouchControls->Graphics()->CalcScreenParams(Aspect: m_pTouchControls->Graphics()->ScreenAspect(), Zoom: m_pTouchControls->GameClient()->m_Camera.m_Zoom, pWidth: &WorldScreenSize.x, pHeight: &WorldScreenSize.y);
617 Controls.m_aMousePos[g_Config.m_ClDummy] += -m_AccumulatedDelta * WorldScreenSize;
618 Controls.m_aMouseInputType[g_Config.m_ClDummy] = CControls::EMouseInputType::RELATIVE;
619 Controls.m_aMousePos[g_Config.m_ClDummy].x = std::clamp(val: Controls.m_aMousePos[g_Config.m_ClDummy].x, lo: -201.0f * 32, hi: (m_pTouchControls->Collision()->GetWidth() + 201.0f) * 32.0f);
620 Controls.m_aMousePos[g_Config.m_ClDummy].y = std::clamp(val: Controls.m_aMousePos[g_Config.m_ClDummy].y, lo: -201.0f * 32, hi: (m_pTouchControls->Collision()->GetHeight() + 201.0f) * 32.0f);
621 m_AccumulatedDelta = vec2(0.0f, 0.0f);
622 }
623 else
624 {
625 const vec2 AbsolutePosition = (m_ActivePosition - vec2(0.5f, 0.5f)) * 2.0f;
626 Controls.m_aMousePos[g_Config.m_ClDummy] = AbsolutePosition * (Controls.GetMaxMouseDistance() - Controls.GetMinMouseDistance()) + normalize(v: AbsolutePosition) * Controls.GetMinMouseDistance();
627 Controls.m_aMouseInputType[g_Config.m_ClDummy] = CControls::EMouseInputType::ABSOLUTE;
628 if(length(a: Controls.m_aMousePos[g_Config.m_ClDummy]) < 0.001f)
629 {
630 Controls.m_aMousePos[g_Config.m_ClDummy].x = 0.001f;
631 Controls.m_aMousePos[g_Config.m_ClDummy].y = 0.0f;
632 }
633 }
634}
635
636// Joystick that uses the active action.
637void CTouchControls::CJoystickActionTouchButtonBehavior::Init(CTouchButton *pTouchButton)
638{
639 CPredefinedTouchButtonBehavior::Init(pTouchButton);
640}
641
642int CTouchControls::CJoystickActionTouchButtonBehavior::SelectedAction() const
643{
644 return m_pTouchControls->m_ActionSelected;
645}
646
647// Joystick that only aims.
648int CTouchControls::CJoystickAimTouchButtonBehavior::SelectedAction() const
649{
650 return ACTION_AIM;
651}
652
653// Joystick that always uses fire.
654int CTouchControls::CJoystickFireTouchButtonBehavior::SelectedAction() const
655{
656 return ACTION_FIRE;
657}
658
659// Joystick that always uses hook.
660int CTouchControls::CJoystickHookTouchButtonBehavior::SelectedAction() const
661{
662 return ACTION_HOOK;
663}
664
665// Bind button behavior that executes a command like a bind.
666CTouchControls::CButtonLabel CTouchControls::CBindTouchButtonBehavior::GetLabel() const
667{
668 return {.m_Type: m_LabelType, .m_pLabel: m_Label.c_str()};
669}
670
671void CTouchControls::CBindTouchButtonBehavior::OnActivate()
672{
673 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: m_Command.c_str());
674 m_Repeating = false;
675}
676
677void CTouchControls::CBindTouchButtonBehavior::OnDeactivate(bool ByFinger)
678{
679 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 0, pStr: m_Command.c_str());
680}
681
682void CTouchControls::CBindTouchButtonBehavior::OnUpdate()
683{
684 const auto Now = time_get_nanoseconds();
685 if(m_Repeating)
686 {
687 m_AccumulatedRepeatingTime += Now - m_LastUpdateTime;
688 m_LastUpdateTime = Now;
689 if(m_AccumulatedRepeatingTime >= BIND_REPEAT_RATE)
690 {
691 m_AccumulatedRepeatingTime -= BIND_REPEAT_RATE;
692 m_pTouchControls->Console()->ExecuteLineStroked(Stroke: 1, pStr: m_Command.c_str());
693 }
694 }
695 else if(Now - m_ActivationStartTime >= BIND_REPEAT_INITIAL_DELAY)
696 {
697 m_Repeating = true;
698 m_LastUpdateTime = Now;
699 m_AccumulatedRepeatingTime = 0ns;
700 }
701}
702
703void CTouchControls::CBindTouchButtonBehavior::WriteToConfiguration(CJsonWriter *pWriter)
704{
705 pWriter->WriteAttribute(pName: "type");
706 pWriter->WriteStrValue(pValue: BEHAVIOR_TYPE);
707
708 pWriter->WriteAttribute(pName: "label");
709 pWriter->WriteStrValue(pValue: m_Label.c_str());
710
711 pWriter->WriteAttribute(pName: "label-type");
712 pWriter->WriteStrValue(pValue: LABEL_TYPE_NAMES[(int)m_LabelType]);
713
714 pWriter->WriteAttribute(pName: "command");
715 pWriter->WriteStrValue(pValue: m_Command.c_str());
716}
717
718// Bind button behavior that switches between executing one of two or more console commands.
719CTouchControls::CButtonLabel CTouchControls::CBindToggleTouchButtonBehavior::GetLabel() const
720{
721 const auto &ActiveCommand = m_vCommands[m_ActiveCommandIndex];
722 return {.m_Type: ActiveCommand.m_LabelType, .m_pLabel: ActiveCommand.m_Label.c_str()};
723}
724
725void CTouchControls::CBindToggleTouchButtonBehavior::OnActivate()
726{
727 m_pTouchControls->Console()->ExecuteLine(pStr: m_vCommands[m_ActiveCommandIndex].m_Command.c_str());
728 m_ActiveCommandIndex = (m_ActiveCommandIndex + 1) % m_vCommands.size();
729}
730
731void CTouchControls::CBindToggleTouchButtonBehavior::WriteToConfiguration(CJsonWriter *pWriter)
732{
733 pWriter->WriteAttribute(pName: "type");
734 pWriter->WriteStrValue(pValue: BEHAVIOR_TYPE);
735
736 pWriter->WriteAttribute(pName: "commands");
737 pWriter->BeginArray();
738
739 for(const auto &Command : m_vCommands)
740 {
741 pWriter->BeginObject();
742
743 pWriter->WriteAttribute(pName: "label");
744 pWriter->WriteStrValue(pValue: Command.m_Label.c_str());
745
746 pWriter->WriteAttribute(pName: "label-type");
747 pWriter->WriteStrValue(pValue: LABEL_TYPE_NAMES[(int)Command.m_LabelType]);
748
749 pWriter->WriteAttribute(pName: "command");
750 pWriter->WriteStrValue(pValue: Command.m_Command.c_str());
751
752 pWriter->EndObject();
753 }
754
755 pWriter->EndArray();
756}
757
758void CTouchControls::OnInit()
759{
760 InitVisibilityFunctions();
761 if(!LoadConfigurationFromFile(StorageType: IStorage::TYPE_ALL))
762 {
763 Client()->AddWarning(Warning: SWarning(Localize(pStr: "Error loading touch controls"), Localize(pStr: "Could not load touch controls from file. See local console for details.")));
764 }
765}
766
767void CTouchControls::OnReset()
768{
769 ResetButtons();
770 m_EditingActive = false;
771}
772
773void CTouchControls::OnWindowResize()
774{
775 ResetButtons();
776 for(CTouchButton &TouchButton : m_vTouchButtons)
777 {
778 TouchButton.UpdateScreenFromUnitRect();
779 }
780}
781
782bool CTouchControls::OnTouchState(const std::vector<IInput::CTouchFingerState> &vTouchFingerStates)
783{
784 if(!g_Config.m_ClTouchControls)
785 return false;
786 if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK)
787 return false;
788 if(GameClient()->m_Chat.IsActive() ||
789 GameClient()->m_GameConsole.IsActive() ||
790 GameClient()->m_Menus.IsActive() ||
791 GameClient()->m_Emoticon.IsActive() ||
792 GameClient()->m_Spectator.IsActive() ||
793 m_PreviewAllButtons)
794 {
795 ResetButtons();
796 return false;
797 }
798
799 if(m_EditingActive)
800 UpdateButtonsEditor(vTouchFingerStates);
801 else
802 UpdateButtonsGame(vTouchFingerStates);
803 return true;
804}
805
806void CTouchControls::OnRender()
807{
808 if(!g_Config.m_ClTouchControls)
809 return;
810 if(Client()->State() != IClient::STATE_ONLINE && Client()->State() != IClient::STATE_DEMOPLAYBACK)
811 return;
812 if(GameClient()->m_Chat.IsActive() ||
813 GameClient()->m_Emoticon.IsActive() ||
814 GameClient()->m_Spectator.IsActive())
815 {
816 return;
817 }
818
819 const vec2 ScreenSize = CalculateScreenSize();
820 Graphics()->MapScreen(TopLeftX: 0.0f, TopLeftY: 0.0f, BottomRightX: ScreenSize.x, BottomRightY: ScreenSize.y);
821
822 if(m_EditingActive)
823 {
824 RenderButtonsEditor();
825 return;
826 }
827 // If not editing, deselect it.
828 m_pSelectedButton = nullptr;
829 m_pSampleButton = nullptr;
830 m_UnsavedChanges = false;
831 RenderButtonsGame();
832}
833
834bool CTouchControls::LoadConfigurationFromFile(int StorageType)
835{
836 void *pFileData;
837 unsigned FileLength;
838 if(!Storage()->ReadFile(pFilename: CONFIGURATION_FILENAME, Type: StorageType, ppResult: &pFileData, pResultLen: &FileLength))
839 {
840 log_error("touch_controls", "Failed to read configuration from '%s'", CONFIGURATION_FILENAME);
841 return false;
842 }
843
844 const bool Result = ParseConfiguration(pFileData, FileLength);
845 free(ptr: pFileData);
846 return Result;
847}
848
849bool CTouchControls::LoadConfigurationFromClipboard()
850{
851 std::string Clipboard = Input()->GetClipboardText();
852 return ParseConfiguration(pFileData: Clipboard.c_str(), FileLength: Clipboard.size());
853}
854
855bool CTouchControls::SaveConfigurationToFile()
856{
857 IOHANDLE File = Storage()->OpenFile(pFilename: CONFIGURATION_FILENAME, Flags: IOFLAG_WRITE, Type: IStorage::TYPE_SAVE);
858 if(!File)
859 {
860 log_error("touch_controls", "Failed to open '%s' for writing configuration", CONFIGURATION_FILENAME);
861 return false;
862 }
863
864 CJsonFileWriter Writer(File);
865 WriteConfiguration(pWriter: &Writer);
866 return true;
867}
868
869void CTouchControls::SaveConfigurationToClipboard()
870{
871 CJsonStringWriter Writer;
872 WriteConfiguration(pWriter: &Writer);
873 std::string ConfigurationString = Writer.GetOutputString();
874 Input()->SetClipboardText(ConfigurationString.c_str());
875}
876
877void CTouchControls::InitVisibilityFunctions()
878{
879 m_aVisibilityFunctions[(int)EButtonVisibility::INGAME].m_pId = "ingame";
880 m_aVisibilityFunctions[(int)EButtonVisibility::INGAME].m_Function = [&]() {
881 return !GameClient()->m_Snap.m_SpecInfo.m_Active;
882 };
883 m_aVisibilityFunctions[(int)EButtonVisibility::ZOOM_ALLOWED].m_pId = "zoom-allowed";
884 m_aVisibilityFunctions[(int)EButtonVisibility::ZOOM_ALLOWED].m_Function = [&]() {
885 return GameClient()->m_Camera.ZoomAllowed();
886 };
887 m_aVisibilityFunctions[(int)EButtonVisibility::VOTE_ACTIVE].m_pId = "vote-active";
888 m_aVisibilityFunctions[(int)EButtonVisibility::VOTE_ACTIVE].m_Function = [&]() {
889 return GameClient()->m_Voting.IsVoting();
890 };
891 m_aVisibilityFunctions[(int)EButtonVisibility::DUMMY_ALLOWED].m_pId = "dummy-allowed";
892 m_aVisibilityFunctions[(int)EButtonVisibility::DUMMY_ALLOWED].m_Function = [&]() {
893 return Client()->DummyAllowed();
894 };
895 m_aVisibilityFunctions[(int)EButtonVisibility::DUMMY_CONNECTED].m_pId = "dummy-connected";
896 m_aVisibilityFunctions[(int)EButtonVisibility::DUMMY_CONNECTED].m_Function = [&]() {
897 return Client()->DummyConnected();
898 };
899 m_aVisibilityFunctions[(int)EButtonVisibility::RCON_AUTHED].m_pId = "rcon-authed";
900 m_aVisibilityFunctions[(int)EButtonVisibility::RCON_AUTHED].m_Function = [&]() {
901 return Client()->RconAuthed();
902 };
903 m_aVisibilityFunctions[(int)EButtonVisibility::DEMO_PLAYER].m_pId = "demo-player";
904 m_aVisibilityFunctions[(int)EButtonVisibility::DEMO_PLAYER].m_Function = [&]() {
905 return Client()->State() == IClient::STATE_DEMOPLAYBACK;
906 };
907 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_1].m_pId = "extra-menu";
908 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_1].m_Function = [&]() {
909 return m_aExtraMenuActive[0];
910 };
911 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_2].m_pId = "extra-menu-2";
912 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_2].m_Function = [&]() {
913 return m_aExtraMenuActive[1];
914 };
915 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_3].m_pId = "extra-menu-3";
916 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_3].m_Function = [&]() {
917 return m_aExtraMenuActive[2];
918 };
919 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_4].m_pId = "extra-menu-4";
920 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_4].m_Function = [&]() {
921 return m_aExtraMenuActive[3];
922 };
923 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_5].m_pId = "extra-menu-5";
924 m_aVisibilityFunctions[(int)EButtonVisibility::EXTRA_MENU_5].m_Function = [&]() {
925 return m_aExtraMenuActive[4];
926 };
927}
928
929int CTouchControls::NextActiveAction(int Action) const
930{
931 switch(Action)
932 {
933 case ACTION_FIRE:
934 return ACTION_HOOK;
935 case ACTION_HOOK:
936 return ACTION_FIRE;
937 default:
938 dbg_assert_failed("Action invalid for NextActiveAction");
939 }
940}
941
942int CTouchControls::NextDirectTouchAction() const
943{
944 if(GameClient()->m_Snap.m_SpecInfo.m_Active)
945 {
946 switch(m_DirectTouchSpectate)
947 {
948 case EDirectTouchSpectateMode::DISABLED:
949 return NUM_ACTIONS;
950 case EDirectTouchSpectateMode::AIM:
951 return ACTION_AIM;
952 default:
953 dbg_assert_failed("m_DirectTouchSpectate invalid");
954 }
955 }
956 else
957 {
958 switch(m_DirectTouchIngame)
959 {
960 case EDirectTouchIngameMode::DISABLED:
961 return NUM_ACTIONS;
962 case EDirectTouchIngameMode::ACTION:
963 return m_ActionSelected;
964 case EDirectTouchIngameMode::AIM:
965 return ACTION_AIM;
966 case EDirectTouchIngameMode::FIRE:
967 return ACTION_FIRE;
968 case EDirectTouchIngameMode::HOOK:
969 return ACTION_HOOK;
970 default:
971 dbg_assert_failed("m_DirectTouchIngame invalid");
972 }
973 }
974}
975
976void CTouchControls::UpdateButtonsGame(const std::vector<IInput::CTouchFingerState> &vTouchFingerStates)
977{
978 // Update cached button visibilities and store time that buttons become visible.
979 for(CTouchButton &TouchButton : m_vTouchButtons)
980 {
981 TouchButton.UpdateVisibilityGame();
982 }
983
984 const int DirectTouchAction = NextDirectTouchAction();
985 const vec2 ScreenSize = CalculateScreenSize();
986
987 std::vector<IInput::CTouchFingerState> vRemainingTouchFingerStates = vTouchFingerStates;
988
989 if(!m_vStaleFingers.empty())
990 {
991 // Remove stale fingers that are not pressed anymore.
992 m_vStaleFingers.erase(
993 first: std::remove_if(first: m_vStaleFingers.begin(), last: m_vStaleFingers.end(), pred: [&](const IInput::CTouchFinger &Finger) {
994 return std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
995 return TouchFingerState.m_Finger == Finger;
996 }) == vRemainingTouchFingerStates.end();
997 }),
998 last: m_vStaleFingers.end());
999 // Prevent stale fingers from activating touch buttons and direct touch.
1000 vRemainingTouchFingerStates.erase(
1001 first: std::remove_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1002 return std::find_if(first: m_vStaleFingers.begin(), last: m_vStaleFingers.end(), pred: [&](const IInput::CTouchFinger &Finger) {
1003 return TouchFingerState.m_Finger == Finger;
1004 }) != m_vStaleFingers.end();
1005 }),
1006 last: vRemainingTouchFingerStates.end());
1007 }
1008
1009 // Remove remaining finger states for fingers which are responsible for active actions
1010 // and release action when the finger responsible for it is not pressed down anymore.
1011 bool GotDirectFingerState = false; // Whether DirectFingerState is valid
1012 IInput::CTouchFingerState DirectFingerState{}; // The finger that will be used to update the mouse position
1013 for(int Action = ACTION_AIM; Action < NUM_ACTIONS; ++Action)
1014 {
1015 if(!m_aDirectTouchActionStates[Action].m_Active)
1016 {
1017 continue;
1018 }
1019
1020 const auto ActiveFinger = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1021 return TouchFingerState.m_Finger == m_aDirectTouchActionStates[Action].m_Finger;
1022 });
1023 if(ActiveFinger == vRemainingTouchFingerStates.end() || DirectTouchAction == NUM_ACTIONS)
1024 {
1025 m_aDirectTouchActionStates[Action].m_Active = false;
1026 if(Action != ACTION_AIM)
1027 {
1028 Console()->ExecuteLineStroked(Stroke: 0, pStr: ACTION_COMMANDS[Action]);
1029 }
1030 }
1031 else
1032 {
1033 if(Action == m_DirectTouchLastAction)
1034 {
1035 GotDirectFingerState = true;
1036 DirectFingerState = *ActiveFinger;
1037 }
1038 vRemainingTouchFingerStates.erase(position: ActiveFinger);
1039 }
1040 }
1041
1042 // Update touch button states after the active action fingers were removed from the vector
1043 // so that current cursor movement can cross over touch buttons without activating them.
1044
1045 // Activate visible, inactive buttons with hovered finger. Deactivate previous button being
1046 // activated by the same finger. Touch buttons are only activated if they became visible
1047 // before the respective touch finger was pressed down, to prevent repeatedly activating
1048 // overlapping buttons of excluding visibilities.
1049 for(CTouchButton &TouchButton : m_vTouchButtons)
1050 {
1051 if(!TouchButton.IsVisible() || TouchButton.m_pBehavior->IsActive())
1052 {
1053 continue;
1054 }
1055 const auto FingerInsideButton = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1056 return TouchButton.m_VisibilityStartTime < TouchFingerState.m_PressTime &&
1057 TouchButton.IsInside(TouchPosition: TouchFingerState.m_Position * ScreenSize);
1058 });
1059 if(FingerInsideButton == vRemainingTouchFingerStates.end())
1060 {
1061 continue;
1062 }
1063 const auto OtherHoveredTouchButton = std::find_if(first: m_vTouchButtons.begin(), last: m_vTouchButtons.end(), pred: [&](const CTouchButton &Button) {
1064 return &Button != &TouchButton && Button.IsVisible() && Button.IsInside(TouchPosition: FingerInsideButton->m_Position * ScreenSize);
1065 });
1066 if(OtherHoveredTouchButton != m_vTouchButtons.end())
1067 {
1068 // Do not activate any button if multiple overlapping buttons are hovered.
1069 // TODO: Prevent overlapping buttons entirely when parsing the button configuration?
1070 vRemainingTouchFingerStates.erase(position: FingerInsideButton);
1071 continue;
1072 }
1073 auto PrevActiveTouchButton = std::find_if(first: m_vTouchButtons.begin(), last: m_vTouchButtons.end(), pred: [&](const CTouchButton &Button) {
1074 return Button.m_pBehavior->IsActive(Finger: FingerInsideButton->m_Finger);
1075 });
1076 if(PrevActiveTouchButton != m_vTouchButtons.end())
1077 {
1078 PrevActiveTouchButton->m_pBehavior->SetInactive(true);
1079 }
1080 TouchButton.m_pBehavior->SetActive(*FingerInsideButton);
1081 }
1082
1083 // Deactivate touch buttons only when the respective finger is released, so touch buttons
1084 // are kept active also if the finger is moved outside the button.
1085 for(CTouchButton &TouchButton : m_vTouchButtons)
1086 {
1087 if(!TouchButton.IsVisible())
1088 {
1089 if(TouchButton.m_pBehavior->IsActive())
1090 {
1091 // Remember fingers responsible for buttons that were deactivated due to becoming invisible,
1092 // to ensure that these fingers will not activate direct touch input or touch buttons.
1093 m_vStaleFingers.push_back(x: TouchButton.m_pBehavior->m_Finger);
1094 const auto ActiveFinger = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1095 return TouchFingerState.m_Finger == TouchButton.m_pBehavior->m_Finger;
1096 });
1097 // ActiveFinger could be released during this progress.
1098 if(ActiveFinger != vRemainingTouchFingerStates.end())
1099 vRemainingTouchFingerStates.erase(position: ActiveFinger);
1100 }
1101 TouchButton.m_pBehavior->SetInactive(false);
1102 continue;
1103 }
1104 if(!TouchButton.m_pBehavior->IsActive())
1105 {
1106 continue;
1107 }
1108 const auto ActiveFinger = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1109 return TouchFingerState.m_Finger == TouchButton.m_pBehavior->m_Finger;
1110 });
1111 if(ActiveFinger == vRemainingTouchFingerStates.end())
1112 {
1113 TouchButton.m_pBehavior->SetInactive(true);
1114 }
1115 else
1116 {
1117 // Update the already active touch button with the current finger state
1118 TouchButton.m_pBehavior->SetActive(*ActiveFinger);
1119 }
1120 }
1121
1122 // Remove remaining fingers for active buttons after updating the buttons.
1123 for(CTouchButton &TouchButton : m_vTouchButtons)
1124 {
1125 if(!TouchButton.m_pBehavior->IsActive())
1126 {
1127 continue;
1128 }
1129 const auto ActiveFinger = std::find_if(first: vRemainingTouchFingerStates.begin(), last: vRemainingTouchFingerStates.end(), pred: [&](const IInput::CTouchFingerState &TouchFingerState) {
1130 return TouchFingerState.m_Finger == TouchButton.m_pBehavior->m_Finger;
1131 });
1132 dbg_assert(ActiveFinger != vRemainingTouchFingerStates.end(), "Active button finger not found");
1133 vRemainingTouchFingerStates.erase(position: ActiveFinger);
1134 }
1135
1136 // TODO: Support standard gesture to zoom (enabled separately for ingame and spectator)
1137
1138 // Activate action if there is an unhandled pressed down finger.
1139 int ActivateAction = NUM_ACTIONS;
1140 if(DirectTouchAction != NUM_ACTIONS && !vRemainingTouchFingerStates.empty() && !m_aDirectTouchActionStates[DirectTouchAction].m_Active)
1141 {
1142 GotDirectFingerState = true;
1143 DirectFingerState = vRemainingTouchFingerStates[0];
1144 vRemainingTouchFingerStates.erase(position: vRemainingTouchFingerStates.begin());
1145 m_aDirectTouchActionStates[DirectTouchAction].m_Active = true;
1146 m_aDirectTouchActionStates[DirectTouchAction].m_Finger = DirectFingerState.m_Finger;
1147 m_DirectTouchLastAction = DirectTouchAction;
1148 ActivateAction = DirectTouchAction;
1149 }
1150
1151 // Update mouse position based on the finger responsible for the last active action.
1152 if(GotDirectFingerState)
1153 {
1154 const float Zoom = GameClient()->m_Snap.m_SpecInfo.m_Active ? GameClient()->m_Camera.m_Zoom : 1.0f;
1155 vec2 WorldScreenSize;
1156 Graphics()->CalcScreenParams(Aspect: Graphics()->ScreenAspect(), Zoom, pWidth: &WorldScreenSize.x, pHeight: &WorldScreenSize.y);
1157 CControls &Controls = GameClient()->m_Controls;
1158 if(GameClient()->m_Snap.m_SpecInfo.m_Active)
1159 {
1160 Controls.m_aMousePos[g_Config.m_ClDummy] += -DirectFingerState.m_Delta * WorldScreenSize;
1161 Controls.m_aMouseInputType[g_Config.m_ClDummy] = CControls::EMouseInputType::RELATIVE;
1162 Controls.m_aMousePos[g_Config.m_ClDummy].x = std::clamp(val: Controls.m_aMousePos[g_Config.m_ClDummy].x, lo: -201.0f * 32, hi: (Collision()->GetWidth() + 201.0f) * 32.0f);
1163 Controls.m_aMousePos[g_Config.m_ClDummy].y = std::clamp(val: Controls.m_aMousePos[g_Config.m_ClDummy].y, lo: -201.0f * 32, hi: (Collision()->GetHeight() + 201.0f) * 32.0f);
1164 }
1165 else
1166 {
1167 Controls.m_aMousePos[g_Config.m_ClDummy] = (DirectFingerState.m_Position - vec2(0.5f, 0.5f)) * WorldScreenSize;
1168 Controls.m_aMouseInputType[g_Config.m_ClDummy] = CControls::EMouseInputType::ABSOLUTE;
1169 }
1170 }
1171
1172 // Activate action after the mouse position is set.
1173 if(ActivateAction != ACTION_AIM && ActivateAction != NUM_ACTIONS)
1174 {
1175 Console()->ExecuteLineStroked(Stroke: 1, pStr: ACTION_COMMANDS[ActivateAction]);
1176 }
1177}
1178
1179void CTouchControls::ResetButtons()
1180{
1181 for(CTouchButton &TouchButton : m_vTouchButtons)
1182 {
1183 TouchButton.m_pBehavior->Reset();
1184 }
1185 for(CActionState &ActionState : m_aDirectTouchActionStates)
1186 {
1187 ActionState.m_Active = false;
1188 }
1189}
1190
1191void CTouchControls::RenderButtonsGame()
1192{
1193 for(CTouchButton &TouchButton : m_vTouchButtons)
1194 {
1195 TouchButton.UpdateVisibilityGame();
1196 }
1197 for(CTouchButton &TouchButton : m_vTouchButtons)
1198 {
1199 if(!TouchButton.IsVisible())
1200 {
1201 continue;
1202 }
1203 TouchButton.UpdateBackgroundCorners();
1204 TouchButton.UpdateScreenFromUnitRect();
1205 TouchButton.Render();
1206 }
1207}
1208
1209vec2 CTouchControls::CalculateScreenSize() const
1210{
1211 const float ScreenHeight = 400.0f * 3.0f;
1212 const float ScreenWidth = ScreenHeight * Graphics()->ScreenAspect();
1213 return vec2(ScreenWidth, ScreenHeight);
1214}
1215
1216bool CTouchControls::ParseConfiguration(const void *pFileData, unsigned FileLength)
1217{
1218 json_settings JsonSettings{};
1219 char aError[256];
1220 json_value *pConfiguration = json_parse_ex(settings: &JsonSettings, json: static_cast<const json_char *>(pFileData), length: FileLength, error: aError);
1221
1222 if(pConfiguration == nullptr)
1223 {
1224 log_error("touch_controls", "Failed to parse configuration (invalid json): '%s'", aError);
1225 return false;
1226 }
1227 if(pConfiguration->type != json_object)
1228 {
1229 log_error("touch_controls", "Failed to parse configuration: root must be an object");
1230 json_value_free(pConfiguration);
1231 return false;
1232 }
1233
1234 std::optional<EDirectTouchIngameMode> ParsedDirectTouchIngame = ParseDirectTouchIngameMode(pModeValue: &(*pConfiguration)["direct-touch-ingame"]);
1235 if(!ParsedDirectTouchIngame.has_value())
1236 {
1237 json_value_free(pConfiguration);
1238 return false;
1239 }
1240
1241 std::optional<EDirectTouchSpectateMode> ParsedDirectTouchSpectate = ParseDirectTouchSpectateMode(pModeValue: &(*pConfiguration)["direct-touch-spectate"]);
1242 if(!ParsedDirectTouchSpectate.has_value())
1243 {
1244 json_value_free(pConfiguration);
1245 return false;
1246 }
1247
1248 std::optional<ColorRGBA> ParsedBackgroundColorInactive =
1249 ParseColor(pColorValue: &(*pConfiguration)["background-color-inactive"], pAttributeName: "background-color-inactive", DefaultColor: ColorRGBA(0.0f, 0.0f, 0.0f, 0.25f));
1250 if(!ParsedBackgroundColorInactive.has_value())
1251 {
1252 json_value_free(pConfiguration);
1253 return false;
1254 }
1255
1256 std::optional<ColorRGBA> ParsedBackgroundColorActive =
1257 ParseColor(pColorValue: &(*pConfiguration)["background-color-active"], pAttributeName: "background-color-active", DefaultColor: ColorRGBA(0.2f, 0.2f, 0.2f, 0.25f));
1258 if(!ParsedBackgroundColorActive.has_value())
1259 {
1260 json_value_free(pConfiguration);
1261 return false;
1262 }
1263
1264 const json_value &TouchButtons = (*pConfiguration)["touch-buttons"];
1265 if(TouchButtons.type != json_array)
1266 {
1267 log_error("touch_controls", "Failed to parse configuration: attribute 'touch-buttons' must specify an array");
1268 json_value_free(pConfiguration);
1269 return false;
1270 }
1271
1272 std::vector<CTouchButton> vParsedTouchButtons;
1273 vParsedTouchButtons.reserve(n: TouchButtons.u.array.length);
1274 for(unsigned ButtonIndex = 0; ButtonIndex < TouchButtons.u.array.length; ++ButtonIndex)
1275 {
1276 std::optional<CTouchButton> ParsedButton = ParseButton(pButtonObject: &TouchButtons[ButtonIndex]);
1277 if(!ParsedButton.has_value())
1278 {
1279 log_error("touch_controls", "Failed to parse configuration: could not parse button at index '%d'", ButtonIndex);
1280 json_value_free(pConfiguration);
1281 return false;
1282 }
1283
1284 vParsedTouchButtons.push_back(x: std::move(ParsedButton.value()));
1285 }
1286
1287 // Parsing successful. Apply parsed configuration.
1288 m_DirectTouchIngame = ParsedDirectTouchIngame.value();
1289 m_DirectTouchSpectate = ParsedDirectTouchSpectate.value();
1290 m_BackgroundColorInactive = ParsedBackgroundColorInactive.value();
1291 m_BackgroundColorActive = ParsedBackgroundColorActive.value();
1292
1293 m_vTouchButtons = std::move(vParsedTouchButtons);
1294 for(CTouchButton &TouchButton : m_vTouchButtons)
1295 {
1296 TouchButton.UpdatePointers();
1297 TouchButton.UpdateScreenFromUnitRect();
1298 }
1299
1300 json_value_free(pConfiguration);
1301
1302 // If successfully parsing buttons, deselect it.
1303 m_pSelectedButton = nullptr;
1304 m_pSampleButton = nullptr;
1305 m_UnsavedChanges = false;
1306
1307 return true;
1308}
1309
1310std::optional<CTouchControls::EDirectTouchIngameMode> CTouchControls::ParseDirectTouchIngameMode(const json_value *pModeValue)
1311{
1312 // TODO: Remove json_boolean backwards compatibility
1313 const json_value &DirectTouchIngame = *pModeValue;
1314 if(DirectTouchIngame.type != json_boolean && DirectTouchIngame.type != json_string)
1315 {
1316 log_error("touch_controls", "Failed to parse configuration: attribute 'direct-touch-ingame' must specify a string");
1317 return {};
1318 }
1319 if(DirectTouchIngame.type == json_boolean)
1320 {
1321 return DirectTouchIngame.u.boolean ? EDirectTouchIngameMode::ACTION : EDirectTouchIngameMode::DISABLED;
1322 }
1323 EDirectTouchIngameMode ParsedDirectTouchIngame = EDirectTouchIngameMode::NUM_STATES;
1324 for(int CurrentMode = (int)EDirectTouchIngameMode::DISABLED; CurrentMode < (int)EDirectTouchIngameMode::NUM_STATES; ++CurrentMode)
1325 {
1326 if(str_comp(a: DirectTouchIngame.u.string.ptr, b: DIRECT_TOUCH_INGAME_MODE_NAMES[CurrentMode]) == 0)
1327 {
1328 ParsedDirectTouchIngame = (EDirectTouchIngameMode)CurrentMode;
1329 break;
1330 }
1331 }
1332 if(ParsedDirectTouchIngame == EDirectTouchIngameMode::NUM_STATES)
1333 {
1334 log_error("touch_controls", "Failed to parse configuration: attribute 'direct-touch-ingame' specifies unknown value '%s'", DirectTouchIngame.u.string.ptr);
1335 return {};
1336 }
1337 return ParsedDirectTouchIngame;
1338}
1339
1340std::optional<CTouchControls::EDirectTouchSpectateMode> CTouchControls::ParseDirectTouchSpectateMode(const json_value *pModeValue)
1341{
1342 // TODO: Remove json_boolean backwards compatibility
1343 const json_value &DirectTouchSpectate = *pModeValue;
1344 if(DirectTouchSpectate.type != json_boolean && DirectTouchSpectate.type != json_string)
1345 {
1346 log_error("touch_controls", "Failed to parse configuration: attribute 'direct-touch-spectate' must specify a string");
1347 return {};
1348 }
1349 if(DirectTouchSpectate.type == json_boolean)
1350 {
1351 return DirectTouchSpectate.u.boolean ? EDirectTouchSpectateMode::AIM : EDirectTouchSpectateMode::DISABLED;
1352 }
1353 EDirectTouchSpectateMode ParsedDirectTouchSpectate = EDirectTouchSpectateMode::NUM_STATES;
1354 for(int CurrentMode = (int)EDirectTouchSpectateMode::DISABLED; CurrentMode < (int)EDirectTouchSpectateMode::NUM_STATES; ++CurrentMode)
1355 {
1356 if(str_comp(a: DirectTouchSpectate.u.string.ptr, b: DIRECT_TOUCH_SPECTATE_MODE_NAMES[CurrentMode]) == 0)
1357 {
1358 ParsedDirectTouchSpectate = (EDirectTouchSpectateMode)CurrentMode;
1359 break;
1360 }
1361 }
1362 if(ParsedDirectTouchSpectate == EDirectTouchSpectateMode::NUM_STATES)
1363 {
1364 log_error("touch_controls", "Failed to parse configuration: attribute 'direct-touch-spectate' specifies unknown value '%s'", DirectTouchSpectate.u.string.ptr);
1365 return {};
1366 }
1367 return ParsedDirectTouchSpectate;
1368}
1369
1370std::optional<ColorRGBA> CTouchControls::ParseColor(const json_value *pColorValue, const char *pAttributeName, std::optional<ColorRGBA> DefaultColor) const
1371{
1372 const json_value &Color = *pColorValue;
1373 if(Color.type == json_none && DefaultColor.has_value())
1374 {
1375 return DefaultColor;
1376 }
1377 if(Color.type != json_string)
1378 {
1379 log_error("touch_controls", "Failed to parse configuration: attribute '%s' must specify a string", pAttributeName);
1380 return {};
1381 }
1382 std::optional<ColorRGBA> ParsedColor = color_parse<ColorRGBA>(pStr: Color.u.string.ptr);
1383 if(!ParsedColor.has_value())
1384 {
1385 log_error("touch_controls", "Failed to parse configuration: attribute '%s' specifies invalid color value '%s'", pAttributeName, Color.u.string.ptr);
1386 return {};
1387 }
1388 return ParsedColor;
1389}
1390
1391std::optional<CTouchControls::CTouchButton> CTouchControls::ParseButton(const json_value *pButtonObject)
1392{
1393 const json_value &ButtonObject = *pButtonObject;
1394 if(ButtonObject.type != json_object)
1395 {
1396 log_error("touch_controls", "Failed to parse touch button: must be an object");
1397 return {};
1398 }
1399
1400 const auto &&ParsePositionSize = [&](const char *pAttribute, int &ParsedValue, int Min, int Max) {
1401 const json_value &AttributeValue = ButtonObject[pAttribute];
1402 if(AttributeValue.type != json_integer || !in_range<json_int_t>(a: AttributeValue.u.integer, lower: Min, upper: Max))
1403 {
1404 log_error("touch_controls", "Failed to parse touch button: attribute '%s' must specify an integer between '%d' and '%d'", pAttribute, Min, Max);
1405 return false;
1406 }
1407 ParsedValue = AttributeValue.u.integer;
1408 return true;
1409 };
1410 CUnitRect ParsedUnitRect;
1411 if(!ParsePositionSize("w", ParsedUnitRect.m_W, BUTTON_SIZE_MINIMUM, BUTTON_SIZE_MAXIMUM) ||
1412 !ParsePositionSize("h", ParsedUnitRect.m_H, BUTTON_SIZE_MINIMUM, BUTTON_SIZE_MAXIMUM))
1413 {
1414 return {};
1415 }
1416 if(!ParsePositionSize("x", ParsedUnitRect.m_X, 0, BUTTON_SIZE_SCALE - ParsedUnitRect.m_W) ||
1417 !ParsePositionSize("y", ParsedUnitRect.m_Y, 0, BUTTON_SIZE_SCALE - ParsedUnitRect.m_H))
1418 {
1419 return {};
1420 }
1421
1422 const json_value &Shape = ButtonObject["shape"];
1423 if(Shape.type != json_string)
1424 {
1425 log_error("touch_controls", "Failed to parse touch button: attribute 'shape' must specify a string");
1426 return {};
1427 }
1428 EButtonShape ParsedShape = EButtonShape::NUM_SHAPES;
1429 for(int CurrentShape = (int)EButtonShape::RECT; CurrentShape < (int)EButtonShape::NUM_SHAPES; ++CurrentShape)
1430 {
1431 if(str_comp(a: Shape.u.string.ptr, b: SHAPE_NAMES[CurrentShape]) == 0)
1432 {
1433 ParsedShape = (EButtonShape)CurrentShape;
1434 break;
1435 }
1436 }
1437 if(ParsedShape == EButtonShape::NUM_SHAPES)
1438 {
1439 log_error("touch_controls", "Failed to parse touch button: attribute 'shape' specifies unknown value '%s'", Shape.u.string.ptr);
1440 return {};
1441 }
1442
1443 const json_value &Visibilities = ButtonObject["visibilities"];
1444 if(Visibilities.type != json_array)
1445 {
1446 log_error("touch_controls", "Failed to parse touch button: attribute 'visibilities' must specify an array");
1447 return {};
1448 }
1449 std::vector<CButtonVisibility> vParsedVisibilities;
1450 vParsedVisibilities.reserve(n: Visibilities.u.array.length);
1451 for(unsigned VisibilityIndex = 0; VisibilityIndex < Visibilities.u.array.length; ++VisibilityIndex)
1452 {
1453 const json_value &Visibility = Visibilities[VisibilityIndex];
1454 if(Visibility.type != json_string)
1455 {
1456 log_error("touch_controls", "Failed to parse touch button: attribute 'visibilities' does not specify string at index '%d'", VisibilityIndex);
1457 return {};
1458 }
1459 EButtonVisibility ParsedVisibility = EButtonVisibility::NUM_VISIBILITIES;
1460 const bool ParsedParity = Visibility.u.string.ptr[0] != '-';
1461 const char *pVisibilityString = ParsedParity ? Visibility.u.string.ptr : &Visibility.u.string.ptr[1];
1462 for(int CurrentVisibility = (int)EButtonVisibility::INGAME; CurrentVisibility < (int)EButtonVisibility::NUM_VISIBILITIES; ++CurrentVisibility)
1463 {
1464 if(str_comp(a: pVisibilityString, b: m_aVisibilityFunctions[CurrentVisibility].m_pId) == 0)
1465 {
1466 ParsedVisibility = (EButtonVisibility)CurrentVisibility;
1467 break;
1468 }
1469 }
1470 if(ParsedVisibility == EButtonVisibility::NUM_VISIBILITIES)
1471 {
1472 log_error("touch_controls", "Failed to parse touch button: attribute 'visibilities' specifies unknown value '%s' at index '%d'", pVisibilityString, VisibilityIndex);
1473 return {};
1474 }
1475 const bool VisibilityAlreadyUsed = std::any_of(first: vParsedVisibilities.begin(), last: vParsedVisibilities.end(), pred: [&](CButtonVisibility OtherParsedVisibility) {
1476 return OtherParsedVisibility.m_Type == ParsedVisibility;
1477 });
1478 if(VisibilityAlreadyUsed)
1479 {
1480 log_error("touch_controls", "Failed to parse touch button: attribute 'visibilities' specifies duplicate value '%s' at '%d'", pVisibilityString, VisibilityIndex);
1481 return {};
1482 }
1483 vParsedVisibilities.emplace_back(args&: ParsedVisibility, args: ParsedParity);
1484 }
1485
1486 std::unique_ptr<CTouchButtonBehavior> pParsedBehavior = ParseBehavior(pBehaviorObject: &ButtonObject["behavior"]);
1487 if(pParsedBehavior == nullptr)
1488 {
1489 log_error("touch_controls", "Failed to parse touch button: failed to parse attribute 'behavior' (see details above)");
1490 return {};
1491 }
1492
1493 CTouchButton Button(this);
1494 Button.m_UnitRect = ParsedUnitRect;
1495 Button.m_Shape = ParsedShape;
1496 Button.m_vVisibilities = std::move(vParsedVisibilities);
1497 Button.m_pBehavior = std::move(pParsedBehavior);
1498 return Button;
1499}
1500
1501std::unique_ptr<CTouchControls::CTouchButtonBehavior> CTouchControls::ParseBehavior(const json_value *pBehaviorObject)
1502{
1503 const json_value &BehaviorObject = *pBehaviorObject;
1504 if(BehaviorObject.type != json_object)
1505 {
1506 log_error("touch_controls", "Failed to parse touch button behavior: must be an object");
1507 return nullptr;
1508 }
1509
1510 const json_value &BehaviorType = BehaviorObject["type"];
1511 if(BehaviorType.type != json_string)
1512 {
1513 log_error("touch_controls", "Failed to parse touch button behavior: attribute 'type' must specify a string");
1514 return nullptr;
1515 }
1516
1517 if(str_comp(a: BehaviorType.u.string.ptr, b: CPredefinedTouchButtonBehavior::BEHAVIOR_TYPE) == 0)
1518 {
1519 return ParsePredefinedBehavior(pBehaviorObject: &BehaviorObject);
1520 }
1521 else if(str_comp(a: BehaviorType.u.string.ptr, b: CBindTouchButtonBehavior::BEHAVIOR_TYPE) == 0)
1522 {
1523 return ParseBindBehavior(pBehaviorObject: &BehaviorObject);
1524 }
1525 else if(str_comp(a: BehaviorType.u.string.ptr, b: CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE) == 0)
1526 {
1527 return ParseBindToggleBehavior(pBehaviorObject: &BehaviorObject);
1528 }
1529 else
1530 {
1531 log_error("touch_controls", "Failed to parse touch button behavior: attribute 'type' specifies unknown value '%s'", BehaviorType.u.string.ptr);
1532 return nullptr;
1533 }
1534}
1535
1536std::unique_ptr<CTouchControls::CPredefinedTouchButtonBehavior> CTouchControls::ParsePredefinedBehavior(const json_value *pBehaviorObject)
1537{
1538 const json_value &BehaviorObject = *pBehaviorObject;
1539 const json_value &PredefinedId = BehaviorObject["id"];
1540 if(PredefinedId.type != json_string)
1541 {
1542 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'id' must specify a string", CPredefinedTouchButtonBehavior::BEHAVIOR_TYPE);
1543 return nullptr;
1544 }
1545
1546 class CBehaviorFactory
1547 {
1548 public:
1549 const char *m_pId;
1550 std::function<std::unique_ptr<CPredefinedTouchButtonBehavior>(const json_value *pBehaviorObject)> m_Factory;
1551 };
1552 static const CBehaviorFactory BEHAVIOR_FACTORIES[] = {
1553 {.m_pId: CIngameMenuTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CIngameMenuTouchButtonBehavior>(); }},
1554 {.m_pId: CExtraMenuTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [&](const json_value *pBehavior) { return ParseExtraMenuBehavior(pBehaviorObject: pBehavior); }},
1555 {.m_pId: CEmoticonTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CEmoticonTouchButtonBehavior>(); }},
1556 {.m_pId: CSpectateTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CSpectateTouchButtonBehavior>(); }},
1557 {.m_pId: CSwapActionTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CSwapActionTouchButtonBehavior>(); }},
1558 {.m_pId: CUseActionTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CUseActionTouchButtonBehavior>(); }},
1559 {.m_pId: CJoystickActionTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CJoystickActionTouchButtonBehavior>(); }},
1560 {.m_pId: CJoystickAimTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CJoystickAimTouchButtonBehavior>(); }},
1561 {.m_pId: CJoystickFireTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CJoystickFireTouchButtonBehavior>(); }},
1562 {.m_pId: CJoystickHookTouchButtonBehavior::BEHAVIOR_ID, .m_Factory: [](const json_value *pBehavior) { return std::make_unique<CJoystickHookTouchButtonBehavior>(); }}};
1563 for(const CBehaviorFactory &BehaviorFactory : BEHAVIOR_FACTORIES)
1564 {
1565 if(str_comp(a: PredefinedId.u.string.ptr, b: BehaviorFactory.m_pId) == 0)
1566 {
1567 return BehaviorFactory.m_Factory(&BehaviorObject);
1568 }
1569 }
1570
1571 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'id' specifies unknown value '%s'", CPredefinedTouchButtonBehavior::BEHAVIOR_TYPE, PredefinedId.u.string.ptr);
1572 return nullptr;
1573}
1574
1575std::unique_ptr<CTouchControls::CExtraMenuTouchButtonBehavior> CTouchControls::ParseExtraMenuBehavior(const json_value *pBehaviorObject)
1576{
1577 const json_value &BehaviorObject = *pBehaviorObject;
1578 const json_value &MenuNumber = BehaviorObject["number"];
1579 // TODO: Remove json_none backwards compatibility
1580 if(MenuNumber.type != json_none && (MenuNumber.type != json_integer || !in_range<json_int_t>(a: MenuNumber.u.integer, lower: 1, upper: MAX_EXTRA_MENU_NUMBER)))
1581 {
1582 log_error("touch_controls", "Failed to parse touch button behavior of type '%s' and ID '%s': attribute 'number' must specify an integer between '%d' and '%d'",
1583 CPredefinedTouchButtonBehavior::BEHAVIOR_TYPE, CExtraMenuTouchButtonBehavior::BEHAVIOR_ID, 1, MAX_EXTRA_MENU_NUMBER);
1584 return nullptr;
1585 }
1586 int ParsedMenuNumber = MenuNumber.type == json_none ? 0 : (MenuNumber.u.integer - 1);
1587
1588 return std::make_unique<CExtraMenuTouchButtonBehavior>(args&: ParsedMenuNumber);
1589}
1590
1591std::unique_ptr<CTouchControls::CBindTouchButtonBehavior> CTouchControls::ParseBindBehavior(const json_value *pBehaviorObject)
1592{
1593 const json_value &BehaviorObject = *pBehaviorObject;
1594 const json_value &Label = BehaviorObject["label"];
1595 if(Label.type != json_string)
1596 {
1597 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'label' must specify a string", CBindTouchButtonBehavior::BEHAVIOR_TYPE);
1598 return nullptr;
1599 }
1600
1601 const json_value &LabelType = BehaviorObject["label-type"];
1602 if(LabelType.type != json_string && LabelType.type != json_none)
1603 {
1604 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'label-type' must specify a string", CBindTouchButtonBehavior::BEHAVIOR_TYPE);
1605 return {};
1606 }
1607 CButtonLabel::EType ParsedLabelType = CButtonLabel::EType::NUM_TYPES;
1608 if(LabelType.type == json_none)
1609 {
1610 ParsedLabelType = CButtonLabel::EType::PLAIN;
1611 }
1612 else
1613 {
1614 for(int CurrentType = (int)CButtonLabel::EType::PLAIN; CurrentType < (int)CButtonLabel::EType::NUM_TYPES; ++CurrentType)
1615 {
1616 if(str_comp(a: LabelType.u.string.ptr, b: LABEL_TYPE_NAMES[CurrentType]) == 0)
1617 {
1618 ParsedLabelType = (CButtonLabel::EType)CurrentType;
1619 break;
1620 }
1621 }
1622 }
1623 if(ParsedLabelType == CButtonLabel::EType::NUM_TYPES)
1624 {
1625 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'label-type' specifies unknown value '%s'", CBindTouchButtonBehavior::BEHAVIOR_TYPE, LabelType.u.string.ptr);
1626 return {};
1627 }
1628
1629 const json_value &Command = BehaviorObject["command"];
1630 if(Command.type != json_string)
1631 {
1632 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'command' must specify a string", CBindTouchButtonBehavior::BEHAVIOR_TYPE);
1633 return nullptr;
1634 }
1635
1636 return std::make_unique<CBindTouchButtonBehavior>(args: Label.u.string.ptr, args&: ParsedLabelType, args: Command.u.string.ptr);
1637}
1638
1639std::unique_ptr<CTouchControls::CBindToggleTouchButtonBehavior> CTouchControls::ParseBindToggleBehavior(const json_value *pBehaviorObject)
1640{
1641 const json_value &CommandsObject = (*pBehaviorObject)["commands"];
1642 if(CommandsObject.type != json_array || CommandsObject.u.array.length < 2)
1643 {
1644 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': attribute 'commands' must specify an array with at least 2 entries", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE);
1645 return {};
1646 }
1647
1648 std::vector<CTouchControls::CBindToggleTouchButtonBehavior::CCommand> vCommands;
1649 vCommands.reserve(n: CommandsObject.u.array.length);
1650 for(unsigned CommandIndex = 0; CommandIndex < CommandsObject.u.array.length; ++CommandIndex)
1651 {
1652 const json_value &CommandObject = CommandsObject[CommandIndex];
1653 if(CommandObject.type != json_object)
1654 {
1655 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'commands' must specify an array of objects", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex);
1656 return nullptr;
1657 }
1658
1659 const json_value &Label = CommandObject["label"];
1660 if(Label.type != json_string)
1661 {
1662 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'label' must specify a string", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex);
1663 return nullptr;
1664 }
1665
1666 const json_value &LabelType = CommandObject["label-type"];
1667 if(LabelType.type != json_string && LabelType.type != json_none)
1668 {
1669 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'label-type' must specify a string", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex);
1670 return {};
1671 }
1672 CButtonLabel::EType ParsedLabelType = CButtonLabel::EType::NUM_TYPES;
1673 if(LabelType.type == json_none)
1674 {
1675 ParsedLabelType = CButtonLabel::EType::PLAIN;
1676 }
1677 else
1678 {
1679 for(int CurrentType = (int)CButtonLabel::EType::PLAIN; CurrentType < (int)CButtonLabel::EType::NUM_TYPES; ++CurrentType)
1680 {
1681 if(str_comp(a: LabelType.u.string.ptr, b: LABEL_TYPE_NAMES[CurrentType]) == 0)
1682 {
1683 ParsedLabelType = (CButtonLabel::EType)CurrentType;
1684 break;
1685 }
1686 }
1687 }
1688 if(ParsedLabelType == CButtonLabel::EType::NUM_TYPES)
1689 {
1690 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'label-type' specifies unknown value '%s'", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex, LabelType.u.string.ptr);
1691 return {};
1692 }
1693
1694 const json_value &Command = CommandObject["command"];
1695 if(Command.type != json_string)
1696 {
1697 log_error("touch_controls", "Failed to parse touch button behavior of type '%s': failed to parse command at index '%d': attribute 'command' must specify a string", CBindToggleTouchButtonBehavior::BEHAVIOR_TYPE, CommandIndex);
1698 return nullptr;
1699 }
1700 vCommands.emplace_back(args: Label.u.string.ptr, args&: ParsedLabelType, args: Command.u.string.ptr);
1701 }
1702 return std::make_unique<CBindToggleTouchButtonBehavior>(args: std::move(vCommands));
1703}
1704
1705void CTouchControls::WriteConfiguration(CJsonWriter *pWriter)
1706{
1707 pWriter->BeginObject();
1708
1709 pWriter->WriteAttribute(pName: "direct-touch-ingame");
1710 pWriter->WriteStrValue(pValue: DIRECT_TOUCH_INGAME_MODE_NAMES[(int)m_DirectTouchIngame]);
1711
1712 pWriter->WriteAttribute(pName: "direct-touch-spectate");
1713 pWriter->WriteStrValue(pValue: DIRECT_TOUCH_SPECTATE_MODE_NAMES[(int)m_DirectTouchSpectate]);
1714
1715 char aColor[9];
1716 str_format(buffer: aColor, buffer_size: sizeof(aColor), format: "%08X", m_BackgroundColorInactive.PackAlphaLast());
1717 pWriter->WriteAttribute(pName: "background-color-inactive");
1718 pWriter->WriteStrValue(pValue: aColor);
1719
1720 str_format(buffer: aColor, buffer_size: sizeof(aColor), format: "%08X", m_BackgroundColorActive.PackAlphaLast());
1721 pWriter->WriteAttribute(pName: "background-color-active");
1722 pWriter->WriteStrValue(pValue: aColor);
1723
1724 pWriter->WriteAttribute(pName: "touch-buttons");
1725 pWriter->BeginArray();
1726 for(CTouchButton &TouchButton : m_vTouchButtons)
1727 {
1728 TouchButton.WriteToConfiguration(pWriter);
1729 }
1730 pWriter->EndArray();
1731
1732 pWriter->EndObject();
1733}
1734
1735// This is called when the checkbox "Edit touch controls" is selected, so virtual visibility could be set as the real visibility on entering.
1736void CTouchControls::ResetVirtualVisibilities()
1737{
1738 // Update virtual visibilities.
1739 for(int Visibility = (int)EButtonVisibility::INGAME; Visibility < (int)EButtonVisibility::NUM_VISIBILITIES; ++Visibility)
1740 m_aVirtualVisibilities[Visibility] = m_aVisibilityFunctions[Visibility].m_Function();
1741}
1742
1743void CTouchControls::UpdateButtonsEditor(const std::vector<IInput::CTouchFingerState> &vTouchFingerStates)
1744{
1745 std::vector<CUnitRect> vVisibleButtonRects;
1746 const vec2 ScreenSize = CalculateScreenSize();
1747 bool LongPress = false;
1748 for(CTouchButton &TouchButton : m_vTouchButtons)
1749 {
1750 TouchButton.UpdateVisibilityEditor();
1751 }
1752
1753 if(vTouchFingerStates.empty())
1754 m_PreventSaving = false;
1755
1756 // Remove if the finger deleted has released.
1757 if(!m_vDeletedFingerState.empty())
1758 {
1759 const auto &Remove = std::remove_if(first: m_vDeletedFingerState.begin(), last: m_vDeletedFingerState.end(), pred: [&vTouchFingerStates](const auto &TargetState) {
1760 return std::none_of(vTouchFingerStates.begin(), vTouchFingerStates.end(), [&](const auto &State) {
1761 return State.m_Finger == TargetState.m_Finger;
1762 });
1763 });
1764 m_vDeletedFingerState.erase(first: Remove, last: m_vDeletedFingerState.end());
1765 }
1766 // Delete fingers if they are press later. So they cant be the longpress finger.
1767 if(vTouchFingerStates.size() > 1)
1768 {
1769 std::for_each(first: vTouchFingerStates.begin() + 1, last: vTouchFingerStates.end(), f: [&](const auto &State) {
1770 m_vDeletedFingerState.push_back(State);
1771 });
1772 }
1773
1774 // If released, and there is finger on screen, and the "first finger" is not deleted(new finger), then it can be a LongPress candidate.
1775 if(!vTouchFingerStates.empty() && !std::any_of(first: m_vDeletedFingerState.begin(), last: m_vDeletedFingerState.end(), pred: [&vTouchFingerStates](const auto &State) {
1776 return vTouchFingerStates[0].m_Finger == State.m_Finger;
1777 }))
1778 {
1779 // If has different finger, reset the accumulated delta.
1780 if(m_LongPressFingerState.has_value() && (*m_LongPressFingerState).m_Finger != vTouchFingerStates[0].m_Finger)
1781 m_AccumulatedDelta = vec2(0.0f, 0.0f);
1782 // Update the LongPress candidate state.
1783 m_LongPressFingerState = vTouchFingerStates[0];
1784 }
1785 // If no suitable finger for long press, then clear it.
1786 else
1787 {
1788 m_LongPressFingerState = std::nullopt;
1789 }
1790
1791 // Find long press button. LongPress == true means the first fingerstate long pressed.
1792 if(m_LongPressFingerState.has_value())
1793 {
1794 m_AccumulatedDelta += (*m_LongPressFingerState).m_Delta;
1795 // If slided, then delete.
1796 if(length(a: m_AccumulatedDelta) > 0.005f)
1797 {
1798 m_AccumulatedDelta = vec2(0.0f, 0.0f);
1799 m_vDeletedFingerState.push_back(x: *m_LongPressFingerState);
1800 m_LongPressFingerState = std::nullopt;
1801 m_PreventSaving = true;
1802 }
1803 // Till now, this else contains: if the finger hasn't slided, have no fingers that remain pressed down when it pressed, hasn't been a longpress already, the candidate is always the first finger.
1804 else
1805 {
1806 const auto Now = time_get_nanoseconds();
1807 if(!m_PreventSaving && Now - (*m_LongPressFingerState).m_PressTime > LONG_TOUCH_DURATION)
1808 {
1809 LongPress = true;
1810 m_vDeletedFingerState.push_back(x: *m_LongPressFingerState);
1811 // LongPress will be used this frame for sure, so reset delta.
1812 m_AccumulatedDelta = vec2(0.0f, 0.0f);
1813 }
1814 }
1815 }
1816
1817 // Update active and zoom fingerstate. The first finger will be used for moving button.
1818 if(!vTouchFingerStates.empty())
1819 m_ActiveFingerState = vTouchFingerStates[0];
1820 else
1821 {
1822 m_ActiveFingerState = std::nullopt;
1823 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
1824 m_pSampleButton->m_UnitRect = (*m_ShownRect);
1825 }
1826 // Only the second finger will be used for zooming button.
1827 if(vTouchFingerStates.size() > 1)
1828 {
1829 // If zoom finger is pressed now, reset the zoom startpos
1830 if(!m_ZoomFingerState.has_value())
1831 m_ZoomStartPos = m_ActiveFingerState.value().m_Position - vTouchFingerStates[1].m_Position;
1832 m_ZoomFingerState = vTouchFingerStates[1];
1833 m_PreventSaving = true;
1834
1835 // If Zooming started, update it's x,y value so it's width and height could be calculated correctly.
1836 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
1837 {
1838 m_pSampleButton->m_UnitRect.m_X = m_ShownRect->m_X;
1839 m_pSampleButton->m_UnitRect.m_Y = m_ShownRect->m_Y;
1840 }
1841 }
1842 else
1843 {
1844 m_ZoomFingerState = std::nullopt;
1845 m_ZoomStartPos = vec2(0.0f, 0.0f);
1846 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
1847 {
1848 m_pSampleButton->m_UnitRect.m_W = m_ShownRect->m_W;
1849 m_pSampleButton->m_UnitRect.m_H = m_ShownRect->m_H;
1850 }
1851 }
1852 for(auto &TouchButton : m_vTouchButtons)
1853 {
1854 if(TouchButton.m_VisibilityCached)
1855 {
1856 if(m_pSelectedButton == &TouchButton)
1857 continue;
1858 // Only Long Pressed finger "in visible button" is used for selecting a button.
1859 if(LongPress && !vTouchFingerStates.empty() && TouchButton.IsInside(TouchPosition: (*m_LongPressFingerState).m_Position * ScreenSize))
1860 {
1861 // If m_pSelectedButton changes, Confirm if saving changes, then change.
1862 // LongPress used.
1863 LongPress = false;
1864 // Note: Even after the popup is opened by ChangeSelectedButtonWhile..., the fingerstate still exists. So we have to add it to m_vDeletedFingerState.
1865 m_vDeletedFingerState.push_back(x: *m_LongPressFingerState);
1866 m_LongPressFingerState = std::nullopt;
1867 if(m_UnsavedChanges)
1868 {
1869 // Update sample button before saving, or sample button's position value might be not updated.
1870 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
1871 m_pSampleButton->m_UnitRect = *m_ShownRect;
1872 m_PopupParam.m_KeepMenuOpen = false;
1873 m_PopupParam.m_pOldSelectedButton = m_pSelectedButton;
1874 m_PopupParam.m_pNewSelectedButton = &TouchButton;
1875 m_PopupParam.m_PopupType = EPopupType::BUTTON_CHANGED;
1876 GameClient()->m_Menus.SetActive(true);
1877 // End the function.
1878 return;
1879 }
1880 m_pSelectedButton = &TouchButton;
1881 // Update illegal position when Long press the button. Or later it will keep saying unsavedchanges.
1882 if(IsRectOverlapping(MyRect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape))
1883 {
1884 TouchButton.m_UnitRect = UpdatePosition(MyRect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape);
1885 m_UnsavedChanges = true;
1886 if(TouchButton.m_UnitRect.m_X == -1)
1887 {
1888 m_PopupParam.m_PopupType = EPopupType::NO_SPACE;
1889 m_PopupParam.m_KeepMenuOpen = true;
1890 GameClient()->m_Menus.SetActive(true);
1891 return;
1892 }
1893 TouchButton.UpdateScreenFromUnitRect();
1894 }
1895 m_aIssueParam[(int)EIssueType::CACHE_SETTINGS].m_pTargetButton = m_pSelectedButton;
1896 m_aIssueParam[(int)EIssueType::CACHE_SETTINGS].m_Resolved = false;
1897 RemakeSampleButton();
1898 UpdateSampleButton(SrcButton: *m_pSelectedButton);
1899 // Don't insert the long pressed button. It is selected button now.
1900 continue;
1901 }
1902 // Insert visible but not selected buttons.
1903 vVisibleButtonRects.emplace_back(args: CalculateHitbox(Rect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape));
1904 }
1905 // If selected button not visible, unselect it.
1906 else if(m_pSelectedButton == &TouchButton && !GameClient()->m_Menus.IsActive())
1907 {
1908 m_PopupParam.m_PopupType = EPopupType::BUTTON_INVISIBLE;
1909 GameClient()->m_Menus.SetActive(true);
1910 return;
1911 }
1912 }
1913
1914 // Nothing left to do if no button selected.
1915 if(m_pSampleButton == nullptr)
1916 return;
1917
1918 // If LongPress == true, LongPress finger has to be outside of all visible buttons.(Except m_pSampleButton. This button hasn't been checked)
1919 if(LongPress)
1920 {
1921 // LongPress should be set to false, but to pass clang-tidy check, this shouldn't be set now
1922 // LongPress = false;
1923 bool IsInside = CalculateScreenFromUnitRect(Unit: *m_ShownRect).Inside(Point: m_LongPressFingerState->m_Position * ScreenSize);
1924 m_vDeletedFingerState.push_back(x: *m_LongPressFingerState);
1925 m_LongPressFingerState = std::nullopt;
1926 if(m_UnsavedChanges && !IsInside)
1927 {
1928 m_pSampleButton->m_UnitRect = *m_ShownRect;
1929 m_PopupParam.m_pNewSelectedButton = nullptr;
1930 m_PopupParam.m_pOldSelectedButton = m_pSelectedButton;
1931 m_PopupParam.m_KeepMenuOpen = false;
1932 m_PopupParam.m_PopupType = EPopupType::BUTTON_CHANGED;
1933 GameClient()->m_Menus.SetActive(true);
1934 }
1935 else if(!IsInside)
1936 {
1937 m_UnsavedChanges = false;
1938 ResetButtonPointers();
1939 // No need for caching settings issue. So the issue is set to finished.
1940 m_aIssueParam[(int)EIssueType::CACHE_SETTINGS].m_Resolved = true;
1941 m_aIssueParam[(int)EIssueType::SAVE_SETTINGS].m_Resolved = true;
1942 m_aIssueParam[(int)EIssueType::CACHE_POSITION].m_Resolved = true;
1943 }
1944 }
1945
1946 if(m_pSampleButton != nullptr)
1947 {
1948 if(m_ActiveFingerState.has_value() && m_ZoomFingerState == std::nullopt)
1949 {
1950 vec2 UnitXYDelta = m_ActiveFingerState->m_Delta * BUTTON_SIZE_SCALE;
1951 m_pSampleButton->m_UnitRect.m_X += UnitXYDelta.x;
1952 m_pSampleButton->m_UnitRect.m_Y += UnitXYDelta.y;
1953 m_ShownRect = FindPositionXY(vVisibleButtonRects, MyRect: CalculateHitbox(Rect: m_pSampleButton->m_UnitRect, Shape: m_pSampleButton->m_Shape));
1954 if(m_pSelectedButton != nullptr)
1955 {
1956 unsigned Movement = std::abs(x: m_pSelectedButton->m_UnitRect.m_X - m_ShownRect->m_X) + std::abs(x: m_pSelectedButton->m_UnitRect.m_Y - m_ShownRect->m_Y);
1957 if(Movement > 10000)
1958 {
1959 // Moved a lot, meaning changes made.
1960 m_UnsavedChanges = true;
1961 }
1962 }
1963 }
1964 else if(m_ActiveFingerState.has_value() && m_ZoomFingerState.has_value())
1965 {
1966 m_ShownRect = m_pSampleButton->m_UnitRect;
1967 vec2 UnitWHDelta;
1968 UnitWHDelta.x = (std::abs(x: m_ActiveFingerState.value().m_Position.x - m_ZoomFingerState.value().m_Position.x) - std::abs(x: m_ZoomStartPos.x)) * BUTTON_SIZE_SCALE;
1969 UnitWHDelta.y = (std::abs(x: m_ActiveFingerState.value().m_Position.y - m_ZoomFingerState.value().m_Position.y) - std::abs(x: m_ZoomStartPos.y)) * BUTTON_SIZE_SCALE;
1970 m_ShownRect->m_W = m_pSampleButton->m_UnitRect.m_W + UnitWHDelta.x;
1971 m_ShownRect->m_H = m_pSampleButton->m_UnitRect.m_H + UnitWHDelta.y;
1972 m_ShownRect->m_W = std::clamp(val: m_ShownRect->m_W, lo: BUTTON_SIZE_MINIMUM, hi: BUTTON_SIZE_MAXIMUM);
1973 m_ShownRect->m_H = std::clamp(val: m_ShownRect->m_H, lo: BUTTON_SIZE_MINIMUM, hi: BUTTON_SIZE_MAXIMUM);
1974 if(m_ShownRect->m_W + m_ShownRect->m_X > BUTTON_SIZE_SCALE)
1975 m_ShownRect->m_W = BUTTON_SIZE_SCALE - m_ShownRect->m_X;
1976 if(m_ShownRect->m_H + m_ShownRect->m_Y > BUTTON_SIZE_SCALE)
1977 m_ShownRect->m_H = BUTTON_SIZE_SCALE - m_ShownRect->m_Y;
1978 // Clamp the biggest W and H so they won't overlap with other buttons. Known as "FindPositionWH".
1979 std::optional<int> BiggestW;
1980 std::optional<int> BiggestH;
1981 std::optional<int> LimitH, LimitW;
1982 for(const auto &Rect : vVisibleButtonRects)
1983 {
1984 // If Overlap
1985 if(!(Rect.m_X + Rect.m_W <= m_ShownRect->m_X || m_ShownRect->m_X + m_ShownRect->m_W <= Rect.m_X || Rect.m_Y + Rect.m_H <= m_ShownRect->m_Y || m_ShownRect->m_Y + m_ShownRect->m_H <= Rect.m_Y))
1986 {
1987 // Calculate the biggest Height and Width it could have.
1988 LimitH = Rect.m_Y - m_ShownRect->m_Y;
1989 LimitW = Rect.m_X - m_ShownRect->m_X;
1990 if(LimitH < BUTTON_SIZE_MINIMUM)
1991 LimitH = std::nullopt;
1992 if(LimitW < BUTTON_SIZE_MINIMUM)
1993 LimitW = std::nullopt;
1994 if(LimitH.has_value() && LimitW.has_value())
1995 {
1996 if(std::abs(x: *LimitH - m_ShownRect->m_H) < std::abs(x: *LimitW - m_ShownRect->m_W))
1997 {
1998 BiggestH = std::min(a: *LimitH, b: BiggestH.value_or(u: BUTTON_SIZE_SCALE));
1999 }
2000 else
2001 {
2002 BiggestW = std::min(a: *LimitW, b: BiggestW.value_or(u: BUTTON_SIZE_SCALE));
2003 }
2004 }
2005 else
2006 {
2007 if(LimitH.has_value())
2008 BiggestH = std::min(a: *LimitH, b: BiggestH.value_or(u: BUTTON_SIZE_SCALE));
2009 else if(LimitW.has_value())
2010 BiggestW = std::min(a: *LimitW, b: BiggestW.value_or(u: BUTTON_SIZE_SCALE));
2011 else
2012 {
2013 /*
2014 * LimitH and W can be nullopt at the same time, because two buttons may be overlapping.
2015 * Holding for long press while another finger is pressed.
2016 * Then it will instantly enter zoom mode while buttons are overlapping with each other.
2017 */
2018 m_ShownRect = FindPositionXY(vVisibleButtonRects, MyRect: CalculateHitbox(Rect: m_pSampleButton->m_UnitRect, Shape: m_pSampleButton->m_Shape));
2019 BiggestW = std::nullopt;
2020 BiggestH = std::nullopt;
2021 break;
2022 }
2023 }
2024 }
2025 }
2026 m_ShownRect->m_W = BiggestW.value_or(u&: m_ShownRect->m_W);
2027 m_ShownRect->m_H = BiggestH.value_or(u&: m_ShownRect->m_H);
2028 m_UnsavedChanges = true;
2029 }
2030 // No finger on screen, then show it as is.
2031 else
2032 {
2033 m_ShownRect = m_pSampleButton->m_UnitRect;
2034 }
2035 // Finished moving, no finger on screen.
2036 if(vTouchFingerStates.empty())
2037 {
2038 m_AccumulatedDelta = vec2(0.0f, 0.0f);
2039 std::optional<CUnitRect> OldRect = m_ShownRect;
2040 m_ShownRect = FindPositionXY(vVisibleButtonRects, MyRect: m_pSampleButton->m_UnitRect);
2041 m_UnsavedChanges |= OldRect != m_ShownRect;
2042 m_pSampleButton->m_UnitRect = (*m_ShownRect);
2043 m_aIssueParam[(int)EIssueType::CACHE_POSITION].m_pTargetButton = m_pSampleButton.get();
2044 m_aIssueParam[(int)EIssueType::CACHE_POSITION].m_Resolved = false;
2045 m_pSampleButton->UpdateScreenFromUnitRect();
2046 }
2047 if(m_ShownRect->m_X == -1)
2048 {
2049 m_UnsavedChanges = true;
2050 m_PopupParam.m_PopupType = EPopupType::NO_SPACE;
2051 m_PopupParam.m_KeepMenuOpen = true;
2052 GameClient()->m_Menus.SetActive(true);
2053 return;
2054 }
2055 m_pSampleButton->UpdateScreenFromUnitRect();
2056 }
2057}
2058
2059void CTouchControls::RenderButtonsEditor()
2060{
2061 for(auto &TouchButton : m_vTouchButtons)
2062 {
2063 if(&TouchButton == m_pSelectedButton)
2064 continue;
2065 TouchButton.UpdateVisibilityEditor();
2066 if(TouchButton.m_VisibilityCached || m_PreviewAllButtons)
2067 {
2068 TouchButton.UpdateScreenFromUnitRect();
2069 TouchButton.Render(Selected: false);
2070 }
2071 }
2072
2073 if(m_pSampleButton != nullptr && m_ShownRect.has_value())
2074 {
2075 m_pSampleButton->Render(Selected: true, Rect: m_ShownRect);
2076 }
2077}
2078
2079CTouchControls::CUnitRect CTouchControls::FindPositionXY(std::vector<CUnitRect> &vVisibleButtonRects, CUnitRect MyRect)
2080{
2081 // Border clamp
2082 MyRect.m_X = std::clamp(val: MyRect.m_X, lo: 0, hi: BUTTON_SIZE_SCALE - MyRect.m_W);
2083 MyRect.m_Y = std::clamp(val: MyRect.m_Y, lo: 0, hi: BUTTON_SIZE_SCALE - MyRect.m_H);
2084 // Not overlapping with any rects
2085 {
2086 bool IfOverlap = std::any_of(first: vVisibleButtonRects.begin(), last: vVisibleButtonRects.end(), pred: [&MyRect](const auto &Rect) {
2087 return MyRect.IsOverlap(Other: Rect);
2088 });
2089 if(!IfOverlap)
2090 return MyRect;
2091 }
2092 if(vVisibleButtonRects != m_vLastUpdateRects || MyRect.m_W != m_LastWidth || MyRect.m_H != m_LastHeight)
2093 {
2094 m_LastWidth = MyRect.m_W;
2095 m_LastHeight = MyRect.m_H;
2096 m_vLastUpdateRects = vVisibleButtonRects;
2097 BuildPositionXY(vVisibleButtonRects: m_vLastUpdateRects, MyRect);
2098 }
2099 CUnitRect Result = {.m_X: -1, .m_Y: -1, .m_W: MyRect.m_W, .m_H: MyRect.m_H}, SampleRect;
2100 for(const ivec2 &Target : m_vTargets)
2101 {
2102 SampleRect = {.m_X: Target.x, .m_Y: Target.y, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2103 if(Result.m_X == -1 || MyRect.Distance(Other: Result) > MyRect.Distance(Other: SampleRect))
2104 Result = SampleRect;
2105 }
2106 int BestXPosition = -BUTTON_SIZE_SCALE, BestYPosition = -BUTTON_SIZE_SCALE, Cur = 0;
2107 std::vector<CUnitRect> vTargetRects;
2108 vTargetRects.reserve(n: m_vLastUpdateRects.size());
2109 std::copy_if(first: m_vXSortedRects.begin(), last: m_vXSortedRects.end(), result: std::back_inserter(x&: vTargetRects), pred: [&](const CUnitRect &Rect) {
2110 return !(Rect.m_Y + Rect.m_H <= MyRect.m_Y || MyRect.m_Y + MyRect.m_H <= Rect.m_Y);
2111 });
2112 for(const CUnitRect &Rect : vTargetRects)
2113 {
2114 if(Cur >= Rect.m_X + Rect.m_W)
2115 continue;
2116 SampleRect = {.m_X: Cur, .m_Y: MyRect.m_Y, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2117 if(Cur + MyRect.m_W <= BUTTON_SIZE_SCALE && !SampleRect.IsOverlap(Other: Rect))
2118 {
2119 BestXPosition = std::abs(x: Cur - MyRect.m_X) < std::abs(x: BestXPosition - MyRect.m_X) ? Cur : BestXPosition;
2120 BestXPosition = std::abs(x: Rect.m_X - MyRect.m_W - MyRect.m_X) < std::abs(x: BestXPosition - MyRect.m_X) ? Rect.m_X - MyRect.m_W : BestXPosition;
2121 }
2122 Cur = Rect.m_X + Rect.m_W;
2123 }
2124 if(Cur + MyRect.m_W <= BUTTON_SIZE_SCALE)
2125 {
2126 BestXPosition = std::abs(x: Cur - MyRect.m_X) < std::abs(x: BestXPosition - MyRect.m_X) ? Cur : BestXPosition;
2127 }
2128
2129 vTargetRects.clear();
2130 std::copy_if(first: m_vYSortedRects.begin(), last: m_vYSortedRects.end(), result: std::back_inserter(x&: vTargetRects), pred: [&](const CUnitRect &Rect) {
2131 return !(Rect.m_X + Rect.m_W <= MyRect.m_X || MyRect.m_X + MyRect.m_W <= Rect.m_X);
2132 });
2133 Cur = 0;
2134 for(const CUnitRect &Rect : vTargetRects)
2135 {
2136 if(Cur >= Rect.m_Y + Rect.m_H)
2137 continue;
2138 SampleRect = {.m_X: MyRect.m_X, .m_Y: Cur, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2139 if(Cur + MyRect.m_H <= BUTTON_SIZE_SCALE && !SampleRect.IsOverlap(Other: Rect))
2140 {
2141 BestYPosition = std::abs(x: Cur - MyRect.m_Y) < std::abs(x: BestYPosition - MyRect.m_Y) ? Cur : BestYPosition;
2142 BestYPosition = std::abs(x: Rect.m_Y - MyRect.m_H - MyRect.m_Y) < std::abs(x: BestYPosition - MyRect.m_Y) ? Rect.m_Y - MyRect.m_H : BestYPosition;
2143 }
2144 Cur = Rect.m_Y + Rect.m_H;
2145 }
2146 if(Cur + MyRect.m_H <= BUTTON_SIZE_SCALE)
2147 {
2148 BestYPosition = std::abs(x: Cur - MyRect.m_Y) < std::abs(x: BestYPosition - MyRect.m_Y) ? Cur : BestYPosition;
2149 }
2150
2151 if(BestXPosition != -BUTTON_SIZE_SCALE)
2152 {
2153 SampleRect = {.m_X: BestXPosition, .m_Y: MyRect.m_Y, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2154 if(Result.m_X == -1 || MyRect.Distance(Other: Result) > MyRect.Distance(Other: SampleRect))
2155 Result = SampleRect;
2156 }
2157 if(BestYPosition != -BUTTON_SIZE_SCALE)
2158 {
2159 SampleRect = {.m_X: MyRect.m_X, .m_Y: BestYPosition, .m_W: MyRect.m_W, .m_H: MyRect.m_H};
2160 if(Result.m_X == -1 || MyRect.Distance(Other: Result) > MyRect.Distance(Other: SampleRect))
2161 Result = SampleRect;
2162 }
2163 return Result;
2164}
2165
2166void CTouchControls::BuildPositionXY(std::vector<CUnitRect> vVisibleButtonRects, CUnitRect MyRect)
2167{
2168 m_vTargets.clear();
2169 m_vTargets.reserve(n: vVisibleButtonRects.size() * 4);
2170 m_vXSortedRects = m_vYSortedRects = vVisibleButtonRects;
2171 std::sort(first: m_vXSortedRects.begin(), last: m_vXSortedRects.end(), comp: [](const CUnitRect &Lhs, const CUnitRect &Rhs) {
2172 return Lhs.m_X < Rhs.m_X;
2173 });
2174 std::sort(first: m_vYSortedRects.begin(), last: m_vYSortedRects.end(), comp: [](const CUnitRect &Lhs, const CUnitRect &Rhs) {
2175 return Lhs.m_Y < Rhs.m_Y;
2176 });
2177 std::sort(first: vVisibleButtonRects.begin(), last: vVisibleButtonRects.end(), comp: [](const CUnitRect &Lhs, const CUnitRect &Rhs) {
2178 return Lhs.m_X < Rhs.m_X;
2179 });
2180 class CTree
2181 {
2182 public:
2183 void Init(const std::vector<CUnitRect> &vRects)
2184 {
2185 m_vOrder.reserve(n: vRects.size() * 2);
2186 for(const CUnitRect &Rect : vRects)
2187 {
2188 m_vOrder.emplace_back(args: Rect.m_Y);
2189 m_vOrder.emplace_back(args: Rect.m_Y + Rect.m_H);
2190 }
2191 m_vOrder.emplace_back(args: 0);
2192 m_vOrder.emplace_back(args: BUTTON_SIZE_SCALE);
2193 std::sort(first: m_vOrder.begin(), last: m_vOrder.end());
2194 m_vOrder.erase(first: std::unique(first: m_vOrder.begin(), last: m_vOrder.end()), last: m_vOrder.end());
2195 m_vTree.resize(new_size: m_vOrder.size() * 4, x: {-1, -1, 0, 0});
2196 New(Start: 0, End: m_vOrder.size() - 2, Cur: 0);
2197 m_vZone.reserve(n: m_vTree.size());
2198 }
2199 void New(int Start, int End, unsigned Cur)
2200 {
2201 if(m_vTree[Cur].x != -1)
2202 return;
2203 m_vTree[Cur].x = Start;
2204 m_vTree[Cur].y = End;
2205 m_vTree[Cur].z = 0;
2206 m_vTree[Cur].w = 0;
2207 }
2208 void Add(int Start, int End, unsigned Cur)
2209 {
2210 m_vTree[Cur].z++;
2211 if(m_vTree[Cur].x == Start && m_vTree[Cur].y == End)
2212 {
2213 m_vTree[Cur].w++;
2214 return;
2215 }
2216 int Mid = (m_vTree[Cur].x + m_vTree[Cur].y) / 2;
2217 New(Start: Mid + 1, End: m_vTree[Cur].y, Cur: Cur * 2 + 2);
2218 New(Start: m_vTree[Cur].x, End: Mid, Cur: Cur * 2 + 1);
2219 if(Start <= Mid)
2220 {
2221 Add(Start, End: minimum<int>(a: Mid, b: End), Cur: Cur * 2 + 1);
2222 }
2223 if(End >= Mid + 1)
2224 {
2225 Add(Start: maximum<int>(a: Mid + 1, b: Start), End, Cur: Cur * 2 + 2);
2226 }
2227 }
2228 void Delete(int Start, int End, unsigned Cur)
2229 {
2230 m_vTree[Cur].z--;
2231 if(m_vTree[Cur].x == Start && m_vTree[Cur].y == End)
2232 {
2233 m_vTree[Cur].w--;
2234 return;
2235 }
2236 int Mid = (m_vTree[Cur].x + m_vTree[Cur].y) / 2;
2237 if(Start <= Mid)
2238 {
2239 Delete(Start, End: minimum<int>(a: Mid, b: End), Cur: Cur * 2 + 1);
2240 }
2241 if(End >= Mid + 1)
2242 {
2243 Delete(Start: maximum<int>(a: Mid + 1, b: Start), End, Cur: Cur * 2 + 2);
2244 }
2245 }
2246 void InnerQuery(unsigned Start)
2247 {
2248 std::vector<unsigned> vStack;
2249 vStack.reserve(n: BUTTON_SIZE_SCALE / BUTTON_SIZE_MINIMUM);
2250 vStack.push_back(x: Start);
2251 while(!vStack.empty())
2252 {
2253 unsigned Cur = vStack.back();
2254 vStack.pop_back();
2255 if(m_vTree[Cur].w > 0)
2256 {
2257 m_vZone.emplace_back(args&: m_vTree[Cur].x, args&: m_vTree[Cur].y);
2258 continue;
2259 }
2260 if(m_vTree[Cur].x == m_vTree[Cur].y || m_vTree[Cur].z == 0)
2261 continue;
2262 if(m_vTree[Cur * 2 + 2].x != -1 && m_vTree[Cur * 2 + 2].z > 0)
2263 {
2264 vStack.push_back(x: (Cur << 1) + 2);
2265 }
2266 if(m_vTree[Cur * 2 + 1].x != -1 && m_vTree[Cur * 2 + 1].z > 0)
2267 {
2268 vStack.push_back(x: (Cur << 1) + 1);
2269 }
2270 }
2271 }
2272 std::vector<ivec2> Query(int Length)
2273 {
2274 m_vZone.clear();
2275 InnerQuery(Start: 0);
2276 if(m_vZone.empty())
2277 {
2278 return {{0, BUTTON_SIZE_SCALE}};
2279 }
2280
2281 // Inverse discretization
2282 for(ivec2 &Zone : m_vZone)
2283 {
2284 Zone.x = m_vOrder[Zone.x];
2285 Zone.y = m_vOrder[Zone.y + 1];
2286 }
2287 if(m_vZone[0].x < Length)
2288 m_vZone[0].x = 0;
2289 // Merge segments.
2290 for(unsigned Index = 1; Index < m_vZone.size(); Index++)
2291 {
2292 if(m_vZone[Index - 1].y + Length <= m_vZone[Index].x)
2293 continue;
2294 m_vZone[Index].x = m_vZone[Index - 1].x;
2295 m_vZone[Index - 1].x = -1;
2296 }
2297 if(m_vZone.back().y + Length > BUTTON_SIZE_SCALE)
2298 m_vZone.back().y = BUTTON_SIZE_SCALE;
2299 m_vZone.erase(first: std::remove_if(first: m_vZone.begin(), last: m_vZone.end(), pred: [](const ivec2 &Zone) { return Zone.x == -1; }),
2300 last: m_vZone.end());
2301 // Result stores obstacles, now turn it into free spaces.
2302 std::vector<ivec2> vFree;
2303 vFree.reserve(n: m_vZone.size());
2304 if(m_vZone[0].x != 0)
2305 vFree.emplace_back(args: 0, args&: m_vZone[0].x);
2306 for(unsigned Index = 1; Index < m_vZone.size(); Index++)
2307 {
2308 vFree.emplace_back(args&: m_vZone[Index - 1].y, args&: m_vZone[Index].x);
2309 }
2310 if(m_vZone.back().y != BUTTON_SIZE_SCALE)
2311 vFree.emplace_back(args&: m_vZone.back().y, args: BUTTON_SIZE_SCALE);
2312 return vFree;
2313 }
2314 ivec2 Discretization(int Start, int End)
2315 {
2316 ivec2 Result;
2317 auto It = std::lower_bound(first: m_vOrder.begin(), last: m_vOrder.end(), val: Start);
2318 Result.x = std::distance(first: m_vOrder.begin(), last: It);
2319 It = std::lower_bound(first: m_vOrder.begin(), last: m_vOrder.end(), val: End);
2320 Result.y = std::distance(first: m_vOrder.begin(), last: It) - 1;
2321 return Result;
2322 }
2323
2324 private:
2325 std::vector<int> m_vOrder;
2326 std::vector<ivec4> m_vTree;
2327 std::vector<ivec2> m_vZone;
2328 } Tree;
2329
2330 std::set<int> CandidateX;
2331 for(const CUnitRect &Rect : vVisibleButtonRects)
2332 {
2333 // Rect right border.
2334 int Pos = Rect.m_X + Rect.m_W;
2335 if(Pos + MyRect.m_W <= BUTTON_SIZE_SCALE)
2336 CandidateX.insert(x: Pos);
2337 // Rect left border.
2338 Pos = Rect.m_X - MyRect.m_W;
2339 if(Pos >= 0)
2340 CandidateX.insert(x: Pos);
2341 }
2342 CandidateX.insert(position: CandidateX.begin(), x: 0);
2343 CandidateX.insert(x: BUTTON_SIZE_SCALE - MyRect.m_W);
2344 Tree.Init(vRects: vVisibleButtonRects);
2345
2346 auto Cmp = [&vVisibleButtonRects](int Lhs, int Rhs) -> bool {
2347 return vVisibleButtonRects[Lhs].m_X + vVisibleButtonRects[Lhs].m_W > vVisibleButtonRects[Rhs].m_X + vVisibleButtonRects[Rhs].m_W;
2348 };
2349 std::priority_queue<int, std::vector<int>, decltype(Cmp)> Out(Cmp);
2350
2351 unsigned Index = 0;
2352
2353 for(int CurrentX : CandidateX)
2354 {
2355 while(Index < vVisibleButtonRects.size() && vVisibleButtonRects[Index].m_X < CurrentX + MyRect.m_W)
2356 {
2357 auto Segment = Tree.Discretization(Start: vVisibleButtonRects[Index].m_Y, End: vVisibleButtonRects[Index].m_Y + vVisibleButtonRects[Index].m_H);
2358 Tree.Add(Start: Segment.x, End: Segment.y, Cur: 0);
2359 Out.emplace(args: Index++);
2360 }
2361 while(!Out.empty() && vVisibleButtonRects[Out.top()].m_X + vVisibleButtonRects[Out.top()].m_W <= CurrentX)
2362 {
2363 auto Segment = Tree.Discretization(Start: vVisibleButtonRects[Out.top()].m_Y, End: vVisibleButtonRects[Out.top()].m_Y + vVisibleButtonRects[Out.top()].m_H);
2364 Tree.Delete(Start: Segment.x, End: Segment.y, Cur: 0);
2365 Out.pop();
2366 }
2367 auto Spaces = Tree.Query(Length: MyRect.m_H);
2368 for(ivec2 &Space : Spaces)
2369 {
2370 m_vTargets.emplace_back(args&: CurrentX, args&: Space.x);
2371 m_vTargets.emplace_back(args&: CurrentX, args: Space.y - MyRect.m_H);
2372 }
2373 }
2374}
2375
2376// Create a new button and push_back to m_vTouchButton, then return a pointer.
2377CTouchControls::CTouchButton *CTouchControls::NewButton()
2378{
2379 // Ensure m_pSelectedButton doesn't go wild.
2380 int Target = -1;
2381 if(m_pSelectedButton != nullptr)
2382 Target = std::distance(first: m_vTouchButtons.data(), last: m_pSelectedButton);
2383 CTouchButton NewButton(this);
2384 NewButton.m_pBehavior = std::make_unique<CBindTouchButtonBehavior>(args: "", args: CButtonLabel::EType::PLAIN, args: "");
2385 // So the vector's elements might be moved. If moved all button's m_VisibilityCached will be set to false. This should be prevented.
2386 std::vector<bool> vCachedVisibilities;
2387 vCachedVisibilities.reserve(n: m_vTouchButtons.size());
2388 for(const auto &Button : m_vTouchButtons)
2389 {
2390 vCachedVisibilities.emplace_back(args: Button.m_VisibilityCached);
2391 }
2392 for(unsigned Iterator = 0; Iterator < vCachedVisibilities.size(); Iterator++)
2393 {
2394 m_vTouchButtons[Iterator].m_VisibilityCached = vCachedVisibilities[Iterator];
2395 }
2396 m_vTouchButtons.push_back(x: std::move(NewButton));
2397 if(Target != -1)
2398 m_pSelectedButton = &m_vTouchButtons[Target];
2399 return &m_vTouchButtons.back();
2400}
2401
2402void CTouchControls::DeleteSelectedButton()
2403{
2404 if(m_pSelectedButton != nullptr)
2405 {
2406 auto DeleteIt = m_vTouchButtons.begin() + (m_pSelectedButton - m_vTouchButtons.data());
2407 m_vTouchButtons.erase(position: DeleteIt);
2408 }
2409 ResetButtonPointers();
2410 m_UnsavedChanges = false;
2411}
2412
2413bool CTouchControls::IsRectOverlapping(CUnitRect MyRect, EButtonShape Shape) const
2414{
2415 MyRect = CalculateHitbox(Rect: MyRect, Shape);
2416 for(const auto &TouchButton : m_vTouchButtons)
2417 {
2418 if(m_pSelectedButton == &TouchButton)
2419 continue;
2420 bool IsVisible = std::all_of(first: TouchButton.m_vVisibilities.begin(), last: TouchButton.m_vVisibilities.end(), pred: [&](const auto &Visibility) {
2421 return Visibility.m_Parity == m_aVirtualVisibilities[(int)Visibility.m_Type];
2422 });
2423 if(IsVisible && MyRect.IsOverlap(Other: CalculateHitbox(Rect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape)))
2424 return true;
2425 }
2426 return false;
2427}
2428
2429CTouchControls::CUnitRect CTouchControls::UpdatePosition(CUnitRect MyRect, EButtonShape Shape, bool Ignore)
2430{
2431 MyRect = CalculateHitbox(Rect: MyRect, Shape);
2432 std::vector<CUnitRect> vVisibleButtonRects;
2433 for(const auto &TouchButton : m_vTouchButtons)
2434 {
2435 if(m_pSelectedButton == &TouchButton && !Ignore)
2436 continue;
2437 bool IsVisible = std::all_of(first: TouchButton.m_vVisibilities.begin(), last: TouchButton.m_vVisibilities.end(), pred: [&](const auto &Visibility) {
2438 return Visibility.m_Parity == m_aVirtualVisibilities[(int)Visibility.m_Type];
2439 });
2440 if(!IsVisible)
2441 continue;
2442 vVisibleButtonRects.emplace_back(args: CalculateHitbox(Rect: TouchButton.m_UnitRect, Shape: TouchButton.m_Shape));
2443 }
2444 return FindPositionXY(vVisibleButtonRects, MyRect);
2445}
2446
2447void CTouchControls::ResetButtonPointers()
2448{
2449 m_pSelectedButton = nullptr;
2450 m_pSampleButton = nullptr;
2451 m_ShownRect = std::nullopt;
2452}
2453
2454// After sending the type, the popup should be reset immediately.
2455CTouchControls::CPopupParam CTouchControls::RequiredPopup()
2456{
2457 CPopupParam ReturnPopup = m_PopupParam;
2458 // Reset type so it won't be called for multiple times.
2459 m_PopupParam.m_PopupType = EPopupType::NUM_POPUPS;
2460 return ReturnPopup;
2461}
2462
2463// Return true if any issue is not finished.
2464bool CTouchControls::AnyIssueNotResolved() const
2465{
2466 return std::any_of(first: m_aIssueParam.begin(), last: m_aIssueParam.end(), pred: [](const auto &Issue) {
2467 return !Issue.m_Resolved;
2468 });
2469}
2470
2471std::array<CTouchControls::CIssueParam, (unsigned)CTouchControls::EIssueType::NUM_ISSUES> CTouchControls::Issues()
2472{
2473 std::array<CIssueParam, (unsigned)EIssueType::NUM_ISSUES> aUnresolvedIssues;
2474 for(int Issue = 0; Issue < (int)EIssueType::NUM_ISSUES; Issue++)
2475 {
2476 aUnresolvedIssues[Issue] = m_aIssueParam[Issue];
2477 m_aIssueParam[Issue].m_Resolved = true;
2478 }
2479 return aUnresolvedIssues;
2480}
2481
2482// Make it look like the button, only have bind behavior. This is only used on m_pSampleButton.
2483void CTouchControls::UpdateSampleButton(const CTouchButton &SrcButton)
2484{
2485 dbg_assert(m_pSampleButton != nullptr, "Sample button not created");
2486 m_pSampleButton->m_UnitRect = SrcButton.m_UnitRect;
2487 m_pSampleButton->m_Shape = SrcButton.m_Shape;
2488 m_pSampleButton->m_vVisibilities = SrcButton.m_vVisibilities;
2489 CButtonLabel Label = SrcButton.m_pBehavior->GetLabel();
2490 m_pSampleButton->m_pBehavior = std::make_unique<CBindTouchButtonBehavior>(args&: Label.m_pLabel, args&: Label.m_Type, args: "");
2491 m_pSampleButton->UpdatePointers();
2492 m_pSampleButton->m_UnitRect = CalculateHitbox(Rect: m_pSampleButton->m_UnitRect, Shape: m_pSampleButton->m_Shape);
2493 m_pSampleButton->UpdateScreenFromUnitRect();
2494}
2495
2496std::vector<CTouchControls::CTouchButton *> CTouchControls::GetButtonsEditor()
2497{
2498 std::vector<CTouchButton *> vpButtons;
2499 vpButtons.reserve(n: m_vTouchButtons.size());
2500 for(auto &TouchButton : m_vTouchButtons)
2501 {
2502 TouchButton.UpdateVisibilityEditor();
2503 vpButtons.emplace_back(args: &TouchButton);
2504 }
2505 return vpButtons;
2506}
2507
2508float CTouchControls::CUnitRect::Distance(const CUnitRect &Other) const
2509{
2510 vec2 Delta;
2511 Delta.x = Other.m_X + Other.m_W / 2.0f - m_X - m_W / 2.0f;
2512 Delta.y = Other.m_Y + Other.m_H / 2.0f - m_Y - m_H / 2.0f;
2513 return length(a: Delta / BUTTON_SIZE_SCALE);
2514}
2515