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