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